首页 > 解决方案 > 来自子进程的烧瓶重定向 - 仅使用 python 制作等待页面

问题描述

今天我尝试使用 Flask 制作一个“等待页面”。我的意思是客户提出请求,我想向他显示一个页面,例如“等待进程可能需要几分钟”,当进程在服务器上结束时显示结果。我想在我的函数之前显示“等待”manageBill.teste但是仅在返回正确时重定向工作?

@application.route('/teste', methods=['POST', 'GET'])
def test_conf():
if request.method == 'POST':
    if request.form.get('confList') != None:
        conf_file = request.form.get('confList')
        username = request.form.get('username')
        password = request.form.get('password')
        date = request.form.get('date')
        if date == '' or conf_file == '' or username == '' or password == '':
            return "You forget to provide information"
        newpid = os.fork()
        if newpid == 0: # in child procces
            print('A new child ',  os.getpid())
            error = manageBill.teste(conf_file, username, password, date)
            print ("Error :" + error)
            return redirect('/tmp/' + error)
        else: # in parent procces
            return redirect('/tmp/wait')
        return error
return manageBill.manageTest()`

我的 /tmp 路线:

@application.route('/tmp/<wait>')
def wait_teste(wait):
    return "The procces can take few minute, you will be redirected when the teste is done.<br>" + wait

标签: pythonredirectflask

解决方案


如果您使用 WSGI 服务器(默认),请求由线程处理。这可能与分叉不兼容。

但即使不是,你还有另一个根本问题。一个请求只能产生一个响应。一旦你return redirect('/tmp/wait')完成了这个请求。超过。你不能发送其他任何东西。

要支持这样的功能,您有几个选择:

  1. 最常见的方法是让 AJAX 发出请求以启动一个长时间运行的进程。然后设置一个/is_done烧瓶端点,您可以定期检查(通过 AJAX)(这称为轮询)。一旦您的端点返回工作已完成,您就可以更新页面(使用 JS 或通过重定向到新页面)。
  2. 必须/is_done是一个页面,而不是从 JS 查询的 API 端点。在其上设置 HTTP 刷新(有一些短暂的超时,如 10 秒)。然后,您的服务器可以/is_done在任务完成后将端点的重定向发送到结果页面。

通常,您应该努力尽快处理 Web 请求。您不应该让连接保持打开状态(等待长时间任务完成),并且应该将这些长时间运行的任务卸载到与 Web 进程分开运行的队列系统。通过这种方式,您可以扩展您分别处理 Web 请求和后台进程的能力(一个失败不会导致另一个失败)。


推荐阅读