Back to python + flask basics Change a port

Adding SSL using python

To learn more about what SSL is visit the command line SSL page.

The simplest way to add SSL to our project is simply to create one at runtime. We can do this by modifying our command to run our flask app and adding the ssl_context='adhoc' parameter.

app.run(ssl_context='adhoc')

Every time you run the program a new SSL certificate and key are added. A disadvantage with this is that the warning about an invalid certificate will be shown every time the program is started even though we have already trusted the previous one.

To combat this, we can use a piece of software called pyOpenSSL to generate these certificates and store them on our PC.

You can find instructions on downloading and creating certificates with it here. We’ll assume that you already have a certificate though, and therefore we only need to link to it in the program.

This code snippet can replace the previous app.run call, and will create the flask instance using cert.pem as the cretificate and key.pem as the key.

app.run(ssl_context=('cert.pem''key.pem'))

When we run the program we’ll now notice that we only have to trust the certificate the first time that we start the program. The computer will remember our preference until the certificate expires.

Back to python + flask basics Return to top Change a port