开发者

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

开发者 https://www.devze.com 2022-12-15 02:47 出处:网络
for instance, say I have my cherrypy index module set up like this >>> import cherrypy >>> class test:

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 开发者_JS百科= 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消