【问题标题】:How can I force cherrypy to accept a variable number of GET parameters?如何强制cherrypy接受可变数量的GET参数?
【发布时间】:2010-01-03 01:33:47
【问题描述】:

例如,假设我的 Cherrypy 索引模块是这样设置的

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

>>> cherrypy.quickstart(test())

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

404 未找到

意外的查询字符串参数: 变量2

回溯(最近一次通话最后一次):
文件 "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 提供支持

【问题讨论】:

  • 请不要接受我的回答并接受 Coady 的正确回答,以便我删除我的。

标签: python cherrypy


【解决方案1】:
def index(self, var=None, **params):

def index(self, **params):

'var2' 将是 params 字典中的一个键。在第二个示例中,'var' 也是如此。

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

【讨论】:

    【解决方案2】:

    为了通用性,更改

        def index(self, var = None):
    

        def index(self, *vars):
    

    vars 将绑定到一个元组,如果没有传递参数,则该元组为空,如果传递了一个参数,则为一项,如果传递了两个,则为两项,依此类推。当然,这取决于您的代码是否明智和适当地处理各种此类情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多