[Python recipe] Run a Flask web application locally in https

Problem:

You want to run a Flask application on your development machine using https.

Solution:

Provided that you have openssl installed (apt-get install openssl -y on ubuntu), we can create a self signed SSL certificate:

cd /your_project_dir

mkdir ssl && cd ssl

openssl genrsa -des3 -passout pass:x -out server.pass.key 2048

openssl rsa -passin pass:x -in server.pass.key -out server.key

rm server.pass.key

openssl req -new -key server.key -out server.csr

openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

Once the certificate has been generated, we can configure the Flask app to run in https using it (in the python code I’m assuming that the application code is under the “src” folder).
The Flask app should be configured with the option ssl_context which accepts a tuple containing the paths of .crt and .key files.
In the main application module:

ssl_dir: str = os.path.dirname(__file__).replace('src', 'ssl')
key_path: str = os.path.join(ssl_path, 'server.key')
crt_path: str = os.path.join(ssl_path, 'server.crt')
ssl_context: tuple = (crt_path, key_path)
app.run('0.0.0.0', 8000, debug=False, ssl_context=ssl_context)

Now you should be able to reach your app from any device in your local network with https://your-machine-ip:8000

Notes:

This recipe has been tested with Flask 0.12.1 on Ubuntu, older versions may behave differently.