[英]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.