用于发布数据和图像的 Flask API [英] Flask API to post data and image
问题描述
我有点困惑.我想创建可以发布图像的 API,以及与该图像一起的字典.我该怎么做 ?对于一张图片,我可以这样做.如果我想发布另一个不是文件的变量怎么办,比如说变量 meta_data?
I am little confused. I want to create API that can post image, and one dictionary along with that image. How can I do it ? for one image, I can do it like this. What if I want to post another variable which is not a file, lets say variable meta_data?
url = 'http://127.0.0.1:5000/im_size'
my_img = {'image': open('test.jpg', 'rb')}
r = requests.post(url, files=my_img)
我的 API 脚本也应该有什么变化,如下
What change should be in my API script as well which is as follow
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/im_size", methods=["POST"])
def process_image():
file = request.files['image']
# Read the image via file.stream
img = Image.open(file.stream)
return jsonify({'msg': 'success', 'size': [img.width, img.height]})
if __name__ == "__main__":
app.run(debug=True)
推荐答案
requests.post
支持 json参数 为该数据设置正确的内容类型('application/json'
),然后通过 Flask 中的 request.get_json()
方法访问.
requests.post
supports a json argument which sets the correct content type ('application/json'
) for that data to then be accessed via request.get_json()
method in Flask.
但是,当您还提供 files
参数时,会出现这种情况,该参数将内容类型设置为 'multipart/form-data'
.
However this plays up when you're also providing the files
argument, which sets the content type to 'multipart/form-data'
.
在这个线程的帮助下,我找到了解决方案是将您的 JSON 数据作为多部分表单的一部分发送.
With help from this thread I found the solution is to send your JSON data as part of the multipart form.
于是在客户端定义了一个字典,并将其添加到my_img
字典中,如下所示:
So on the client define a dictionary, and add it to the my_img
dict as follows:
import json
meta_data = {'message':'I am a picture', 'another_message':'About to upload'}
my_img = {'image': open('test.jpg', 'rb'),
'json_data': ('j', json.dumps(meta_data), 'application/json')}
然后在服务器端,您还需要import json
并且在您的 process_image
视图函数中,您可以使用以下方法访问该数据:
Then on the server end you'll also need to import json
and within your process_image
view function you can access that data with:
json_data = request.files['json_data']
meta_data = json.load(json_data)
print (meta_data)
print (json_data.filename)
服务器输出:
{'message': 'I am a picture', 'another_message': 'About to upload'}
j
这篇关于用于发布数据和图像的 Flask API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!