python - 来自子进程的烧瓶重定向 - 仅使用 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
解决方案
如果您使用 WSGI 服务器(默认),请求由线程处理。这可能与分叉不兼容。
但即使不是,你还有另一个根本问题。一个请求只能产生一个响应。一旦你return redirect('/tmp/wait')
完成了这个请求。超过。你不能发送其他任何东西。
要支持这样的功能,您有几个选择:
- 最常见的方法是让 AJAX 发出请求以启动一个长时间运行的进程。然后设置一个
/is_done
烧瓶端点,您可以定期检查(通过 AJAX)(这称为轮询)。一旦您的端点返回工作已完成,您就可以更新页面(使用 JS 或通过重定向到新页面)。 - 必须
/is_done
是一个页面,而不是从 JS 查询的 API 端点。在其上设置 HTTP 刷新(有一些短暂的超时,如 10 秒)。然后,您的服务器可以/is_done
在任务完成后将端点的重定向发送到结果页面。
通常,您应该努力尽快处理 Web 请求。您不应该让连接保持打开状态(等待长时间任务完成),并且应该将这些长时间运行的任务卸载到与 Web 进程分开运行的队列系统。通过这种方式,您可以扩展您分别处理 Web 请求和后台进程的能力(一个失败不会导致另一个失败)。
推荐阅读
- asp.net-core - 我可以使用当前 NTML 上下文从 WebAPI 控制器(或 BlazorComponent)内部发出请求吗?
- github - 有没有办法将 2 个本地文件夹连接到 2 个单独的 github 分支
- ruby-on-rails - rails NoMethodError(“1”的未定义方法`map':String您是说吗?点击):
- c++ - 键盘记录器返回所有值
- angular - 如何在 NgRx 中使用 remote-redux-devtools?
- inheritance - UML 中继承的 actor 具有不同行为的相同用例
- java - @RequestMapping 注释控制器中的运行时异常 - 哪个 HTTP 响应代码?
- c# - 实体框架在插入子项后不保存导航属性
- c - 在没有 WMI 的 Windows 中查找 MaxNumberOfProcesses
- c - 为什么我的程序没有提示输入最终值?[C]