在Python中的REST API程序中,使用多处理调用方法时遇到了困难



我正在学习Python,但我有一位糟糕的老师,我不知道如何在windows上处理REST API程序中的multiprocessing模块。我有一个存储人员(医院患者(数据的应用程序,我必须包含一个在后台统计这些数据的方法。

from flask import Flask
from hospital_controller import hospital_api
from report_generator import statistic_reporting
import multiprocessing
app = Flask(__name__)

@app.route('/')
def hello_world():
return 'Hello World!'

if __name__ == '__main__':
print('Hello')
REPORT_GENERATOR_PID = multiprocessing.Queue()
if REPORT_GENERATOR_PID == 0:
statistic_reporting()
exit(0)
print(hospital_api)
app.register_blueprint(hospital_api)
app.run(host='0.0.0.0', port=5000, debug=True)

这样,多进程调用就会被忽略。其他一切都很好,所以我正在运行REST API。我试着用不同的方式来称呼它:

p = multiprocessing.Queue(target=statistic_reporting())

在这种情况下,statistic_reporting()方法运行良好,但API服务器本身没有响应。总之,我不能让这两件事同时起作用。

multiprocessing.Queue()不创建新进程,也不接受目标参数。您似乎有点困惑,确实需要阅读一本关于多处理的好教程。但是,值得一提的是,下面的代码是启动后台进程的Flask应用程序的一个示例。但是,我很遗憾,我无法为您提供您似乎需要的完整的多处理教程。所以我不知道你会从中得到什么价值。

from flask import Flask
from multiprocessing import Process
app = Flask(__name__)
def background_task():
import time
print('Background task started.')
time.sleep(5)
print('Background task ended.')
@app.route('/')
def hello_world():
Process(target=background_task).start()
return 'Hello World!'

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)

最新更新