Https with Http in Flask Python

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.


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

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.