简体   繁体   English

将图像从python客户端上传到Flask服务器

[英]Uploading an image from python client to a flask server

I am using requests and requests_toolbelt to send an image to the cloud and so far I have something like this 我正在使用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

After it gets to the server, how to I get back a dictionary of something usable? 到达服务器后,如何找回可用字典? The toolbelt docs show only how to post, not how to handle it on the other end. 工具栏文档仅显示如何发布,而在另一端则不显示如何处理。 Any advice? 有什么建议吗?

You can see a working example of Flask server which accepts POSTS like the on you're trying to make on HTTPbin . 您可以看到Flask服务器的一个工作示例,该示例接受POST,例如您尝试在HTTPbin上进行的 If you do something like: 如果您执行以下操作:

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

You'll see that everything in your post should be in that dictionary. 您会看到帖子中的所有内容都应该在该词典中。

Using HTTPBin's source, you can then see that the form section is generated from request.form . 使用HTTPBin的源代码,您可以看到form部分是从request.form生成的。 You can use that to retrieve the rest of your data. 您可以使用它来检索其余数据。 Then you can use request.files to access the image you wish to upload. 然后,您可以使用request.files访问要上传的图像。

The example Flask route handler would look like: Flask路由处理程序示例如下所示:

@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

You should read into Uploading Files documentation though. 不过,您应该阅读“ 上传文件”文档。 It is really invaluable when using common patterns like this in Flask. 当在Flask中使用类似这样的常见模式时,这确实是无价的。

requests-toolbelt can only send the file to the server but it is up to you to save that on the server side and then return meaningful result. requests-toolbelt只能将文件发送到服务器,但是由您自己决定将文件保存在服务器端,然后返回有意义的结果。 You can create a flask endpoint to handle the file upload, return the desired result dictionary as a JSON and then convert the JSON back to dict on the client side with json.loads . 您可以创建一个flask端点来处理文件上传,以JSON形式返回所需的结果字典,然后使用json.loads将JSON转换回客户端的json.loads

@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})

See flask documentation for more info on file uploading. 有关文件上传的更多信息,请参见flask 文档

Also, you need to specify the mime-type while including the image in MultipartEncoder and content-type in the header while making the request. 另外,在发出请求时,您需要指定mime类型,同时在MultipartEncoder包含图像,并在标头中包含content-type。 (I'm not sure you if you can even upload images with MultipartEncoder. I was successful with only the text files.) (我不确定您是否可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM