【问题标题】:How to translate this curl post of an actual file to python request?如何将实际文件的这个 curl 帖子转换为 python 请求?
【发布时间】:2014-01-23 15:25:36
【问题描述】:

我已经彻底搜索了stackoverflow,但我找不到这个问题的答案。

我正在尝试为 asana API python wrapper 做出贡献。这个想法是将文件作为任务的附件发布。

在 asana API docs 中,指定上传的文件“需要是实际文件,而不是字节流。”

我有一个这样的 curl 请求:

curl -u <api_key>: --form "file=@file.txt" https://app.asana.com/api/1.0/tasks/1337/attachments

它工作得很好。

我现在打算用request 做所有事情。在请求文档中,他们谈论的只是“上传多部分编码的文件”。

所以这是我的实际问题:

  1. “上传多部分编码的文件”是否与文件“需要是实际文件,而不是字节流”冲突?

  2. 如何正确地将工作 curl 转换为请求帖子?

我的目标是

request.post('https://app.asana.com/api/1.0/tasks/task_id/attachments', auth=(<api_key>, ""), data={'file': open('valid_path_to_file.ext', 'rb')})

运行时,我得到 ​​p>

{"errors":[{"message":"file: File is not an object"}]}

来自体式。

【问题讨论】:

  • 我已经能够解决问题了。错误在data={'file': open('valid_path_to_file.ext', 'rb')}。应该是files={'file': open('valid_path_to_file.ext', 'rb')}。相当琐碎。

标签: python post curl python-requests asana


【解决方案1】:

您可以将files 参数传递给requests.post 以进行表单编码文件上传。请参见下面的示例:

import requests

KEY = ''
TASK_ID = ''
url = 'https://app.asana.com/api/1.0/tasks/{0}/attachments'.format(TASK_ID)

with open('file.txt') as f:
    files = {'file': f.read()}
    r = requests.post(url, auth=(KEY, ''), files=files)

print(r.status_code)
print(r.json())

【讨论】:

    【解决方案2】:

    这可能完全相同,但是您是否尝试在请求网站上的 data 参数之外分配 files 参数:

    url = 'http://httpbin.org/post'
    files = {'file': open('report.xls', 'rb')}
    r = requests.post(url, files=files)
    

    http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests

    【讨论】:

    • 不,这没有什么区别。事实上,我已经按照您建议的方式实现了它,并且只是针对问题“转述”了它。
    • 对不起,没有看到你的答案。但你的应该工作:)
    猜你喜欢
    • 2019-07-31
    • 2019-06-28
    • 2020-05-31
    • 2023-02-14
    • 1970-01-01
    • 2020-09-08
    • 2016-01-30
    • 2020-03-18
    相关资源
    最近更新 更多