tehryan
tehryan

Reputation: 775

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

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

Upvotes: 16

Views: 12571

Answers (2)

A. Coady
A. Coady

Reputation: 57338

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.

Upvotes: 37

Alex Martelli
Alex Martelli

Reputation: 881735

For complete generality, change

    def index(self, var = None):

to

    def index(self, *vars):

vars will be bound to a tuple, which is empty if no arguments were passed, has one item if one argument was passed, two if two, and so forth. It's then up to your code to deal with various such cases sensibly and appropriately, of course.

Upvotes: 1

Related Questions