繁体   English   中英

在 Flask 中推送应用程序上下文

[英]Push application context in Flask

我正在为我最后一年的大学项目开发一个在线投票系统。 多线程 class 给用户 15 秒的投票时间。 它接受时间戳 cookie 并将其与当前时间进行比较。

class MonitorThread(threading.Thread):
def __init__(self, timecookie):
    threading.Thread.__init__(self)
    self.timecookie = timecookie

def run(self):
    try:
        while 1:
            timenow = datetime.timestamp(datetime.now())
            if timenow - int(float(self.timecookie)) < 15:
                continue
            else:
                return redirect(url_for('index'))
            sleep(0.1)
    except KeyboardInterrupt:
        GPIO.cleanup()

视频流路由运行用户的网络摄像头以捕获图像以进行面部验证,并运行多线程 class 的实例。

@ app.route('/videostream')
def videostream():
    video_stream = VideoCamera()
    timecookie = getcookie('time')
    MonitorThread(timecookie).start()
    return Response(gen(video_stream), mimetype='multipart/x-mixed-replace; boundary=frame')

这会导致错误:

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/home/abhishek/Documents/sem8/project/myfinalyear/app/app.py", line 48, in run
    return redirect(url_for('index'))
  File "/home/abhishek/Documents/sem8/project/myfinalyear/env/lib/python3.8/site-packages/flask/helpers.py", line 306, in url_for
    raise RuntimeError(
RuntimeError: Attempted to generate a URL without the application context being pushed. This has to be executed when application context is available.

我想在时间一到就结束投票过程。 请提出想法。

您是否尝试过用with语句包装它?

with app.app_context():

如果它仍然不起作用,您可以尝试设置SERVER_NAME配置,如文档中所述:

If set, url_for can generate external URLs with only an application context instead of a request context

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM