How to run localhost with https in flask?

Member

by aubrey , in category: PHP General , 5 months ago

How to run localhost with https in flask?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 4 months 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.

Related Threads:

How to run a symfony project in localhost?
How to create a https server on localhost?
How to run npm serve with https?
How to run vue.js dev serve with https?
How to run node on https in windows?
How to run custom domain under https?