How to set up production environment for your Flask project on Repl.it
Minobi (1)

Flask development server is good during the development cycle, but not in production work. As the Flask documentation says:

Flask’s built-in server is not suitable for production

So, we need a production server for Flask app after the end of project development. Based on this I prepare this template for set up production environment for Repl.it without using Flask (more correctly Werkzeug) development server. We will use Gevent as webserver and Flask-Compress for compressing static files because Repl.it not support gzip/deflate for response content

  • First we need to create sample Flask app from examples
from flask import Flask
app = Flask('app')

@app.route('/')
def hello_world():
  return 'Hello, World!'

app.run(host='0.0.0.0', port=8080)
  • Next we add Gevent and Flask-Compress packages to project
    Add import WSGI server from Gevent package
from gevent.pywsgi import WSGIServer
  • Setup params for Repl.it and start Gevent WSGI server with our Flask app for serving forever
http_server = WSGIServer(('0.0.0.0', 8080), app)
http_server.serve_forever()

instead of

app.run(host='0.0.0.0', port=8080)
  • Now we need to do "monkey-patching" standart Python library for work with async Gevent module. For this import
from gevent import monkey

on the first line of your main.py file before other imports and expressions. On the next line paste

monkey.patch_all()

This aplly runtime patches to synchoronous functions in standart Python library make it "gevent-friendly". For details see Gevent monkey module docs.
Now we have Flask app run on production-ready Gevent WSGI server, next we need enable compressing for static content such as HTML, CSS and JS files

  • Add import Flask-Compress
from flask_compress import Compress
  • Init compress with default params for our Flask app
compress = Compress()
compress.init_app(app)
  • If we already don't need debug capabilities for our project add secret with key FLASK_ENV and value production, otherwise set value to development.

That's all!

Now we have Flask app with production-ready Gevent WSGI server and compress for text-based static files using gzip/deflate/brotli algorithms. For test this create template folder with index.html file, import

from flask import render_template

and change hello_world function to

return render_template('index.html')

and paste some boilerplate HTML on your choice into index.html
After start your app you may see in network tab browser's dev tools that your web app serving with gzip/deflate/brotli compressing in dependence of your browser support.

You are viewing a single comment. View All