【问题标题】:Parsing url with webapp2 handler Python GAE使用 webapp2 处理程序 Python GAE 解析 url
【发布时间】:2016-05-14 13:53:24
【问题描述】:

考虑以下代码:

class Activate(BaseHandler):
    def get(self, key):
    self.response.out.write(key)
application = webapp2.WSGIApplication([('/activationlink/([^/]+)?', Activate)],debug=True,config=config)

我想知道处理程序如何“知道” /activationlink/ 之后的部分实际上是关键?是模式 /string/string2 的每个 URL 都向处理程序发送一个 key = string2 吗?如果有,是在webapp2.RequestHandler类中设置的吗?

【问题讨论】:

    标签: python google-app-engine


    【解决方案1】:

    看看这个例子:

    class ProductHandler(webapp2.RequestHandler):
    def get(self, product_id):
        self.response.write('You requested product %r.' % product_id)
    
    app = webapp2.WSGIApplication([
        (r'/products/(\d+)', ProductHandler),
    ])
    

    handler 方法接收从 URI 中提取的product_id,并设置一个包含 id 的简单消息作为响应。

    如您所见,\d+ 定义我们正在发送一个正整数。

    参数是位置的。所以,如果你这样做:

    ...
    (r'/products/(\d+)/(\d+)', ProductHandler)
    ...
    

    您的方法必须接收这些参数(按 url 的顺序),如下所示:

    ...
    def get(self, param1, param2):
        ...
    

    如果您想了解更多信息,请阅读此处的文档:

    希望对你有所帮助。

    【讨论】:

      【解决方案2】:

      来自 webapp2 URI routing 中的简单路由部分:

      class ProductHandler(webapp2.RequestHandler):
          def get(self, product_id):
              self.response.write('This is the ProductHandler. '
                  'The product id is %s' % product_id)
      
      app = webapp2.WSGIApplication([
          (r'/', HomeHandler),
          (r'/products', ProductListHandler),
          (r'/products/(\d+)', ProductHandler),
      ])
      

      ...

      regex部分是一个普通的正则表达式(见re模块) 可以在括号内定义组。匹配的组值 作为位置参数传递给处理程序。在示例中 上面,最后一个路由定义了一个组,所以处理程序将收到 路由匹配时的匹配值(此中的一位或多位数字 案例)。

      在您的情况下,([^/]+) 是有问题的正则表达式组,它将匹配的内容转换为传递给 Activate.get()key

      【讨论】:

        猜你喜欢
        • 2012-02-06
        • 1970-01-01
        • 2013-03-24
        • 2018-08-11
        • 1970-01-01
        • 2013-02-09
        • 2018-03-29
        • 2017-01-13
        • 2012-12-02
        相关资源
        最近更新 更多