Skip to content

Instantly share code, notes, and snippets.

@vpack
Last active October 20, 2023 07:59
Show Gist options
  • Save vpack/2d5f3f89affcc58dac462edbfdd5c119 to your computer and use it in GitHub Desktop.
Save vpack/2d5f3f89affcc58dac462edbfdd5c119 to your computer and use it in GitHub Desktop.
Flask SSL Sample APP
from flask import Flask
from flask_sslify import SSLify
"""
Option 1 : (pip install pyopenssl)
from OpenSSL import SSL
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('web.key')
context.use_certificate_file('web.crt')
Option 2 : (OOB : No install)
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain('web.crt', 'web.key')
Option 3 : Native Flask (No imports needed)
"""
app = Flask(__name__)
context = ('web.crt', 'web.key')
sslify = SSLify(app)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
context = ('web.crt', 'web.key')
app.run( debug = True, ssl_context = context)
#app.run( debug = True, ssl_context = 'adhoc') # Generate Adhoc Certs
@fcovlz
Copy link

fcovlz commented May 3, 2020

Thanks for this info. Using option 2, I have an issue with the crt and key files. Do you where are they stored by default? I looked into Python2/Python3 folders respectively and find nothing.

context.load_cert_chain('web.crt', 'web.key')
FileNotFoundError: [Errno 2] No such file or directory

@paulchabotca
Copy link

Thanks for this info. Using option 2, I have an issue with the crt and key files. Do you where are they stored by default? I looked into Python2/Python3 folders respectively and find nothing.

context.load_cert_chain('web.crt', 'web.key')
FileNotFoundError: [Errno 2] No such file or directory

You need to make your certs and place them in the directory.

Here is a page explaining making a self-signed cert.
Self Signed Certificates - devcenter.heroku.com

if you need something for online, check out lets-encrypt.

@lidkicker
Copy link

Just want to note that if anyone's having issues loading the .crt and .key files and they had converted them from .pem files, it's possible the conversion wasn't necessary - it wasn't in my case (running on diet-pi using letsencrypt/certbot to gen keys) and in fact threw the following error:

OpenSSL.SSL.Error: [('PEM routines', 'get_name', 'no start line'), ('SSL routines', 'SSL_CTX_use_PrivateKey_file', 'PEM lib')]

@antoniojsp
Copy link

when I use ssl_context = 'adhoc', everything runs but it doesn't show anything in the web browser. (it shoows in the terminal that it's running at https but doesn't work in the webbrowser) Any suggestion?

@omarnazih
Copy link

I have same problem as @antoniojsp , did you find a solution?

@TyLaneTech
Copy link

I'm having the same problem @antoniojsp @omarnazih
Any answers?

@LauraFgar
Copy link

Tengo el mismo problema, alguna solución?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment