views:

312

answers:

3

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

+1  A: 

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.

Alex Martelli
+2  A: 

If you follow the normal Python conventions of args and kwargs CherryPy should do what you want:

class test:
    def index(self, *args):
        pass

Any additional parameters will be picked up by args. If you want to define explicit parameters in addition, you should have them at the beginning of the method definition:

class test:
    def index(self, var=None, *args):
        pass
Michael Greene
+3  A: 
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.

Coady