Skip to content Skip to sidebar Skip to footer

How To Set Wsgi.url_scheme To Https In Bottle?

I want to redirect all requests to http to https. Is there a generic approach to setting wsgi.url_scheme to https in a Python 2.7 bottle application? The general structure of the

Solution 1:

Forgive me if I'm not understanding your question, but why not just install a simple redirect plugin for your Bottle app? Something like this:

import bottle

app = bottle.app()

def redirect_http_to_https(callback):
    '''Bottle plugin that redirects all http requests to https'''

    def wrapper(*args, **kwargs):
        scheme = bottle.request.urlparts[0]
        if scheme == 'http':
            # request is http; redirect to https
            bottle.redirect(bottle.request.url.replace('http', 'https', 1))
        else:
            # request is already https; okay to proceed
            return callback(*args, **kwargs)
    return wrapper

bottle.install(redirect_http_to_https)

@bottle.route('/hello')
def hello():
    return 'hello\n'

bottle.run(host='127.0.0.1', port=8080)

Tested with curl:

% 05:57:03 !3000 ~>curl -v 'http://127.0.0.1:8080/hello'
* Connected to 127.0.0.1 (127.0.0.1) port 8080 (#0)
> GET /hello HTTP/1.1
> User-Agent: curl/7.30.0
> Host: 127.0.0.1:8080
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 303 See Other
< Date: Sun, 01 Dec 2013 10:57:16 GMT
< Server: WSGIServer/0.1 Python/2.7.5
< Content-Length: 0
< Location: https://127.0.0.1:8080/hello
< Content-Type: text/html; charset=UTF-8

For details on how plugins work, see the Bottle docs.

Briefly, this plugin works by intercepting all requests and checking the protocol ("scheme"). If the scheme is "http", the plugin instructs Bottle to return an HTTP redirect to the corresponding secure (https) URL.


Post a Comment for "How To Set Wsgi.url_scheme To Https In Bottle?"