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

时间:2019-03-15 16:44:55

标签: python uwsgi

来自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..

1 个答案:

答案 0 :(得分:0)

不幸的是,返回响应后,无法继续执行代码。如果使用多线程,会容易得多,但如果不使用多线程,则可以通过在HTML响应中添加AJAX调用来解决该问题,该调用将向服务器额外路由之一发送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。如果一切正常,您应该看到页面已立即加载,而终端仅在Do something之后打印8 seconds have passed,表明函数run在关闭HTTP连接后执行。 / p>

相关问题