考虑以下代码:
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类中设置的吗?
看看这个例子:
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):
...
如果你想了解更多,请阅读此处的文档:
- 请求处理程序
- URI路由
希望这对你有帮助。
来自webapp2 URI路由中的"简单路由"部分:
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
。