[英]Python - Stop infinite loop with yield and then redirect
我试图停止一个无限的 while 循环,该循环使用 yield 函数从相机馈送中传递帧,但如果在识别过程中在相机中识别了正确的人,还会传递一个确认标签(“确认”)。 所以我写了一个 if 语句,检查确认不等于“notfound”,如果是这样,它意味着它是一个人,我需要重定向到某个地方,在这个例子中 - 主页。
from flask import Flask, render_template, Response, redirect, url_for
import cv2
import numpy as np
from camera2 import VideoCamera
app = Flask(__name__)
light_on = False
@app.route('/', methods=['GET', 'POST'])
@app.route('/home', methods=['GET', 'POST'])
def home():
return render_template("main.html")
@app.route('/recognition', methods=['GET', 'POST'])
def recognition():
return render_template('recognition.html')
def gen(camera2):
while True:
confirmation, frame = camera2.get_frame()
print(confirmation)
# yield ('--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + '\r\n\r\n')
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
if confirmation != "notfound":
return redirect(url_for("home"))
@app.route('/video_feed')
def video_feed():
return Response(gen(VideoCamera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run("localhost", 5050, debug=True, threaded=True)
但是每当我尝试这样做时,我都会收到一条错误消息:
"Attempted to generate a URL without the application context being"
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.
我将不胜感激任何帮助或建议!
谢谢!
我遇到了类似的问题,这可能对某人有所帮助...
from functools import wraps
def my_decorator(function):
@wraps(function)
def wrapper():
if not os.path.isdir(audioPath):
return ""
return function()
return wrapper
@app.route('/playaudio')
@my_decorator # this avoid infinity loop
def playaudio():
def generate():
data = ""
if os.path.isdir(audioPath):
for audioPath in filesAudios:
data=subprocess.check_output(['cat',audioPath])
yield data # ifinity loop if audioPath do not exist
return data
return Response(generate(), mimetype='audio/mp3')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.