'Making my Flask website HTTPS stops me from being able to connect
I am trying to run a Flask website using HTTPS. The website worked perfectly using HTTP, but once I added a certificate I can no longer connect to it.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return '<b>hello world!'
if __name__ == '__main__':
# The following line is one option I tried.
# app.run(ssl_context='adhoc', host='0.0.0.0', port='80')
# The following line is another option I tried.
# app.run(ssl_context=('cert.pem', 'key.pem'), host='0.0.0.0', port='80')
# The following line works totally fine, but is not HTTPS.
app.run('0.0.0.0', '80')
All the code is in a file called main.py which I am running on a Ubuntu machine with the command sudo -E python3 main.py.
Running with app.run('0.0.0.0', '80') gives me this output (which is normal, and I can connect):
* Serving Flask app 'main' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployment.
* Running on http://127.0.0.1:80
* Running on http://192.168.1.34:80 (Press CTRL+C to quit)
Running with either other option gives me this output (which is normal, but I CAN'T connect):
* Serving Flask app 'main' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployment.
* Running on https://127.0.0.1:80
* Running on https://192.168.1.34:80 (Press CTRL+C to quit)
Extra Information:
I was following a very helpful tutorial here: https://blog.miguelgrinberg.com/post/running-your-flask-application-over-https, and it seems like everything is working as intended (which is why I came to Stack Overflow to ask this question).
I have pyopenssl installed.
I ran openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365 and it executed fine. The cert.pem and key.pem files were (I assume) correctly generated.
Solution 1:[1]
SSL usually runs via port 443, so changing it to that might fix the problem. If you look closely in the tutorial, they haven't defined it at all and let Flask figure out where to run itself.
If your browser simply tells you that "Your connection is not private" or "Can't verify certificate" or something along those lines, you can usually skip that message. But should use something like Let's Encrypt if you wanna go public with your WebApp.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jonii |
