flask post JSON 数据获取方式总结

服务端代码:

import base64
import io
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from keras.applications.resnet50 import preprocess_input, decode_predictions
import numpy as np
import urllib

import json
from flask import Flask
from flask import request
app = Flask(__name__)

model = ResNet50(weights='imagenet')


def picture_recognition_base64(img_base64):
    ret = []
    img = io.BytesIO(base64.b64decode(img_base64))
    img = image.load_img(img, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    result = decode_predictions(preds, top=5)[0]
    for item in result:
        ret.append({'name': item[1], 'sim': str(item[2])})
    return ret

def picture_recognition(url):
    ret = []
    img = io.BytesIO(urllib.request.urlopen(url).read())
    img = image.load_img(img, target_size=(224, 224))
    x = image.img_to_array(img)
    x = np.expand_dims(x, axis=0)
    x = preprocess_input(x)
    preds = model.predict(x)
    result = decode_predictions(preds, top=5)[0]
    for item in result:
        ret.append({'name': item[1], 'sim': str(item[2])})
    return ret


@app.route('/url', methods=['GET', 'POST'])
def route_url():
    if request.method == 'POST':
        data = request.get_data()
        print(data)
        json_data = json.loads(data.decode("utf-8"))
        print(json_data)
        img_url = json_data.get("img_url")
        result = picture_recognition(img_url)
        print(json.dumps(result))
        return json.dumps(result)

@app.route('/base64', methods=['GET', 'POST'])
def route_base64():
    if request.method == 'POST':
        data = request.get_data()
        print(data)
        json_data = json.loads(data.decode("utf-8"))
        print(json_data)

        img_base64 = json_data.get("img_base64")
        result = picture_recognition_base64(img_base64)
        print(json.dumps(result))
        return json.dumps(result)

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=22222, debug=False)

测试代码:

window cmd:  curl -X post --data {\"img_url\":\"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=68222350,3999791223&fm=27&gp=0.jpg\"} http://172.0.0.1:22222/url

linux shell: curl -X post --data '{"img_url":"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=68222350,3999791223&fm=27&gp=0.jpg"}' http://172.0.0.1:22222/url




已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页