Search code examples
pythonwebcherrypy

How to get name of a required page in CherryPy?


I know that in CherryPy requested pages are bound to the functions with the same names. For example

import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    def hello(self):
        return "Hello Hello2!"
    index.exposed = True
    hello.exposed = True

cherrypy.quickstart(HelloWorld())

if we go to 127.0.0.1:8080/hello we get Hello Hello2!.

However, I need a more flexible behavior. I do not know in advance what URL will be requested, I just want to be able to determine with CherryPy the requested URL. For example if 127.0.0.1:8080/goodbye is requested, I want to know that some variable is equal to goodbye and than based on the found value, I start a certain functionality.


Solution

  • +1 For @Burhan's answer. However for a simple working example you'll only need something like this:

    import cherrypy
    
    class HelloWorld(object):
        @cherrypy.expose
        def default(self, *args, **kwargs):
            return "Hello world!" + cherrypy.url()
    
    cherrypy.quickstart(HelloWorld())