Photo by Ferenc Almasi on Unsplash
How to make your FLASK APP asynchronous with gunicorn?
2 min read
While deep-diving into python's flask framework I realized that flask has some huge issues with asynchronous tasks. See every good thing comes with pros and cons and the asynchronous task seems to be one of the cons here for the flask.
So as I was building this app I realized that even though I used threading (Which is a bad idea to replace async tasks with) inside the application to easily bypass some of these issues it still didn't solve what I wanted. So basically this was the scenario my application was working fine until I realized that all the view functions are not asynchronous at all, If one page was loading then the other page wouldn't load until that was finished which was a complete disaster because it will make the application very slow.
I started asking my friends they suggested me to use queues , celery or other similar projects to do asynchronous tasks smoothly but I had my security scanner developed already and didn't want to add things back to it again so I started looking for solutions and came across gunicorn which gave the exact result I wanted.
So Gunicorn has something called workers which works asynchronously and by spawning 5-6 such workers I achieved complete asynchronous functionality for the view functions in flask.
If you used threading use this:
gunicorn --workers=5 --threads=10 --worker-class=gthread app:app
If you want to use gevent use this:
gunicorn --worker-class=gevent --worker-connections=1000 --workers=5 app:app
Note: You don't have to launch more than 10-12 workers as it is mentioned in the documentation that 5-6 such workers can easily handle thousands of requests so use them wisely.