简体   繁体   English

如何使用flask在回调函数中返回响应

[英]How to return a response in callback function with flask

here is a dll, that can compare face distance, and the compareFace.dll, I need use callback to receive it's value 这是一个dll,可以比较人脸距离,并且compareFace.dll,我需要使用回调函数来接收它的值

now, I want use flask to wrapper it, then can visit by http and json 现在,我想用flask包装它,然后可以通过http和json访问

lib= c.CDLL('comparedFace.dll')
CALLBACKFUNC = c.CFUNCTYPE(None, c.c_int, c.c_char_p)
lib.startComparedFace.restype = c.c_int 
lib.startComparedFace.argtypes = (c.c_char_p, c.c_char_p, CALLBACKFUNC)


@app.route('/compare', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':

        request_json = request.get_json()
        print(request_json)
        number       = request_json.get('number')
        image01      = request_json.get('image01')
        image02      = request_json.get('image02')
        print(image01)
        print(image02)


        @c.CFUNCTYPE(None, c.c_int, c.c_char_p)
        @copy_current_request_context
        def callback(status, result_string):

            result_json = json.loads(result_string)
            distance = result_json['compareResult']

            resp_data = {
                "number": number, 
                "distance": distance,
            }
            print(resp_data)
            response = Response(
                response=json.dumps(resp_data),
                status=200,
                mimetype='application/json'
            )
            return response


    lib.startComparedFace(b'd:/1.jpg', b'd:/2.jpg', callback)

run the code, and I receive a error ValueError: View function did not return a response 运行代码,并且收到错误ValueError: View function did not return a response

I know, I should write a return 'xxx' as response 我知道,我应该写一个“ xxx”作为回应

But, I want wait the callback function, and return response in the callback function, so how should I modify my code, thank you. 但是,我想等待回调函数,并在回调函数中返回响应,所以我应该如何修改我的代码,谢谢。

Let's see a simple scenario: 让我们看一个简单的场景:

  1. User gives his/her username. 用户提供他/她的用户名。
  2. Our function calculates a value based on the username. 我们的函数根据用户名计算一个值。 Making this dummy call as time consuming call using time.sleep function. 使用time.sleep函数将此虚拟呼叫作为耗时的呼叫进行。
  3. User receives the value after the operation is being completed. 操作完成后,用户会收到该值。

This can be achieved by using the following code. 这可以通过使用以下代码来实现。

app.py : app.py

import time
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/', methods=["GET", "POST"])
def index():
    username = None
    value = 0
    if request.method == 'POST':
        username = request.form.get("username", None)

    def calculate_value_based_on_username(user_given_name):
        time.sleep(10)
        return len(user_given_name)

    if username:
        value = calculate_value_based_on_username(username)
        return render_template('app.html', username=username, value=value)
    return render_template('app.html')

if __name__ == '__main__':
    app.run(debug=True)

app.html : app.html

<html>
  <head></head>
  <body>
    {% if username %}
      Hello {{ username }}! Length of your username: {{ value }}
    {% else %}
      Hello guest! 
    {% endif %}
    <form action="/" method="post">
      Username: <input type="text" name="username">
      <input type="submit" name="submit" value="Submit">
    </form>
  </body>
</html>

Output: 输出:

输出

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

相关问题 如何在Flask的回调中返回HTTP响应,或者甚至是否重要? - How do I return an HTTP response in a callback in Flask, or does it even matter? 查看功能未在烧瓶中返回响应 - View function did not return a response in flask Flask 视图返回错误“视图函数未返回响应” - Flask view return error "View function did not return a response" 如何在烧瓶中的一行中返回 json 响应? - How to return a json response in one line in flask? 如何使用 Flask 将 return.find() 作为响应? - How to return .find() as a response using Flask? 如何使用 function 中的 dataframe 并返回响应以下载 csv 文件 - Z9784E916BCAF2656789172 - How to use dataframe from a function and return response to download csv file - Flask 如何解决TypeError: The view function did not return a valid response in python flask api - How to solve the TypeError: The view function did not return a valid response in python flask api Flask REST API错误:视图函数未返回有效响应 - Flask REST API Error: The view function did not return a valid response Flask返回TypeError:视图函数未返回有效响应 - Flask is returning TypeError: The view function did not return a valid response FLASK-python ValueError:视图函数未返回响应 - FLASK-python ValueError: View function did not return a response
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM