Search code examples
pythoncherrypy

In a CherryPy dispatcher, get the original path including the query string


I have a CherryPy application with a custom dispatcher, inheriting from cherrypy._cpdispatch.Dispatcher. In its method def __call__(self, path): ..., I can get the requested path as the argument path. The path doesn't include the query string, nor does cherrypy.url. I've found that I can get the query string separately as cherrypy.request.query_string. Of course, if I raise a redirect in the dispatcher, such as

raise cherrypy.HTTPRedirect(transform(path), 301)

then the query string is lost.

I want to preserve the query string after a redirect. Is there a way to get the original path or URL, including the query string? If not, should I reconstruct it with something like path + (if query_string then '?' + query_string else ''), or is there a better way to do this?


Solution

  • I realized that cherrypy.url has some useful parameters.

    • To get the full URL, like "http://example.com/foo/bar?arg=1", say cherrypy.url(qs = cherrypy.request.query_string).
    • To get the full server-relative path, like "/foo/bar?arg=1", say cherrypy.url(qs = cherrypy.request.query_string, relative = "server").