我想做这样的事情:
class Basehandler(webapp.RequestHandler):
def __init__(self):
if checkforspecialcase: #check something that always needs to be handled
return SpecialCaseHandler.get()
class NormalHandler(Basehandler):
def get(self):
print 'hello world'
return
class SpecialCaseHandler(Basehandler):
def get(self):
print 'hello special world'
return
这个想法是,无论最初调用哪个处理程序,如果满足某个特定情况,我们基本上都会切换到另一个处理程序。
我对python很新,所以我不确定我是否有可能做的事情。或者这是否是最佳方法。我真正要做的是确保向某人展示完整的你的个人资料页面,如果他们已经开始注册过程但尚未完成它......无论他们提出什么要求。所以“checkforspecialcase”会查看他们的会话并检查不完整的信息。
答案 0 :(得分:3)
WSGIApplication根据URL路由传入的请求。例如,
application = webapp.WSGIApplication(
[('/special-case', SpecialCaseHandler)])
当checkforspecialcase
通过时,您可以使用self.redirect('/special-case')
。
答案 1 :(得分:3)
要保持干爽,请使用Template Method pattern
class BaseHandler(webapp.RequestHandler):
def DoGet(self, *args):
''' defined in derived classes, actual per-handler get() logic'''
pass
def get(self, *args):
# don't get caught in endless redirects!
if specialCase and not self.request.path.startswith('/special'):
self.redirect('/special')
else:
self.DoGet(*args)
class NormalHandler(BaseHandler):
def DoGet(self, *args):
# normal stuff
class SpecialHandler(BaseHandler):
def DoGet(self, *args):
# SPECIAL stuff
答案 2 :(得分:0)
你的Basehandler可以实现一个get()来检查特殊情况并重定向或调用self.view(),并且每个处理程序都可以实现view()(或者你想要调用它的任何东西)而不是得到()。
我不是真的为每个处理程序编写一个类,或者使用继承如此引人注目,所以我建议像这样滚动装饰器:
routes = []
def get (route):
def makeHandler (handle, *args, **kwargs):
class Handler (webapp.RequestHandler):
def get (self, *args, **kwargs):
shouldRedirectToCompleteProfile = # do your test
if shouldRedirectToCompleteProfile:
self.redirect('/special-case')
else:
handle(self, *args, **kwargs)
routes.append((route, Handler))
return Handler
return makeHandler
def post (route):
def makeHandler (handle, *args, **kwargs):
class Handler (webapp.RequestHandler):
def post (self, *args, **kwargs):
handle(self, *args, **kwargs)
routes.append((route, Handler))
return Handler
return makeHandler
@get('/')
def home (ctx):
# <...>
@get('/whatever/(.*)/(.*)')
def whatever (ctx, whatever0, whatever1):
# <...>
@post('/submit')
def submit (ctx):
# <...>
application = webapp.WSGIApplication(routes)