RicardoM.Lu1 2022-12-29 11:35 采纳率: 80.6%
浏览 77
已结题

Flask接口处理post请求时出现问题

Flask接口post请求之后另一边只能收到None
代码能够正确运行,并且使用在接口代码中加入print能够正确输出内容,但是使用测试接口的代码时只能收到None

而且在最后会出现一个"POST / HTTP/1.1" 500 -的信息

这是接口的代码:
import json
import cv2
from PIL import Image
import numpy as np
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from modelscope.outputs import OutputKeys
from flask import request
from flask import jsonify
from flask import Flask,make_response
import base64

face_recognition = pipeline(Tasks.face_recognition, model='damo/cv_ir101_facerecognition_cfglint')

# def face_recognition(image1,image2):
#     emb1 = face_recognition(image1)[OutputKeys.IMG_EMBEDDING]
#     emb2 = face_recognition(image2)[OutputKeys.IMG_EMBEDDING]
#     sim = np.dot(emb1[0], emb2[0])
#     sim=face_recognition(image1, image2)
#     return jsonify(sim)
#     return (f'Face cosine similarity={sim:.3f}, get_img1:{image1}  get_img2:{image2}')


app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
def making_response(json_data):
    response = make_response(jsonify(json_data))
    response.headers['Content-Type'] = 'application/json;charset=UTF-8'
    return response

@app.route("/",methods=["POST"])
def first_post():
    my_json = {"msg": None,
               "sim": None
                }
    data = request.get_data()
    if not data:
        my_json["msg"] = "No data obtained!"
    try:
        data=json.loads(data)
        image1 = base64.b64decode(data["image1"].encode())
        image2 = base64.b64decode(data["image2"].encode())
        # image1_base64 = data["image1"].encode()
        # image2_base64 = data["image2"].encode()
        image1 = cv2.imdecode(np.frombuffer(image1, np.uint8), cv2.IMREAD_ANYCOLOR) #cv2.IMREAD_UNCHANGED
        image2 = cv2.imdecode(np.frombuffer(image2, np.uint8), cv2.IMREAD_ANYCOLOR)

        emb1 = face_recognition(image1)[OutputKeys.IMG_EMBEDDING]
        emb2 = face_recognition(image2)[OutputKeys.IMG_EMBEDDING]
        sim = np.dot(emb1[0], emb2[0])
        print(sim)
        my_json["msg"] = "successful!"
        my_json["sim"] = sim

        # face_recognition(image1,image2)
    except Exception as e:
        print(e)
        my_json["msg"] = "出错了,请检查是否正确访问!"
        response = making_response(my_json)
        return response

    response = make_response(jsonify(my_json))
    response.headers['Content-Type'] = 'application/json;charset=UTF-8'
    return response

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=12000, debug=True, use_reloader=False)

这是我测试用的代码:
import os
import time
import json
import base64
import random
import requests


IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo']


# 文件目录遍历,返回[fileP, fileN]
def get_filepaths(path):
    pathlists = []
    for root, dirs, files in os.walk(path):
        for file in files:
            pathlists.append([os.path.join(root, file), file])
    return pathlists


class api_test:
    def __init__(self):
        self.url = "http://0.0.0.0:12000/"  # nginx url

    @staticmethod
    def read_img_base64(p):
        with open(p, 'rb') as f:
            imgString = base64.b64encode(f.read())
            base64_data = imgString.decode()
        return base64_data

    def send_post(self, img_path1,img_path2):
        base64_data1 = self.read_img_base64(img_path1)
        base64_data2 = self.read_img_base64(img_path2)
        #image_name = str(img_path)
        data = {
            "image1": base64_data1,
            "image2": base64_data2
        }

        session = requests.session()
        start_time = time.time()
        response = session.post(self.url, json.dumps(data))  # Json格式请求
        end_time = time.time()
        run_time = end_time - start_time
        # logger.info('接口调用时间为:%s' % run_time)
        # logger.info(response.status_code)
        # logger.info(response.text)
        session.close()
        response.close()


if __name__ == "__main__":
    # 开始单元测试
    api = api_test()


    # 单张图片测试
    img_path1 = './样本.jpg'
    img_path2 = './样本1.jpg'
    res = api.send_post(img_path1,img_path2)
    print(res)

###### 
Press CTRL+C to quit
/opt/conda/lib/python3.7/site-packages/mmdet/core/anchor/anchor_generator.py:333: UserWarning: ``grid_anchors`` would be deprecated soon. Please use ``grid_priors`` 
  warnings.warn('``grid_anchors`` would be deprecated soon. '
/opt/conda/lib/python3.7/site-packages/mmdet/core/anchor/anchor_generator.py:370: UserWarning: ``single_level_grid_anchors`` would be deprecated soon. Please use ``single_level_grid_priors`` 
  '``single_level_grid_anchors`` would be deprecated soon. '
127.0.0.1 - - [29/Dec/2022 11:20:27] "POST / HTTP/1.1" 500 -
这是print输出的结果:-0.11088603
这是测试代码得到的结果:None

Press CTRL+C to quit

/opt/conda/lib/python3.7/site-packages/mmdet/core/anchor/anchor_generator.py:333: UserWarning: grid_anchors would be deprecated soon. Please use grid_priors
warnings.warn('grid_anchors would be deprecated soon. '
/opt/conda/lib/python3.7/site-packages/mmdet/core/anchor/anchor_generator.py:370: UserWarning: single_level_grid_anchors would be deprecated soon. Please use single_level_grid_priors
'single_level_grid_anchors would be deprecated soon. '
127.0.0.1 - - [29/Dec/2022 11:20:27] "POST / HTTP/1.1" 500 -
这是print输出的结果:-0.11088603
这是测试代码得到的结果:None

一头雾水。不知道是哪出了问题
我想要测试代码访问时 能把输出的结果也就是代码中的sim这个值返回给访问的那一端

PS:这个模型是魔塔社区的模型 我用来练习使用的,如果各位需要测试使用的话可以直接去https://www.modelscope.cn/models/damo/cv_ir101_facerecognition_cfglint/summary 打开使用测试

  • 写回答

3条回答 默认 最新

  • CSDN专家-sinJack 2022-12-29 12:22
    关注

    send_post方法没有return ,导致打印的结果为None

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 系统已结题 1月7日
  • 已采纳回答 12月30日
  • 修改了问题 12月29日
  • 修改了问题 12月29日
  • 展开全部

悬赏问题

  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭
  • ¥15 Matlab读取根元素出错