如何强制cherrypy接受可变数量的GET参数?

teh*_*yan 15 python cherrypy

例如,假设我的cherrypy索引模块设置如下

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

>>> cherrypy.quickstart(test())
Run Code Online (Sandbox Code Playgroud)

如果我发送多个GET参数,我会收到此错误

404未找到

意外的查询字符串参数:var2

回溯(最近一次调用最后一次):
文件"C:\ Python26\lib\site-packages\cherrypy_cprequest.py",第606行,在响应cherrypy.response.body = self.handler()文件"C:\ Python26\lib\site-packages\cherrypy_cpdispatch.py​​",第27行,在调用 test_callable_spec(self.callable,self.args,self.kwargs)文件"C:\ Python26\lib\site-packages\cherrypy_cpdispatch.py​​",第130行,在test_callable_spec"参数:%s"%",".join(extra_qs_params))HTTPError:(404,'意外的查询字符串参数:var2')

由CherryPy 3.1.2提供支持

A. *_*ady 35

def index(self, var=None, **params):
Run Code Online (Sandbox Code Playgroud)

要么

def index(self, **params):
Run Code Online (Sandbox Code Playgroud)

'var2'将成为params dict的关键.在第二个例子中,'var'也是如此.

注意引用*args语法的其他答案在这种情况下不起作用,因为CherryPy将查询参数作为关键字参数传递,而不是位置参数.因此,您需要**语法.


Ale*_*lli 1

为了完整的通用性,改变

    def index(self, var = None):
Run Code Online (Sandbox Code Playgroud)

    def index(self, *vars):
Run Code Online (Sandbox Code Playgroud)

vars将绑定到一个元组,如果没有传递任何参数,则该元组为空;如果传递一个参数,则该元组包含一项;如果传递两个参数,则该元组包含两项,依此类推。当然,然后由您的代码明智且适当地处理各种此类情况。