程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在 Flask 中推送应用程序上下文大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在 Flask 中推送应用程序上下文?

开发过程中遇到在 Flask 中推送应用程序上下文的问题如何解决?下面主要结合日常开发的经验,给出你关于在 Flask 中推送应用程序上下文的解决方法建议,希望对你解决在 Flask 中推送应用程序上下文有所启发或帮助;

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

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

def run(self):
    try:
        while 1:
            timeNow = @R_607_7538@me.timestamp(@R_607_7538@me.Now())
            if timeNow - int(float(self.timecookiE)) < 15:
                conTinue
            else:
                return redirect(url_for('index'))
            sleep(0.1)
    except KeyboardInterrupt:
        GPIO.cleanup()

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

@ 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配置,如documentation中所述:

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

大佬总结

以上是大佬教程为你收集整理的在 Flask 中推送应用程序上下文全部内容,希望文章能够帮你解决在 Flask 中推送应用程序上下文所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。