Unable to configure Gunicorn to serve a flask app running another loop concurrently -
i have simple flask app, this:
# app.py flask import flask app = flask(__name__) @app.route('/') def hello_world(): return 'hello, world!'
i have slack bot reading messages
#bot.py def serve(self): while true: message, channel = self.parse_slack_output(self.slack_client.rtm_read()) if message , channel: self.handle_message(message, channel) time.sleep(self.read_websocket_delay)
i want both codes run concurrently. in app.py
do:
#app.py if __name__ == "__main__": import threading import bot flask_process = threading.thread(target=app.run) bot_process = threading.thread(target=bot.serve) bot_thread.start() flask_thread.start()
this code works expected $ python app.py
, when bring in gunicorn
bot thread doesn't seem work.
i have tried:
gunicorn app:app gunicorn --workers=2 app:app gunicorn --threads=2 app:app
i tried multiprocessing
library , got same results.
any idea how issue can tackled? thanks.
edit: understand how lame question is. shouldn't writing code in if __name__ = "__main__":
block. not run gunicorn
. directly picks app , runs it. still have figure how make handle bot thread.
i have made work following solution:
# app.py flask import flask import threading import bot def create_app(): app = flask(__name__) bot_process = threading.thread(target=bot.serve) return app app = create_app() @app.route('/') def hello_world(): return 'hello, world!'
this makes sure gunicorn --workers=1 app:app
runs both app , bot in different threads. while works, 1 drawback solution not able scale number of workers > 1. not scale app thread, bot thread, don't want. bot unnecessarily listen messages in 2 threads.
any better solution in mind? please convey it. thanks.
Comments
Post a Comment