uwsgi:发送http响应并继续执行

问题描述 投票:0回答:1

来自uwsgi文档:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

是否可以响应http请求(关闭http连接)并继续执行流程(不使用任何线程/队列/外部服务等)?像这样:

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    end_response(b"Hello World")
    #HTTP connection is closed
    #continue execution..
python uwsgi
1个回答
0
投票

不幸的是,在返回响应后无法继续执行代码。如果使用多线程会更容易,但是如果不是,你可以通过向HTML响应添加一个AJAX调用来解决它在Flask中的问题,该调用将向一个服务器额外路由发送一个POST请求,其处理函数将是你想要的执行代码在回复之后。这是使用Flask的可能方法之一:

my flask app.朋友

from flask import Flask, render_template_string
import time

app = Flask(__name__)

@app.route('/run', methods=['POST'])
def run():
    # this is where you put your "continue execution..." code
    # below code is used to test if it runs after HTTP connection close
    time.sleep(8)
    print('Do something')
    return ''

@app.route('/')
def index():
    return render_template_string('''
            Hello World!
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
            <script>
            $(function() {
                $.ajax({
                    type: "POST",
                    url: "{{ url_for('run') }}"
                });
            })
            </script>
            ''')

if __name__ == "__main__":
    app.run(host='0.0.0.0')

您可以使用以下命令在端口9091上运行服务器:

uwsgi --http 127.0.0.1:9091 --wsgi-file myflaskapp.py --callable app

要测试它是否正常工作,您可以访问地址localhost:9091。如果一切正常,您应该看到页面立即加载,而终端只会在Do something之后打印出8 seconds have passed,表示在HTTP连接关闭后执行run函数。

© www.soinside.com 2019 - 2024. All rights reserved.