webapp2 的 dispatch() 方法是做什么用的?
What is webapp2's dispatch() method used for?
我构建了 gae webapps 而无需使用 dispatch() 方法。我在尝试使用 webapp2_extras.auth
时遇到过它,但我不完全理解它的概念以及它如何适应 get()
和 post()
方法。根据其简短文档:
Dispatches the request.
This will first check if there's a handler_method defined in the
matched route, and if not it'll use the method correspondent to the
request method (get()
, post()
etc).
我的理解是它检查我的路由以查看是否存在处理程序 class 来处理请求,但 dispatch()
方法不是在现有处理程序 class 中定义的已经?另外,不是从客户端发出请求 dispatched 吗?
我对它的一些用例感到困惑,尤其是在 webapp_extras.auth
的上下文中。
source code 可能是开始了解此问题的最佳起点。
如果我们只看最后几行,
try:
return method(*args, **kwargs)
except Exception, e:
return self.handle_exception(e, self.app.debug)
它正在调用一个方法,如果该方法调用因异常而失败,它会调用 handle_exception
方法。所以,这解释了 handle_exception
.
的魔力
函数的其余部分是
- 查看请求并确定调用哪个方法(
get
、post
、put
、delete
、...)并确定处理程序是否支持该方法。
- 确定是否应该将任何其他参数传递给处理程序。
至于它如何与 webapp2_extras.auth
一起玩,我认为这取决于您要做什么。我想您可以创建一个处理程序子类来检查用户是否已登录:
class AuthedHandler(webapp2.RequestHandler):
def dispatch(self):
# Check of user is authenticated, otherwise redirect or
# return error response.
super(AuthedHandler, self).dispatch()
我构建了 gae webapps 而无需使用 dispatch() 方法。我在尝试使用 webapp2_extras.auth
时遇到过它,但我不完全理解它的概念以及它如何适应 get()
和 post()
方法。根据其简短文档:
Dispatches the request. This will first check if there's a handler_method defined in the matched route, and if not it'll use the method correspondent to the request method (
get()
,post()
etc).
我的理解是它检查我的路由以查看是否存在处理程序 class 来处理请求,但 dispatch()
方法不是在现有处理程序 class 中定义的已经?另外,不是从客户端发出请求 dispatched 吗?
我对它的一些用例感到困惑,尤其是在 webapp_extras.auth
的上下文中。
source code 可能是开始了解此问题的最佳起点。
如果我们只看最后几行,
try:
return method(*args, **kwargs)
except Exception, e:
return self.handle_exception(e, self.app.debug)
它正在调用一个方法,如果该方法调用因异常而失败,它会调用 handle_exception
方法。所以,这解释了 handle_exception
.
函数的其余部分是
- 查看请求并确定调用哪个方法(
get
、post
、put
、delete
、...)并确定处理程序是否支持该方法。 - 确定是否应该将任何其他参数传递给处理程序。
至于它如何与 webapp2_extras.auth
一起玩,我认为这取决于您要做什么。我想您可以创建一个处理程序子类来检查用户是否已登录:
class AuthedHandler(webapp2.RequestHandler):
def dispatch(self):
# Check of user is authenticated, otherwise redirect or
# return error response.
super(AuthedHandler, self).dispatch()