I have a Flask application that works fine when run on the commandline, but when it is run through uWSGI it doesn't respond correctly to requests or the worker thread doesn't work properly. I've rewritten a simple proof-of-concept/failure program that demonstrates the issue:
from datetime import datetime
from threading import Event, Thread
from flask import Flask
class JobManager:
def __init__(self):
self.running = False
self.event = Event()
def start(self):
self.running = True
while self.running:
print("Processing Job at", datetime.now().strftime('%c'))
self.event.clear()
self.event.wait(5)
if self.event.is_set():
print("Interrupted by request!")
def stop(self):
self.running = False
self.event.set()
app = Flask(__name__)
jobs = JobManager()
t = Thread(target=jobs.start)
t.start()
@app.route('/')
def hello_world():
global jobs
jobs.event.set()
return "I'm alive at " + datetime.now().strftime('%c')
if __name__ == '__main__':
app.run()
I'd expect that calling the / route would print "Interrupted by request!" on the console but it just hangs even though the job should be running in a seperate thread.
My uWSGI configuration is:
[uwsgi]
module = app:app
master = true
processes = 5
threads = 2
socket = 0.0.0.0:5000
protocol = http
reload-mercy = 5
worker-reload-mercy = 5
die-on-term = true
enable-threads = true
thunder-lock = true
logto = /home/user/dev/flask-thread/uwsgi_log.log
logto2 = /home/user/dev/flask-thread/uwsgi2_log.log
env = PATH=/home/user/dev/flask-thread/env/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
I then run uWSGI in the venv with: uwsgi --ini uwsgi-test.ini
It will work if I use python app.py
and use the built in flask development server.
My only guess is that it has something to do with the GIL interacting with uWSGI but that's a wild guess and I have no idea how to stop that.