Python请求:如何获取和POST一张图片而不保存到驱动器?

Python Requests: how to GET and POST a picture without saving to drive?

我正在研究的 API 有一种方法可以通过请求中的图片文件将图片发送到 /api/pictures/

我想使用 Python 的请求库自动执行一些示例图像,但我不太确定该怎么做。我有一个指向图像的 URL 列表。

rv = requests.get('http://api.randomuser.me')
resp = rv.json()
picture_href = resp['results'][0]['user']['picture']['thumbnail']
rv = requests.get(picture_href)
resp = rv.content
rv = requests.post(prefix + '/api/pictures/', data = resp)

rv.content returns 字节码。我从服务器收到 400 Bad Request 但没有错误消息。我相信我在 rv.content 时 'getting' 图片错误,或者 data = resp 发送错误。我在正确的轨道上吗?如何发送文件?

--编辑--

我把最后一行改成了

rv = requests.post('myapp.com' + '/api/pictures/', files = {'file': resp})

服务器端代码(Flask):

file = request.files['file'] 
if file and allowed_file(file.filename):
    ...
else:
    abort(400, message = 'Picture must exist and be either png, jpg, or jpeg')

服务器中止,状态代码为 400 和上面的消息。我还尝试使用 BytesIO 读取 resp,但没有帮助。

问题是您的数据不是文件,而是字节流。所以它没有 "filename",我怀疑这就是你的服务器代码失败的原因。

尝试在您的请求中发送有效的文件名和正确的 MIME 类型:

files = {'file': ('user.gif', resp, 'image/gif', {'Expires': '0'})}
rv = requests.post('myapp.com' + '/api/pictures/', files = files)

您可以使用 imghdr 来确定您正在处理的图像类型(以获得正确的 mime 类型):

import imghdr

image_type = imghdr.what(None, resp)
# You should improve this logic, by possibly creating a
# dictionary lookup
mime_type = 'image/{}'.format(image_type)