문제

I have searched stackoverflow thoroughly, but nowhere could I find an answer to this problem.

I'm trying to contribute to asana API python wrapper. 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."

I have a working curl request like so:

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. 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:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top