在Flask中返回响应后需要执行一个函数 [英] Need to execute a function after returning the response in Flask

查看:222
本文介绍了在Flask中返回响应后需要执行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅对于一个请求,我需要在将响应发送给客户端之后执行一个功能.因为该功能需要时间,并且最终会导致连接超时Socket error: [Errno 32] Broken pipe

For one request alone i need to execute a function after sending the response to the client. Because the function takes time and that ends up in connection timeout Socket error: [Errno 32] Broken pipe

烧瓶中是否存在一种在返回请求后执行功能的方法

Is there a way in Flask to execute function after returning the request

推荐答案

我将公开我的解决方案.

I will expose my solution.

您可以在使用烧瓶路由调用的函数中返回某些内容之后,使用线程来计算任何内容.

You can use threads to compute anything after returned something in your function called by a flask route.

import time
from threading import Thread
from flask import request, Flask
app = Flask(__name__)


class Compute(Thread):
    def __init__(self, request):
        Thread.__init__(self)
        self.request = request

    def run(self):
        print("start")
        time.sleep(5)
        print(self.request)
        print("done")


@app.route('/myfunc', methods=["GET", "POST"])
def myfunc():
        thread_a = Compute(request.__copy__())
        thread_a.start()
        return "Processing in background", 200

这篇关于在Flask中返回响应后需要执行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆