简体   繁体   中英

Push application context in Flask

I am developing an online voting system for my final year college project. The multi threading class gives a user 15 seconds to vote. It accepts a timestamp cookie and compares it to the current time.

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()

The videostream route runs the user's webcam to capture images for face verification and also runs an instance of the multi threading 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')

This results in an error:

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.

I want to end the voting process as soon as the time is up. Please suggest ideas.

Have you tried wrapping it with a with statement?

with app.app_context():

If it still doesn't work, you can try setting a SERVER_NAME configuration, as written in the documentation :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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