使用Python requests发送GET请求下载Salesforce报表CSV失败求助
Salesforce报表导出问题解决
问题说明
通过浏览器发送GET请求可从Salesforce下载.csv格式的报表,但使用Python的requests模块复现该操作时,无法生成.csv格式报表也无法将其转为Data Frame。当前仅可使用requests、urllib3库,不可使用simple-salesforce包或Selenium。
现有实现代码
导出请求规则
url = '{0}/{1}?export=1&enc=ISO-8859-1&xf=csv&isdtp=nv'.format(base_url, report_id)
身份认证逻辑
import requests import logging # Function to establish a connection to Salesforce: sforce_connect => function() def sforce_connect(c_id, cs_id, sforce_uname, sforce_pwd): """Function to create a connection with Salesforce. Dependent on the requests module. Args: c_id (str): A string scalar denoting the Consumer (Client) ID. cs_id (str): A string scalar denoting the Consumer (Client) Secret ID sforce_uname (str): A string scalar denoting the user's salesforce username. sforce_pwd (str): A string scalar denoting the user's salesforce password. Returns: (list): A list comprised of the instance_url (str) scalar, and the oauth details (dict). """ # Store the auth url as a string scalar: auth_url => string scalar auth_url = 'https://login.salesforce.com/services/oauth2/token' # Defensively attempt to: try: # Issue a POST request in order to retrieve access token: response => response object response = requests.post(auth_url, data = { 'client_id': c_id, 'client_secret': cs_id, 'grant_type': 'password', 'username': sforce_uname, 'password': sforce_pwd}) # If an error occurs: except Exception as error: # Log the error: str => stdout(logfile) logging.critical("Failed to retrieve Bearer token from Salesforce API, rest of run will be problematic, the " + " error caught: " + repr(error)) # Extract the json from the response: json_res => json object json_res = response.json() # Extract the access token from the json response object: access_token => string scalar access_token = json_res['access_token'] # Extract the token type from the json response object: token_type => string scalar token_type = json_res['token_type'] # Extract the session id: session_id => string scalar session_id = json_res['id'] # A dictionary denoting the Authorisation string required, token type concatenated with the token: auth => dictionary oauth = {'Authorization': ' '.join([token_type, access_token])} # Extract the instance url from the response.json(): instance_url => string scalar instance_url = json_res['instance_url'] # Explicitly define the return object: list => GlobalEnv() return([instance_url, oauth, session_id, access_token]) # Apply the function to establish a connection with salesforce: # instance_url => string scalar, auth => dictionary, session_id => string scalar, access_token => string scalar instance_url, auth, session_id, access_token = sforce_connect( client_id, client_secret, sfdc_user, sfdc_pass )
现有导出代码(失效)
req = requests.get(url, headers = auth) df = pd.read_csv(req.content)
问题原因
当前返回内容为SAML跳转相关的HTML页面,说明请求被Salesforce的单点登录校验拦截,OAuth返回的Authorization头无法通过前端导出接口的身份校验。
解决思路
- 调整请求头,新增
sidcookie,值为OAuth获取的access_token,Salesforce前端导出接口优先识别sid cookie完成身份校验 - 新增
X-SFDC-Request-API: 1请求头,标识当前为API请求,跳过SAML跳转校验逻辑 - 关闭自动重定向,手动处理3xx跳转响应,避免跳转过程中丢失身份校验信息
- 读取响应内容时指定编码为请求参数中设置的ISO-8859-1,使用StringIO包装响应文本避免编码解析错误
修复后代码示例
import pandas as pd from io import StringIO # 构造完整请求头 export_headers = { **auth, "Cookie": f"sid={access_token}", "X-SFDC-Request-API": "1" } # 发起导出请求,关闭自动重定向 resp = requests.get(url, headers=export_headers, allow_redirects=False) # 手动处理跳转逻辑 if 300 <= resp.status_code < 400: redirect_url = resp.headers["Location"] # 相对路径拼接实例域名 if redirect_url.startswith("/"): redirect_url = f"{instance_url}{redirect_url}" resp = requests.get(redirect_url, headers=export_headers) # 转为DataFrame df = pd.read_csv(StringIO(resp.text), encoding="ISO-8859-1")
补充校验点
- 确认构造请求的base_url为OAuth返回的instance_url,而非通用登录域名
- 确认所用账号拥有对应报表的导出权限,关联的Connected App开启了API访问权限
- 若仍触发SAML跳转,可在Salesforce后台将所用Connected App配置为受信任连接,豁免SAML校验
内容的提问来源于stack exchange,提问作者hello_friend
相关产品推荐
相关产品推荐

