SSL for flask local development

Recently at HasGeek we moved all our web application to https. So I wanted to have all my development environment urls to have https.

How to have https in flask app

Method 1

from flask import Flask
app = Flask(__name__)
app.run('0.0.0.0', debug=True, port=8100, ssl_context='adhoc')

In the above piece of code, ssl_context variable is passed to werkezug.run_simple which creates SSL certificates using OpenSSL, you may need to install pyopenssl. I had issues with this method, so I generated self signed certificate.

Method 2

  • Generate a private key openssl genrsa -des3 -out server.key 1024

Generate a CSR
` openssl req -new -key server.key -out server.csr `
Remove Passphrase from key
`cp server.key server.key.org `
`openssl rsa -in server.key.org -out server.key `
Generate self signed certificate
`openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt `

code

from flask import Flask
app = Flask(__name__)
app.run('0.0.0.0', debug=True, port=8100, ssl_context=('/Users/kracekumarramaraju/certificates/server.crt', '/Users/kracekumarramaraju/certificates/server.key'))

ssl_context can take option adhoc or tuple of the form (cert_file, pkey_file).

In case you are using /etc/hosts, add something similar 127.0.0.1 https://hacknight.local for accessing the web application locally.

Here is much detailed post about generating self signed certificates.

python  ssl  https  flask 

See also

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Powered by Buttondown.