简体   繁体   English

如何将实际文件的curl转换为python请求?

[英]How to translate this curl post of an actual file to python request?

I have searched stackoverflow thoroughly, but nowhere could I find an answer to this problem. 我已经对stackoverflow进行了彻底的搜索,但是在任何地方都找不到该问题的答案。

I'm trying to contribute to asana API python wrapper . 我正在尝试为asana API python包装器做出贡献。 The idea is to post a file as an attachment to a task. 想法是将文件作为任务的附件发布。

In the asana API docs , it is specified that the uploaded file "needs to be an actual file, not a stream of bytes." 在asana API 文档中 ,指定上传的文件“需要是实际文件,而不是字节流”。

I have a working curl request like so: 我有一个工作的curl请求,如下所示:

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

Its working just fine. 它的工作很好。

I now intend to do the whole thing with request . 我现在打算做整个事情与要求 In the request docs, all they talk about is "upload Multipart-encoded files". 在请求文档中,他们所讨论的只是“上传经过多部分编码的文件”。

So here's my actual question(s): 所以这是我的实际问题:

  1. Does "upload Multipart-encoded files" conflict with file "needs to be an actual file, not a stream of bytes"? “上传多部分编码文件”是否与文件“需要是实际文件,而不是字节流”冲突?

  2. How do I properly translate the working curl to a request post? 如何正确地将工作卷毛转换为请求帖子?

My go is 我去

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')})

When running it, I get 运行时,我得到

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

from asana. 来自体式。

You can pass a files parameter to requests.post for form encoded file upload. 你可以通过一个files参数requests.post的形式编码的文件上传。 See example below: 请参见下面的示例:

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())

This might be exactly the same, but did you try assigning the files parameter outside of the data parameter like on the request website: 这可能是完全相同的,但是您是否尝试像在请求网站上那样在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 http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM