如何在请求启动后self.redirect
之后停止执行?
方法重定向不会停止/暂停脚本执行。我调用了我的initilizer方法,但该过程继续进入方法AnswerHandler.get()
,但self.user
为None,因为用户未被记录。
class BaseRequestHandler(webapp.RequestHandler):
def __init__(self):
self.user = None
def initialize(self, request=None, response=None):
super(BaseRequestHandler,self).initialize(request, response)
user = users.get_current_user()
if not user:
return self.redirect(users.create_login_url(request.uri))
self.user = user
class AnswerHandler(BaseRequestHandler):
def get(self):
answer = Answer.next_answer_by_user(self.user)
self.write_template({"answer" : answer})
坦克!
答案 0 :(得分:3)
我会选择这个解决方案:
class BaseRequestHandler(webapp.RequestHandler):
def __init__(self):
self.user = None
def setAuthUser(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(request.uri))
return False
self.user = user
return True
class AnswerHandler(BaseRequestHandler):
def get(self):
if not self.setAuthUser():
return
answer = Answer.next_answer_by_user(self.user)
self.write_template({"answer" : answer})
据我所知,您希望在每个处理程序中都有两行代码。
如果你真的想要,你的另一个选择是:
class BaseRequestHandler(webapp.RequestHandler):
def __init__(self):
self.user = None
def get(self):
self.user = users.get_current_user()
if not self.user:
self.redirect(users.create_login_url(request.uri))
return
self.doGet()
def doGet(self):
raise Exception("doGet() needs to be implemented by a subclass.")
class AnswerHandler(BaseRequestHandler):
def doGet(self):
answer = Answer.next_answer_by_user(self.user)
self.write_template({"answer" : answer})
答案 1 :(得分:1)
使用webapp2,有一个可选的abort参数:
重定向(uri,permanent = False,abort = False,code = None,body = None)
取自api here
答案 2 :(得分:0)
我通过使用abort()方法并使用自定义异常处理程序来完成此操作,从而捕获异常