Push application context in Flask

Issue

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.

Solution

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

Answered By – Roy Rosenfeld

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published