Search code examples
pythonpython-3.xcherrypy

How can I show arbitrary pages based oy the URL requested in CherryPy?


For example, if the user were to go to localhost:8080/foobar228, I wouldn't need to hardcode in the request for foobar228 page by defining a function. I want to simply have a function that gives you the requested URL ("foobar228") and other information like GET and POST requests, and returns the HTML to be served. Any way to do this?


Solution

  • Use the default method. Here is an example.

    import cherrypy
    
    
    class Root:
    
        @cherrypy.expose
        def default(self, *url_parts, **params):
            req = cherrypy.request
            print(url_parts)
            body = [
                'Page served with method: %s' % req.method,
                'Query string from req: %s' % req.query_string,
                'Path info from req: %s' % req.path_info,
                'Params (query string + body for POST): %s' % params,
                'Body params (only for POST ): %s' % req.body.params
            ]
            if url_parts: # url_parts is path_info but divided by "/" as a tuple
                if url_parts[0] == 'foobar228':
                    body.append( 'Special foobar page')
                else:
                    body.append('Page for %s' % '/'.join(url_parts))
            else:
                body.append("No path, regular page")
            return '<br>\n'.join(body)
    
    cherrypy.quickstart(Root())
    

    The url segments becomes the positional arguments and any query string (?foo=bar) are part of the keyword arguments of the method, also the body parameters for the POST method are included in the keyword arguments (in this case under the name params in the method definition.