[英]How can I run two different tasks of Flask simultaneously
I'm working on my flask project.我正在研究我的 flask 项目。 First, Look at the below code.首先,看下面的代码。
def video_1() :
try :
# Response is used to display a flow of information
#SER = speechEmotionRecognition()
SER = speechEmotionRecognition()
# Voice Recording
rec_duration = 16 # in sec
rec_sub_dir = os.path.join('tmp','voice_recording.wav')
SER.voice_recording(rec_sub_dir, duration=rec_duration)
return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
except :
return None
In the try block, the lines above the return statement should execute with the expression of the return statement.在 try 块中,return 语句上面的行应该与 return 语句的表达式一起执行。 The lines before the return statement are used to record the audio while the last return statement is for real-time video capturing and saving emotions of each frame in a CSV file. return 语句之前的行用于记录音频,而最后的 return 语句用于实时视频捕获并将每一帧的情绪保存在 CSV 文件中。 I want to do both these processes at once like recording video and audio at the same time.我想同时完成这两个过程,比如同时录制视频和音频。 How can I modify the code to do so?我该如何修改代码来做到这一点?
I know the concept of threading I tried to make two processes and run them but it's still not working, Look at the below code:我知道线程的概念我试图创建两个进程并运行它们但它仍然无法正常工作,请查看以下代码:
@app.route('/fun1', methods=("POST", "GET"))
def fun1():
SER = speechEmotionRecognition()
rec_duration = 16
rec_sub_dir = os.path.join('tmp','voice_recording.wav')
SER.voice_recording(rec_sub_dir, duration=rec_duration)
return None
@app.route('/fun2', methods=("POST", "GET"))
def fun2():
return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_1', methods=['POST'])
def video_1() :
try :
p1 = Process(target = fun1)
p1.start()
p2 = Process(target = fun2)
p2.start()
return "dummy"
except :
return None
As mentioned by Ayaan you can use threading or multiprocessing to perform tasks "simultaneously", BUT there a huge caveat here the Global Interpreter Lock (GIL).正如 Ayaan 所提到的,您可以使用线程或多处理来“同时”执行任务,但这里有一个巨大的警告,即全局解释器锁(GIL)。
The GIL prevents a single python process performing two tasks concurrently. GIL 可防止单个 python 进程同时执行两个任务。 Usually there's enough going on to cause things to block and control to pass between threads within a single process;通常有足够多的事情导致阻塞和控制在单个进程中的线程之间传递; however, what you want to do (record video and audio separately) will probably require separate processes.但是,您想要做的(分别录制视频和音频)可能需要单独的过程。
You really should look for a library that has implemented this outside of Python, but this is the gist of how to start up another process:您确实应该寻找在 Python 之外实现此功能的库,但这是如何启动另一个进程的要点:
from multiprocessing import Process
audio_process = Process(target=SER.voice_recording, args=[rec_sub_dir], kwargs={"duration": rec_duration})
audio_process.start()
You should probably add some process management around that.您可能应该围绕它添加一些流程管理。
Additionally, while using os.path is better than concatenating strings you could further modernize your code using pathlib .此外,虽然使用os.path比连接字符串更好,但您可以使用pathlib进一步现代化您的代码。 Pathlike objects include a lot of functionality and override the division method to allow them to be combined using / (as seen in the example below). Pathlike 对象包含许多功能并覆盖除法方法以允许使用 / 组合它们(如下例所示)。
from pathlib import Path
recording_directory = Path('tmp')
audio_file = recording_directory / 'voice_recording.wav'
Lastly, please try to adhere to PEP8 .最后,请尽量遵守PEP8 。
Your class names should be camel case and start with a capital (if you can, then change speechEmotionRecognition to SpeechEmotionRecognition).您的 class 名称应为驼峰式并以大写字母开头(如果可以,请将 SpeechEmotionRecognition 更改为 SpeechEmotionRecognition)。 Also, common variable should be snake case and lowercase (SER should be ser, but maybe using a descriptive word is better... speech_recognize perhaps?).此外,公共变量应该是蛇形和小写(SER 应该是 ser,但也许使用描述性的词更好……speech_recognize 也许?)。
You can use the threading module or multiprocessing module in Python, I would check out both.您可以使用 Python 中的线程模块或多处理模块,我会检查两者。 Basically, what they do is well, they run multiple processes/functions at once, which is exactly what you wanna do.基本上,他们做得很好,他们一次运行多个进程/功能,这正是你想要做的。 I believe there are a few extra steps if you wanna get that working with Flask, but yeah.我相信如果您想使用 Flask 进行操作,还有一些额外的步骤,但是是的。 Here's a tutorial on the threading module,https://www.tutorialspoint.com/python/python_multithreading.htm , and here's a tutorial on the multiprocessing module, https://www.geeksforgeeks.org/multiprocessing-python-set-1/这是关于线程模块的教程,https://www.tutorialspoint.com/python/python_multithreading.htm ,这里是关于多处理模块的教程, https://www.geeksforgeeks.org/multiprocessing-python /
The problem has been resolved, I just used the below code问题已经解决,我只是使用下面的代码
@app.route('/fun1', methods=("POST", "GET"))
def fun1():
SER = speechEmotionRecognition()
rec_duration = 16
rec_sub_dir = os.path.join('tmp','voice_recording.wav')
SER.voice_recording(rec_sub_dir, duration=rec_duration)
return None
@app.route('/fun2', methods=("POST", "GET"))
def fun2():
return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_1', methods=['POST'])
def video_1() :
try :
p1 = Process(target = fun1)
p1.start()
p2 = Process(target = fun2)
p2.start()
return Response(gen(),mimetype='multipart/x-mixed-replace; boundary=frame')
except :
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.