python - Python-使用yield停止无限循环,然后重定向

标签 python python-3.x opencv yield url-for

我试图停止一个无限的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')

关于python - Python-使用yield停止无限循环,然后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60870615/

相关文章:

javascript - 如何通过 Javascript 在 PythonAnywhere 上的 OpenCV 中访问网络摄像头?

python - Python tkinter 绑定(bind)事件查询

python - ML 引擎实验 eval tf.summary.scalar 未显示在张量板中

python - 从列表条目访问 SQL 数据

python - 导入 OpenCV - 导入 cv2 或 cv3,为什么目录很重要?

python - 是否可以以不切断角的方式在 python 中使用 OpenCV 轮廓?

python - 检查二维数组每行中不同列索引的值

python - 为什么 "else"子句的目的是在 "for"或 "while"循环之后?

python - 从 Django 中的模型字段在 ListView 中创建列表

python-3.x - 线性回归决定系数背后的直觉