can you add HTTPS functionality to a python flask web server?
Don't use openssl or pyopenssl its now become obselete in python
Refer the Code below
from flask import Flask, jsonify
import os
ASSETS_DIR = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
@app.route('/')
def index():
return 'Flask is running!'
@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
return jsonify(data)
if __name__ == '__main__':
context = ('local.crt', 'local.key')#certificate and key files
app.run(debug=True, ssl_context=context)
- To run HTTPS functionality or SSL authentication in your flask application, first install "pyOpenSSL" python package
pip install pyopenssl
- Next step is to create
cert.pem
andkey.pem
openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
Copy generated
cert.pem
andkey.pem
in your flask application projectAdd
ssl_context=('cert.pem', 'key.pem')
inapp.run()
, like in the example below.
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def index():
return "Flask is running!"
@app.route("/data")
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
return jsonify(data)
if __name__ == "__main__":
app.run(ssl_context=("cert.pem", "key.pem"))
Deploy Flask on a real web server, rather than with the built-in (development) server.
See the Deployment Options chapter of the Flask documentation. Servers like Nginx and Apache both can handle setting up HTTPS servers rather than HTTP servers for your site.
The standalone WSGI servers listed would typically be deployed behind Nginx and Apache in a proxy-forwarding configuration, where the front-end server handles the SSL encryption for you still.
this also works in a pinch
from flask import Flask, jsonify
from OpenSSL import SSL
context = SSL.Context(SSL.PROTOCOL_TLSv1_2)
context.use_privatekey_file('server.key')
context.use_certificate_file('server.crt')
app = Flask(__name__)
@app.route('/')
def index():
return 'Flask is running!'
@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
return jsonify(data)
#if __name__ == '__main__':
# app.run()
if __name__ == '__main__':
app.run(host='127.0.0.1', debug=True, ssl_context=context)