2

I wrote a Flask application that needs a secondary thread to display a video stream in the browser. Here is the way the thread is created:

if __name__ == '__main__':
    # # start a thread that will perform motion detection
    t = threading.Thread(target=prepare_video_stream)
    t.daemon = True
    t.start()

    print(t.is_alive())

    app.run(debug=True, threaded=True, use_reloader=False)

Everything works fine when a run my application with the built-in flask server, but after deploying to heroku with gunicorn the thread doesn't seem to start. Here is my Procfile:

web: gunicorn app:app

How can I make the thread run? Am I missing something?

Ttt
  • 113
  • 7

1 Answers1

0

I found a solution to this

The key is to run your thread in @app.before _first_request instead of the name locked __main__

@app.before_first_request
def thread_start():
    # # start a thread that will perform motion detection
    t = threading.Thread(target=prepare_video_stream)
    t.daemon = True
    t.start()
    print(t.is_alive())

if __name__ == '__main__':
    app.run(debug=True, threaded=True, use_reloader=False)
Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53