How to run localhost with https in flask?

Member

by aubrey , in category: PHP General , 4 days ago

How to run localhost with https in flask?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 4 days ago

@aubrey 

To run Flask with HTTPS on localhost, you will need to create an SSL certificate and key. Here's how you can do it:

  1. Generate a self-signed SSL certificate and key using OpenSSL. Open a terminal and run the following command:
1
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365


Follow the prompts to provide the necessary information for the certificate.

  1. Create a Flask app that serves over HTTPS. Here's an example of a basic Flask app that serves over HTTPS:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(ssl_context=('cert.pem', 'key.pem'))


  1. Save the SSL certificate (cert.pem) and SSL key (key.pem) in the same directory as your Flask app.
  2. Run your Flask app using the following command:
1
python your_flask_app.py


Your Flask app should now be running on HTTPS on localhost. You can access it at https://localhost:5000. Please note that since this is a self-signed certificate, your browser may show a privacy error when accessing the site. You can proceed to the site by accepting the risk.