【问题标题】:Redirect by handler由处理程序重定向
【发布时间】:2014-06-09 10:31:25
【问题描述】:
我正在为 appengine 寻找类似于烧瓶框架 url_for 的功能。它需要一个类名重定向到在 webapp2.WSGIApplication 中与之关联的 url。
如果我有这个。
app = webapp2.WSGIApplication([
("/", PostsPage),
("/login", LoginPage),
], debug=True)
所以redirect(url_for(LoginPage)) 会将我重定向到 /login。
【问题讨论】:
标签:
google-app-engine
webapp2
【解决方案1】:
如果您可以访问传递给 WSGIApplication 构造函数的参数,这相对容易构建:
class PostsPage:
pass
class LoginPage:
pass
urls = [
("/", PostsPage),
("/login", LoginPage),
]
def url_for(cls):
return [x[0] for x in urls if x[1] == cls][0]
print url_for(LoginPage)
【解决方案2】:
您可以命名不同的“路线”,例如
app = webapp2.WSGIApplication([
webapp2.Route(r'/', handler=PostsPage, name ='main'),
webapp2.Route(r'/login', handler=LoginPage, name ='login'),
], debug = True)
现在您可以按照您的建议或使用名称重定向
return self.redirect_to('login')或return self.redirect_to(main`)
我已经包含了一个返回语句,因为重定向首先发生在您返回之后。