Permalink
Browse files

Add BaseUrlOverride CherryPy tool

  • Loading branch information...
mrled committed Apr 25, 2017
1 parent a767ef2 commit 12c334833addf511261c6acfa69fd49ec315e914
Showing with 39 additions and 1 deletion.
  1. +17 −1 munger.py
  2. +22 −0 util.py
@@ -16,6 +16,7 @@

versionfile = os.path.join(scriptdir, 'deploymentinfo.txt')
cherrypy.tools.mako = cherrypy.Tool('on_start_resource', util.MakoLoader())
cherrypy.tools.baseurloverride = util.BaseUrlOverride()
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

@@ -202,6 +203,19 @@ def configure():
if not configuration:
raise Exception("No configuration file was found")

# Configure environment variable override

if "BIBLEMUNGER_DEBUG" in os.environ.keys():
if os.environ['BIBLEMUNGER_DEBUG'] in ['1', 'true', 'True', 'TRUE']:
configuration['debug'] = True

if "baseurloverride" not in configuration.keys():
configuration['baseurloverride'] = None
if "BIBLEMUNGER_BASEURL_OVERRIDE" in os.environ.keys():
configuration['baseurloverride'] = os.environ["BIBLEMUNGER_BASEURL_OVERRIDE"]

# Normalize configuration so it can be used easily in the application

def ensureabs(path):
return path if os.path.isabs(path) else os.path.join(scriptdir, path)

@@ -272,7 +286,9 @@ def application(environ=None,
'/': {
'tools.mako.directories': os.path.join(scriptdir, 'temple'),
'tools.mako.debug': configuration['debug'],
'tools.staticdir.root': scriptdir},
'tools.staticdir.root': scriptdir,
'tools.baseurloverride.baseurl': configuration['baseurloverride'],
'tools.baseurloverride.on': True},
'/static': {
'tools.staticdir.on': True,
'tools.staticdir.dir': 'static'},
22 util.py
@@ -15,6 +15,28 @@
scriptdir = os.path.dirname(os.path.realpath(__file__))


class BaseUrlOverride(cherrypy.Tool):
"""Override the base URL
When running behind a reverse proxy, the path of the proxy may differ from that of the CherryPy application. For instance, CherryPy may think it's running on http://localhost:8187/, but the reverse proxy makes it available as https://example.com/biblemunger. In that scenario, URLs generated by CherryPy in HTTP redirects, or in HTML, will be localhost URLs, and the reverse proxy will have to rewrite the HTML and/or HTTP headers by parsing the content and doing a regex replace on the URLs - not ideal from a speed or security perspective.
Instead, you can use this tool to tell CherryPy to use a different base URL like so:
cherrypy.tools.baseurloverride = util.BaseUrlOverride()
cherrypy.tree.mount(server, '/', {
'/': {
'tools.baseurloverride.baseurl': 'https://example.com/biblemunger',
'tools.baseurloverride.on': True}})
"""

def __init__(self):
cherrypy.Tool.__init__(self, 'before_request_body', self.setbaseurl, priority=10)

def setbaseurl(self, baseurl=None):
if baseurl:
cherrypy.request.base = baseurl


class MakoHandler(cherrypy.dispatch.LateParamPageHandler):
"""Callable which sets response.body

0 comments on commit 12c3348

Please sign in to comment.