15

I have a client server application. I managed to make them connect over https using SSl encryption using this

    context = SSL.Context(SSL.SSLv3_METHOD)
    context.use_privatekey_file('/path_to_key/key.key')
    context.use_certificate_file('/path_to_cert/cert.crt')
    app.run(use_reloader=True, host='0.0.0.0',port=9020,ssl_context = context)

Now I want to run the server using both http and https. Is there any possible way to do that?

1

4 Answers 4

13

First big thing: don't use the built in web server in flask to do any heavy lifting. You should use a real web server like apache (mod_wsgi) nginex + gunicore, etc. These servers have documentation on how to run http and https simultaneously.

4
  • Well i am using apache with mod_wsgi to run flask, i've managed to configure apache to use both (http and https) on diffrent ports 80 and 443 it's working fine with https but http connection is not working as long as ssl_context is enabled in Flask Sep 23, 2013 at 15:02
  • Dont use app.run when you are running behind a real server.
    – Tritium21
    Sep 23, 2013 at 15:05
  • what should i use then ? Sep 23, 2013 at 15:13
  • just let the wsgi server (mod_wsgi, gunicorn) run your application. app.run runs the built in web server.
    – Tritium21
    Sep 23, 2013 at 15:16
8

My I suggest trying out Flask-SSLify - https://github.com/kennethreitz/flask-sslify

Usage

Usage is pretty simple:

from flask import Flask
from flask_sslify import SSLify

app = Flask(__name__)
sslify = SSLify(app)

If you make an HTTP request, it will automatically redirect:

$ curl -I http://secure-samurai.herokuapp.com/
HTTP/1.1 302 FOUND
Content-length: 281
Content-Type: text/html; charset=utf-8
Date: Sun, 29 Apr 2012 21:39:36 GMT
Location: https://secure-samurai.herokuapp.com/
Server: gunicorn/0.14.2
Strict-Transport-Security: max-age=31536000
Connection: keep-alive

Install

Installation is simple too:

$ pip install Flask-SSLify
2
  • 11
    This does not answer this question.
    – Tritium21
    Jun 17, 2015 at 2:49
  • this also does not work for creating SSL-enabled connecion for Slack
    – CKM
    Jul 18, 2017 at 10:35
2

Now i want to run the server using both http and https is there any possible way to do that ??

I have had a similar problem recently. To test whether a proxy is used after http is redirected to https, I've just started two processes on different ports: one for http, another for https:

#!/usr/bin/env python3
"""Serve both http and https. Redirect http to https."""
from flask import Flask, abort, redirect, request # $ pip install flask

app = Flask(__name__)

@app.route('/')
def index():
    if request.url.startswith('http://'):
        return redirect(request.url.replace('http', 'https', 1)
                        .replace('080', '443', 1))
    elif request.url.startswith('https://'):
        return 'Hello HTTPS World!'
    abort(500)

def https_app(**kwargs):
    import ssl
    context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
    context.load_cert_chain('server.crt', 'server.key')
    app.run(ssl_context=context, **kwargs)


if __name__ == "__main__":
    from multiprocessing import Process

    kwargs = dict(host='localhost')
    Process(target=https_app, kwargs=dict(kwargs, port=7443),
            daemon=True).start()
    app.run(port=7080, **kwargs)

Needless to say, it is only for testing/debugging purposes.

0

I've ran into trouble with this also. I originally had:

    if sys.argv[1] == 'https' or sys.argv[1] == 'Https':
        app.run(host="0.0.0.0", port=12100, ssl_context='adhoc')
    elif sys.argv[1] == 'http' or sys.argv[1] == 'HTTP':
        app.run(host="0.0.0.0", port=12100)

which only allowed either http or https at a time and not both.

So I used multi-threading to make both work at the same time. I put each app.run in it's own function and called an independent thread on each one of them.

import threading
import time as t

...

def runHttps():
    app.run(host="0.0.0.0", port=12101, ssl_context='adhoc')

def runHttp():
    app.run(host="0.0.0.0", port=12100)

if __name__ == '__main__':
    # register_views(app)
    CORS(app, resources={r"*": {"origins": "*"}}, supports_credentials=True)
    if sys.argv[1] == 'https' or sys.argv[1] == 'Https' or sys.argv[1] == 'http' or sys.argv[1] == 'Http':
        print("here")
        y = threading.Thread(target=runHttp)
        x = threading.Thread(target=runHttps)
        print("before running runHttps and runHttp")
        y.start()
        t.sleep(0.5)
        x.start()

And that's how I made http and https work at the same time.

Not the answer you're looking for? Browse other questions tagged or ask your own question.