如何使用python的Request库进行带有附件和参数的API调用 [英] how to use python's Request library to make an API call with an attachment and a parameter

查看:194
本文介绍了如何使用python的Request库进行带有附件和参数的API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用请求库来测试ReST API。尝试转换以下cURL以请求库调用时遇到问题。

I am using the Request library to test ReST APIs. I am facing a problem while trying to trasform the below cURL to request library Call.

curl https://upload.box.com/api/2.0/files/content \
-H授权:承载ACCESS_TOKEN \
-F filename = @ FILE_NAME \
-F parent_id = PARENT_FOLDER_ID

curl https://upload.box.com/api/2.0/files/content \ -H "Authorization: Bearer ACCESS_TOKEN" \ -F filename=@FILE_NAME \ -F parent_id=PARENT_FOLDER_ID

我在此论坛上尝试了许多建议。但是没有任何效果。

I tried many of the suggestions in this forum. But nothing worked.

我在评论后添加的代码是:

The code which I addedd after the comment is:

我写的代码是:

def upload_a_file(url,folder_id,file_name,access_token):
field_values = {\'filename\ ':(文件名,打开( + file_name +,\'rb\'))}
payload = {\'parent_id\': + folder_id +}
request_headers = {'Authorization':'Bearer'+ access_token}
result = requests.post(url,headers = request_headers,data = payload ,files = field_values)
response = result.json()
print response

def upload_a_file(url, folder_id, file_name, access_token): field_values = "{\'filename\': (filename, open("+file_name+", \'rb\'))}" payload = "{\'parent_id\':"+folder_id+"}" request_headers = {'Authorization': 'Bearer '+access_token} result = requests.post(url, headers=request_headers, data=payload, files=field_values) response = result.json() print response

推荐答案

我假设您是说请求库?

如果是这样,这就是我的处理方法。

If so, here is how I do it.

access_token = <user access token>
filename = <name of the file as you want it to appear on Box>
src_file = the actual file path
parent_id = the id of the folder you want to upload to

headers = { 'Authorization' : 'Bearer {0}'.format(access_token) }
url = 'https://upload.box.com/api/2.0/files/content'
files = { 'filename': (filename, open(src_file,'rb')) }
data = { "parent_id": parent_id }
response = requests.post(url, data=data, files=files, headers=headers)
file_info = response.json()

这篇关于如何使用python的Request库进行带有附件和参数的API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆