将图像从python客户端上载到flask

2024-05-13 06:35:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用requestsrequests_toolbelt将图像发送到云中,到目前为止,我有类似的东西

import requests
import json
from requests_toolbelt import MultipartEncoder

m = MultipartEncoder(
    fields={"user_name":"tom", "password":"tom", "method":"login",
            "location":"landing", "cam_id":"c00001", "datetime":"hammaTime!"
            ,'image': ('filename', open('image.jpg', 'rb'))}
    )
r = requests.post(url, data=m)
print r.text

当它到达服务器后,我如何找回一本有用的字典?toolbelt docs只显示如何发布,而不显示如何在另一端处理它。有什么建议吗?


Tags: namefrom图像imageimportjsonfieldslogin
2条回答

requests-toolbelt只能将文件发送到服务器,但由您在服务器端保存该文件,然后返回有意义的结果。您可以创建一个flask端点来处理文件上传,将所需的结果字典作为JSON返回,然后使用json.loads将JSON转换回客户端的dict。

@app.route('/upload', methods=['POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['image']
        f.save('uploads/uploaded_file')
        # do other stuff with values in request.form
        # and return desired output in JSON format
        return jsonify({'success': True})

有关文件上载的详细信息,请参见flaskdocumentation

此外,在发出请求时,需要指定mime类型,同时在MultipartEncoder中包含图像,在头中包含内容类型。(我不确定你是否能用MultipartEncoder上传图片。我只处理了文本文件。)

m = MultipartEncoder(
    fields={"user_name":"tom", "password":"tom", "method":"login",
            "location":"landing", "cam_id":"c00001", "datetime":"hammaTime!"
            ,'image': ('filename', open('file.txt', 'rb'), 'text/plain')}  # added mime-type here
    )
r = requests.post(url, data=m, headers={'Content-Type': m.content_type})  # added content-type header here

您可以看到Flask服务器的一个工作示例,它接受您试图在HTTPbin上生成的类似于的帖子。如果你这样做:

m = MultipartEncoder(fields=your_fields)
r = requests.post('https://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
print(r.json()['form'])

你会发现你帖子里的所有东西都应该在那本字典里。

使用HTTPBin的源代码,可以看到form部分是从request.form生成的。您可以使用它来检索其余的数据。然后,您可以使用request.files访问要上载的图像。

示例烧瓶路由处理程序如下所示:

@app.route('/upload', methods=['POST'])
def upload_files():
    resp = flask.make_response()
    if authenticate_user(request.form):
        request.files['image'].save('path/to/file.jpg')
        resp.status_code = 204
    else:
        resp.status_code = 411
    return resp

不过,您应该阅读Uploading Files文档。在烧瓶里用这种常见的图案真的很有价值。

相关问题 更多 >