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

uwsgi: Send http response and continue execution

来自 uwsgi 文档:

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

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

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    end_response(b"Hello World")
    #HTTP connection is closed
    #continue execution..

很遗憾,返回响应后无法继续执行代码。如果您使用多线程会容易得多,但如果不使用,您可以通过向 HTML 响应添加 AJAX 调用来在 Flask 中解决它,这将向其中一个服务器发送 POST 请求额外的路由,其处理函数将是返回响应后所需的执行代码。这是使用 Flask 的一种可能方法:

myflaskapp.py

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。如果一切正常,您应该会看到页面立即加载,而终端只会在 8 seconds have passed 之后打印出 Do something,表明函数 run 在 HTTP 连接关闭后执行。