When developing web apps using frameworks like Django or Flask, we usually use built-in servers to develop and debug the program, and then hand it over to the production environment for deployment when the program is finished. The problem is that these built-in servers usually don't support HTTPS. We want to be able to use and test HTTPS during development, and we don't want to deploy the program to production without testing it, so we need the built-in server to support HTTPS.
This problem can be solved by an external program, stunnel. stunnel's role is to encrypt TCP sessions through the OpenSSL library, creating a secure channel that protects unencrypted or unencrypted programs. Its main function is twofold:
Receives the unencrypted data stream, performs SSL encryption, and then sends the encrypted data stream over the network;
The encrypted data stream is decrypted and the decrypted data stream is sent to another program over the network.
After understanding the function of stunnel, we can easily think of using stunnel to establish an SSL encrypted channel bound to the Django/Flask built-in server. stunnel starts on port 443 to accept the HTTPS request from the user, decrypts it and sends it to the built-in server on port 8000 for processing, and then sends the data to the stunnel after processing. After processing, the built-in server sends the data to stunnel and then encrypts it and returns it to the browser user.
Well, after all the seeming complexity, using stunnel is actually quite simple.
Install stunnel on the server where the Django/Flask development server resides:
# yum install stunnel (on CentOS)
or
$ sudo apt-get install stunnel4(exist Ubuntu first (of multiple parts))
If you don't have an SSL certificate, generate one yourself. By the way, the permissions of this file must be 600:
# openssl req -new -x509 -days 365 -nodes -out -keyout # chmod 600
Create a new configuration file called https and execute it with stunnel to start a port 443 connection to port 8000 of the Django/Flask built-in server:
# vi https pid = cert = debug = 7 foreground = yes [https] accept = 443 connect = 8000 # stunnel https
Start the Django built-in server bound to port 8000 as mentioned in the configuration file above:
# HTTPS=1 python runserver 0.0.0.0:8000
Starting the Flask built-in server doesn't require anything special, just change the port to 8000 and start it in the normal way:
# vi #!flask/bin/python from app import app (host='0.0.0.0', port=8000, debug = True) # ./ * Running on http://0.0.0.0:8000/ * Restarting with reloader