python 如何强制cherrypy接受可变数量的GET参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1993604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I force cherrypy to accept a variable number of GET parameters?
提问by tehryan
for instance, say I have my cherrypy index module set up like this
例如,假设我的cherrypy索引模块设置如下
>>> 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
如果我发送多个 GET 参数,我会收到此错误
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 calltest_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
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, 'Unexpected query string parameters: var2')由 CherryPy 3.1.2 提供支持
回答by A. Coady
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'.
'var2' 将是 params 字典中的一个键。在第二个例子中,'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.
请注意,在这种情况下,引用 *args 语法的其他答案将不起作用,因为 CherryPy 将查询参数作为关键字参数传递,而不是位置参数。因此你需要 ** 语法。
回答by Alex Martelli
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.
vars
将绑定到一个元组,如果没有传递参数,则该元组为空,如果传递一个参数,则为一项,如果传递两个,则为两项,依此类推。当然,然后由您的代码明智地和适当地处理各种此类情况。