Python anywhere: Forcing HTTPS on Flask app

The objective of this post is to explain how to force HTTPS on a deployed Flask application on pythonanywhere.


The objective of this post is to explain how to force HTTPS on a deployed Flask application on pythonanywhere.

As indicated here, there is SSL support even for free accounts. Here is an explanation on how we can force HTTPS for different web frameworks.

As suggested, we will use the flask-sslify extension to do it.

Using the Flask extension

After logging in to your account on pythonanywhere, go to the consoles tab and on the “Start a new console” separator, in other, click Bash. This is highlighted in figure 1.


Figure 1 – Opening a bash console.

In the bash console that will open, just type the following pip command:

pip install --user Flask-SSLify

Note that you should literally write –user [1], you should not change it to your registered username. After the command runs, we should get something similar to figure 2.


Figure 2 – Output of the installation of Flask-SSLify.

Now, go back to the initial webpage and select the Web tab. There, select the option to reload the web application, as highlighted in figure 3. Then, go to the code directory, in order to change the source code of the Flask app to use the new module.

Python anywhere reload changes.png

Figure 3 – Reloading the app.

On the directory page, click on the file to edit the source code, as indicated in figure 4.


Figure 4 – App’s code directory.

From the default app we analysed in the previous post, we will just do some slight changes. First, we will do a new import, to get the SSLify class from the flask-sslify module. You can check the source code for the class here.

from flask_sslify import SSLify

Then, after creating the Flask app, we just create an instance of the mentioned class, passing the previously created app as input.

app = Flask(__name__)
sslify = SSLify(app)

You can check the full source code bellow.

from flask import Flask
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

def hello_world():
    return 'Custom Hello from Flask!'

Finally, just hit the save button and then the reload button, both located on the top right side of the editor. Then, navigate to your app’s URL and it should now be redirected to HTTPS, as shown in figure 5.


Figure 5 – Flask hello world app with HTTPS.

If we check the certificate in our browser, we will see that it was emitted to pythonanywhere, as shown in figure 6.


Figure 6 – Pythonanywhere certificate.




2 Replies to “Python anywhere: Forcing HTTPS on Flask app”

Leave a Reply