使用 Python 请求在单个请求中发送文件和 JSON [英] Using Python Requests to send file and JSON in single request

查看:57
本文介绍了使用 Python 请求在单个请求中发送文件和 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 POST 到一个 API(使用 SlimPHP 构建),该 API 接受图像以及 JSON 形式的附加图像元数据.

I'm trying to POST to an API (Build using SlimPHP) which accepts an image along with additional image meta data in the form of JSON.

我已经使用 REST 客户端工具验证了 AP​​I 工作正常,并且可以成功发布到服务.所有数据都正确存储.

I've verified the API works correctly using a REST client tool and can successfully POST to the service. All data is stored correctly.

我现在正在尝试使用 Python 进行 POST - 但是我的 JSON 数据似乎没有保存.

I'm now trying to POST using Python - however my JSON data doesn't appear to be saving.

我的代码:

    data = {'key1': 'value1', 'key2': 'value2'}
    url = 'http://mydomain.com/api/endpoint'
    headers = {'Authorization': 'my-api-key'}
    files = {'file': (FILE, open(PATH, 'rb'), 'image/jpg', {'Expires': '0'})}
    r = requests.post(url, files=files, headers=headers, data=data)

--

我尝试设置其他标题,

即:/

headers = {'Authorization': 'unique-auth-key', 'Content-type': 'multipart/form-data'}

headers = {'Authorization': 'unique-auth-key', 'Content-type': 'application/json'}

这些会导致 500 错误.

These result in a 500 error.

2014 年 7 月 14 日更新:

UPDATE 14/07/2014:

使用 chrome 扩展(Advanced Rest Client)我的 POST 成功 - 这是控制台显示的有效负载:

Using a chrome extension (Advanced Rest Client) my POST is successful - here's what the console shows as the payload:

------WebKitFormBoundarysBpiwrA3hnGPUbMA
Content-Disposition: form-data; name="data"
test
------WebKitFormBoundarysBpiwrA3hnGPUbMA
Content-Disposition: form-data; name="file"; filename="image.jpg"
Content-Type: image/jpeg
------WebKitFormBoundarysBpiwrA3hnGPUbMA--

我不太清楚这意味着什么......

I'm not quite sure what this signifies...

推荐答案

您的问题是您使用图像元数据作为要发布的键/值对的来源.而不是将其作为这些键/值对之一的值发送.

Your problem is that you are using the image metadata as the source of key/value pairs to be posted. Instead of sending it as the value of one of those key/value pairs.

以下代码将发送与您提供的 curl 语句非常相似的请求:

The following code will send a request much like the curl statement you provided:

url = 'my-url.com/api/endpoint'
headers = {'Authorization': 'my-api-key'}
image_metadata = {'key1': 'value1', 'key2': 'value2'}
data = {'name': 'image.jpg', 'data': json.dumps(image_metadata)}
files = {'file': (FILE, open(PATH, 'rb'), 'image/jpg', {'Expires': '0'})}
r = requests.post(url, files=files, headers=headers, data=data)

这篇关于使用 Python 请求在单个请求中发送文件和 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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