Cherrypy URLs with unknown application mount path

228 Views Asked by At

I have a CherryPy webapp that is hosted by the user. Typically the main application is mounted as such:

cherrypy.tree.mount(root,
                    '/',
                    root.conf
                    )

However, in order to have it work behind a reverse proxy such as nginx, it needs to be able to mount elsewhere, to whatever path the user chooses:

mount = '/my_application'
cherrypy.tree.mount(root,
                    mount,
                    root.conf
                    )

Where mount can be anything the user chooses.

The problem now is that links become broken.

raise cherrypy.HTTPRedirect("/news")

No longer works. It will redirect to address:port/news when I need to redirect to address:port/my_application/news.

I could go through and create a conditional for each url that prepends the application path:

if mount != '/':
    url = mount + '/news'
raise cherrypy.HTTPRedirect(url)

But there must be a better way to do this. I've looked at Request Dispatching but I couldn't get it to re-write urls on the fly.

What is the best way to handle this situation?

1

There are 1 best solutions below

4
On

You can use the helper function cherrypy.url to generate the urls relative to the script_name (/my_application).

You will end up with something like:

raise cherrypy.HTTPRedirect(cherrypy.url('/news'))

Link for the cherrypy.url source: https://github.com/cherrypy/cherrypy/blob/master/cherrypy/_helper.py#L194