【发布时间】:2016-12-06 07:07:01
【问题描述】:
我正在编写一个 Web 应用程序,它会做一些繁重的工作。考虑到这一点,我想将这些任务设为后台任务(非阻塞),这样其他请求就不会被之前的请求阻塞。
我将线程妖魔化,以便在主线程(因为我使用threaded=True)完成后它不会退出,现在如果用户发送请求,我的代码将立即告诉他们他们的请求在进度,它将在后台运行,并且应用程序已准备好处理其他请求。
我当前的应用程序代码如下所示:
from flask import Flask
from flask import request
import threading
class threadClass:
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
#
# This might take several minutes to complete
someHeavyFunction()
app = Flask(__name__)
@app.route('/start', methods=['POST'])
try:
begin = threadClass()
except:
abort(500)
return "Task is in progress"
def main():
"""
Main entry point into program execution
PARAMETERS: none
"""
app.run(host='0.0.0.0',threaded=True)
main()
我只是希望它能够处理一些并发请求(它不会在生产中使用)
我可以做得更好吗?我错过了什么吗?我正在浏览python的多线程包,发现了这个
multiprocessing 是一个支持使用 API 类似于 threading 模块。多处理包 提供本地和远程并发,有效地回避 通过使用子进程而不是线程来全局解释器锁。 因此,多处理模块允许程序员完全 利用给定机器上的多个处理器。它在两个 Unix 上运行 和窗户。
我可以使用多处理来妖魔化进程吗?我怎样才能比使用 threading 模块做得更好?
##编辑
我通过python的多处理包,它类似于线程。
from flask import Flask
from flask import request
from multiprocessing import Process
class processClass:
def __init__(self):
p = Process(target=self.run, args=())
p.daemon = True # Daemonize it
p.start() # Start the execution
def run(self):
#
# This might take several minutes to complete
someHeavyFunction()
app = Flask(__name__)
@app.route('/start', methods=['POST'])
try:
begin = processClass()
except:
abort(500)
return "Task is in progress"
def main():
"""
Main entry point into program execution
PARAMETERS: none
"""
app.run(host='0.0.0.0',threaded=True)
main()
上面的方法好看吗?
【问题讨论】:
-
我知道 celery,因为它需要数据库服务器来支持后端我不想使用它。
-
如果您有时间,请查看 FlaskCon (youtu.be/tdIIJuPh3SI) 上的 Miguel Grinbergs 主题演讲。在 1:25:38,他开始描述如何使用异步装饰器在异步请求处理程序中处理异步请求和转向路由。
标签: python multithreading flask