Python烧瓶表单提交函数到后台进程

时间:2018-02-21 06:37:46

标签: python multithreading process background

我想知道在表单提交作为后台进程之后我们如何才能完成此过程。

from flask import Flask, g, redirect, url_for
@app.route("/form", methods=['GET', 'POST'])
def form():
if request.method == 'POST':
    #form processing(This block need to do as background)
    #background must have access to the app.* and g.* variables
    return redirect(url_for('app.form_result'))
g.result['page_title'] = 'Form Input'
g.template = 'form.html'
return 'Done'

1 个答案:

答案 0 :(得分:0)

我看到两种可能的解决方案:

首先,使用APScheduler(https://pypi.python.org/pypi/APScheduler)并将流程安排为单个作业:

from apscheduler.schedulers.background import BackgroundScheduler

def processing_function(app, g):
    pass # Perform your processing here

scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(processing_function, app, g)

其次,使用芹菜(http://www.celeryproject.org/)。如果要在单独的服务器上运行后台进程,请使用此选项。我不会在这里提供代码示例,但您需要与Web服务器分开启动Celery工作程序和代理程序。然后,您可以将作业传递给worker(带参数),并将响应发回。

相关问题