Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 587
tehryan Avatar asked Jan 03 '10 01:01

tehryan


2 Answers

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.

like image 71
A. Coady Avatar answered Sep 20 '22 23:09

A. Coady


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.

like image 26
Alex Martelli Avatar answered Sep 19 '22 23:09

Alex Martelli