How can I force cherrypy to accept a variable number of GET parameters?

tehryan picture tehryan · Jan 3, 2010 · Viewed 11.7k times · Source

for instance, say I have my cherrypy index module set up like this

>>> import cherrypy
>>> class test:
        def index(self, var = None):
            if var:
                print var
            else:
                print "nothing"
        index.exposed = True

>>> cherrypy.quickstart(test())

If I send more than one GET parameter I get this error

404 Not Found

Unexpected query string parameters: var2

Traceback (most recent call last):
File "C:\Python26\lib\site-packages\cherrypy_cprequest.py", line 606, in respond cherrypy.response.body = self.handler() File "C:\Python26\lib\site-packages\cherrypy_cpdispatch.py", line 27, in call test_callable_spec(self.callable, self.args, self.kwargs) File "C:\Python26\lib\site-packages\cherrypy_cpdispatch.py", line 130, in test_callable_spec "parameters: %s" % ", ".join(extra_qs_params)) HTTPError: (404, 'Unexpected query string parameters: var2')

Powered by CherryPy 3.1.2

Answer

A. Coady picture A. Coady · Jan 3, 2010
def index(self, var=None, **params):

or

def index(self, **params):

'var2' will be a key in the params dict. In the second example, so will 'var'.

Note the other answers which reference the *args syntax won't work in this case, because CherryPy passes query params as keyword arguments, not positional arguments. Hence you need the ** syntax.