The objective of this post is to explain how to force HTTPS on a deployed Flask application on pythonanywhere.
Introduction
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.
Figure 3 – Reloading the app.
On the directory page, click on the flask_app.py 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) @app.route('/') 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.
References
[1] https://help.pythonanywhere.com/pages/InstallingNewModules/
Pingback: Pythonanywhere: Accessing the MySQL database | techtutorialsx
Pingback: Pythonanywhere: Accessing the MySQL database | techtutorialsx
Pingback: Flask: Parsing JSON data | techtutorialsx
Pingback: Flask: Parsing JSON data | techtutorialsx