gpt4 book ai didi

python - 如何在 self.redirect 后停止执行

转载 作者:太空宇宙 更新时间:2023-11-04 10:56:45 25 4
gpt4 key购买 nike

如何在请求初始化中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})

坦克!

最佳答案

我会选择这个解决方案:

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})

我知道您想解决每个处理程序中必须有 2 行代码的问题。

如果你真的想要那样,你的另一个选择是:

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})

关于python - 如何在 self.redirect 后停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9231880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com