Python调用Slack API的files.list接口无法获取指定频道文件
问题:Python调用Slack API files.list无法获取文件,Postman却可以
原本正常运行的Python函数,用于从指定Slack频道获取文件,数月前失效。用Postman测试同一Slack API(files.list)请求,能获取包含3个文件的数组,但Python代码返回空文件数组。已确认应用有该频道的访问权限,且Python与Postman使用的凭证、频道信息完全一致。
原失效代码
import requests import json apiBase = "https://slack.com/api/" accesToken = "Bearer xoxb-<secret>" requestData = { "channel": "<obscured>" } r = requests.post(apiBase + "files.list", headers={'Authorization': accesToken, 'Content-Type': 'application/json; charset=utf-8'}, data=requestData) try: response = json.loads(r.text) except: print("Read error") isError = True if(not 'files' in response): if('error' in response): print(response['error']) if('warning' in response): print(response['warning']) isError = True files = response['files'] files.sort(key=lambda x:x['timestamp']) count = len(files) print(str(r)) print(str(r.request.body)) print(str(r.request.headers['Content-Type'])) print(str(r.text))
代码执行结果
<Response [200]> channel=<secret> application/json; charset=utf-8 {"ok":true,"files":[],"paging":{"count":100,"total":0,"page":1,"pages":0}} Process finished with exit code 0
问题原因
从执行结果里的channel=<secret>可以看出,虽然代码里设置了Content-Type为application/json,但使用data=requestData参数时,requests会把字典自动编码为表单格式的请求体,而非JSON格式。而Slack API的files.list接口需要接收JSON格式的请求体,Postman是正确发送JSON格式,所以能获取到文件数据,Python代码则因为请求体格式不对,返回了空文件列表。
解决方案
将data=requestData替换为json=requestData,requests会自动将字典序列化为JSON格式的请求体,并且自动设置正确的Content-Type(也可以保留原headers,但使用json参数更简洁稳妥)。
修改后的代码
import requests import json apiBase = "https://slack.com/api/" accesToken = "Bearer xoxb-<secret>" requestData = { "channel": "<obscured>" } # 使用json参数替代data参数 r = requests.post(apiBase + "files.list", headers={'Authorization': accesToken}, json=requestData) try: response = json.loads(r.text) except: print("Read error") isError = True if(not 'files' in response): if('error' in response): print(response['error']) if('warning' in response): print(response['warning']) isError = True files = response['files'] files.sort(key=lambda x:x['timestamp']) count = len(files) print(str(r)) print(str(r.request.body)) print(str(r.request.headers['Content-Type'])) print(str(r.text))
修改后重新执行,就能正确获取到频道中的文件数组了。
内容的提问来源于stack exchange,提问作者Jeroen
相关产品推荐
相关产品推荐

