5Mins Task - Move your Flask Web Server based Python App to production (Flask + Gunicorn)

 Without wasting time, I would divide it into three parts and will show you

1. Installation of gunicorn.

2. My old code structure with flask app.

3. Conversion within 5 minutes to gunicorn + flask (production friendly)

This tutorial assumes, you are used to linux flavor and basic commands for pip, git etc.

Installation of gunicorn 

Its the most easy step and you can install gunicorn as any other pip package.

pip install gunicorn


My old code structure with flask

In my case, 

I had a file with the app and methods (appserver.py) within the following method create_app,

Another server file as wsgi.py to call this app.

appserver.py 

def create_app():

    # initialize a flask object
app = Flask(__name__, static_url_path='/static')
################################################################
##########################################
######## SERVER METHODS FOR POST AND GET
##########################################
@app.route("/")
def index():
# return the rendered template
# return render_template("index.html"def index():
return render_template('index.html')

@app.route('/someFunction', methods=['POST'])
    ## ANY OF YOUR CODE IN YOUR FILE, I will move to the last line in this file i.e. below.
    return app

wsgi.py
from gevent.pywsgi import WSGIServer
from appserver import create_app


if __name__=="__main__":

app =create_app()
http_server = WSGIServer(("0.0.0.0", 5050), app)
http_server.serve_forever()

For running the server, I was simply doing "python3 wsgi.py"
Now - As Flask is not suitable for production, we need to convert it to gunicorn.
1. Forget the wsgi.py - not needed anymore, you may keep it for memories somewhere :)
2. appserver.py - change the name to appservergunicorn.py (just to make a different file, can be any name)
   copy all contents from appserver.py, paste them and just add one line in the end 
   as below

appservergunicorn.py 

def create_app():

    # initialize a flask object
app = Flask(__name__, static_url_path='/static')
################################################################
##########################################
######## SERVER METHODS FOR POST AND GET
##########################################
@app.route("/")
def index():
# return the rendered template
# return render_template("index.html"def index():
return render_template('index.html')

@app.route('/someFunction', methods=['POST'])
    ## ANY OF YOUR CODE IN YOUR FILE, I will move to the last line in this file i.e. below.
    return app
my_app= create_app() # by this GUNICORN SERVER Will know which app to refer.

Thats it, you did it.
To run the gunicorn server 
With logs, 7 threads (you may choose any number), logs on and port 5050
gunicorn appservergunicorn:my_app -w 1 --threads=7  -b 0.0.0.0:5050 --error-logfile gunicorn.error.log --access-logfile gunicorn.log --capture-output


Hopefully, you liked it.

Comments