Use HTTPS on the Django and Flask development server

  • 2020-04-02 13:48:50
  • OfStack

When developing a web app using a Django or Flask framework, you typically use a built-in server to develop and debug the program, and then transfer it to a production environment for deployment. The problem is that these built-in servers generally don't support HTTPS, and we want to be able to use and test HTTPS while we're developing, rather than deploying to production without testing, so we need the built-in server to support HTTPS.

This problem can be solved by an external program called stunnel, which encrypts TCP sessions through the OpenSSL library, creating a secure channel to protect programs that are not encrypted or unencrypted. Its main functions are as follows:

Receive unencrypted data stream, SSL encryption, and then the encrypted data flow over the network to send out;
Decrypt the encrypted data stream and send the decrypted data stream over the network to another program.
After understanding the function of the stunnel we can easily think of using the stunnel build a SSL encryption channel binding to Django/Flask built-in server, start stunnel port 443 accept user HTTPS requests, decrypted and port 8000 for built-in server processing, built-in after the server sends data to the stunnel and returned to the browser user after encryption.

Well, it says a bunch of things that may seem complicated, but stunnel is pretty simple to use.

Install stunnel on the same server as the Django/Flask development server:


# yum install stunnel (in the  CentOS  On) 

or


$ sudo apt-get install stunnel4 (in the  Ubuntu  On) 

If you have not purchased an SSL certificate, you can generate one by yourself. By the way, the permission of this file must be 600.


# openssl req -new -x509 -days 365 -nodes -out vpsee.pem -keyout vpsee.pem

# chmod 600 vpsee.pem

Create a new configuration file called HTTPS, then execute this configuration file using stunnel to start port 443 to connect to port 8000 of the Django/Flask built-in server:


# vi https
pid =
cert = vpsee.pem
debug = 7
foreground = yes

[https]
accept = 443
connect = 8000

# stunnel https

Start the Django built-in server to bind to the 8000 port mentioned in the configuration file above:

# HTTPS=1 python manage.py runserver 0.0.0.0:8000
There is no special requirement to start the Flask built-in server, just change the port to 8000 and start it the normal way:


# vi run.py
#!flask/bin/python
from app import app
app.run(host='0.0.0.0', port=8000, debug = True)

# ./run.py
 * Running on http://0.0.0.0:8000/
 * Restarting with reloader


Related articles: