我正在编写一个脚本,使用slack api和Python中的请求库从Slack下载文件。无论何时我下载文件,它们都会出现相同的大小(80kb)并且它们都已损坏。
这是我的代码:
def download_file(url, out):
try:
os.stat(out)
except:
os.mkdir(out)
local_filename = out + '\\' + url.split('/')[-1]
print('outputting to file: %s' % local_filename)
response = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
response.raw.decode_content = True
shutil.copyfileobj(response.raw,f)
return local_filename
我已尝试在SO中发布各种不同的方法来下载文件但尚未成功。我还检查了我从Slack API获取的URL,它们是正确的,因为我可以将它们粘贴到浏览器中并下载文件。
任何帮助将不胜感激!
答案 0 :(得分:0)
我发现了我的问题。由于我使用Slack API文件对象中的图像私有URL下载,我需要在带有令牌的基本请求之外添加一个头。要使用请求API执行此操作:
response = request.get(url,stream = True, headers={'Authorization':'Bearer ' + my_token})