【问题标题】:how to use python's Request library to make an API call with an attachment and a parameter如何使用 python 的 Request 库进行带有附件和参数的 API 调用
【发布时间】:2014-09-19 20:47:51
【问题描述】:

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

卷曲https://upload.box.com/api/2.0/files/content\ -H "授权:承载 ACCESS_TOKEN" \ -F 文件名=@FILE_NAME \ -F parent_id=PARENT_FOLDER_ID

我尝试了这个论坛中的许多建议。但没有任何效果。

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

我写的代码是:

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) 响应 = result.json() print response

【问题讨论】:

标签: python-2.7 box-api box boxapiv2


【解决方案1】:

我假设您的意思是 requests 库?

如果是这样,我就是这样做的。

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

【讨论】:

  • 您能否提供更多详细信息...?你在使用请求包吗?您是否验证了您的应用程序?我将修改上述内容以澄清变量。
【解决方案2】:

我按照http://www.snip2code.com/Snippet/67408/Show-progress-bar-when-uploading-a-file 中给出的示例进行操作。

我能够成功调用 API。

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2013-04-02
    • 2014-10-03
    相关资源
    最近更新 更多