Search code examples
pythonwebcherrypy

How to use URL regex in CherryPy?


I am trying to add URL regex to CherryPy, but for some reason, not everything works out. Where am I mistaken?

I need URL opts to look like example.com/opts/someopts.

But now with such a request, I get a 404 error.

class SomeClass:
    def __init__(self, config):
         someactions

    @cherrypy.expose
    def opts(self):
        templ = Template(filename='dyn/opts.tmpl', lookup=self.lookup)
        self.token = random.randint(0, 99999999)
        return templ.render(opts=self.config, pageid='SETTINGS', 
        token=self.token, docroot=self.docroot)

d = cherrypy.dispatch.RoutesDispatcher()
d.connect(action='opts', name='opts', route='/opts/:optsname', controller=opts)

conf = {
    '/opts': {
         'request.dispatch': d
     },
}
cherrypy.tree.mount(root=None, config=conf)

Solution

  • If all you want to do is pass query string parameter somehow to the controller (Based on the comments you have added in the question), here is a simple example which (CherryPy 18.1.1):

    import cherrypy
    
    class Opts:
    
        @cherrypy.expose
        def opts(self, optsname):
            return optsname
    
    d = cherrypy.dispatch.RoutesDispatcher()
    d.connect(action='opts', name='opts', route='/opts/{optsname}', controller=Opts(), conditions=dict(method=["GET"]))
    
    conf = {
        '/': {
             'request.dispatch': d
         },
    }
    cherrypy.quickstart(None, '/', config=conf)