我的路由对我很有用,但它是很长一段时间构建的,因为框架已更新为webapp2所以我混合路由并且不知道哪种方式最好。你能帮我改进哪些以及如何进行路由?是否更好的方法是让框架让路由器为处理程序设置默认值,或者将路由设置在处理程序的正上方?
app = webapp2.WSGIApplication([
('/', HomeHandler),
('/shop', FileUploadFormHandler),
('/mypage', MyPageHandler),
webapp2.Route(r'/newpassword/', handler=NewPassword, name='newpassword'),
webapp2.Route(r'/signup/', handler=Signup, name='signup'),
webapp2.Route(r'/myorg/', handler=Myorg, name='signup'),
webapp2.Route(r'/register/', handler=Register, name='register'),
webapp2.Route(r'/education/objectives/index', handler=Objectives, name='objectives'),
webapp2.Route(r'/newdistributor/', handler=NewDistributor, name='newdistributor'),
webapp2.Route(r'/emaillogin/', handler=Emaillogin, name='emaillogin'),
webapp2.Route(r'/paysonreceive/', handler=PaysonReceiveHandler, name='paysonreceivehandler'),
webapp2.Route(r'/paysonhandler/', handler=PaysonHandler, name='paysonhandler'),
webapp2.Route('/passwdreset/<token>', handler=PasswordReset, name='passwordreset'),
('/shop/articles', ShopHandler),
('/info', InfoHandler),
('/update', UpdateHandler),
('/support', SupportHandler),
('/events.*', EventHandler),
('/academy', AcademyHandler),
('/marketing.*', MarketingHandler),
('/dropbox', FileUploadFormHandler),
('/upload', FileUploadHandler),
('/user/register', UserRegisterHandler),
('/tracker', TrackerHandler),
('/generate_upload_url', GenerateUploadUrlHandler),
('/file/([0-9]+)', FileInfoHandler),
('/file/([0-9]+)/download', FileDownloadHandler),
('/file/([0-9]+)/success', AjaxSuccessHandler),
('/home', Home),
('/paypal', Home),
('/sell', Sell),
('/sell/(.*)/', Sell),
('/buy/(.*)/return/(.*)/(.*)/', BuyReturn),
('/buy/(.*)/cancel/(.*)/', BuyCancel),
('/buy/(.*)/', Buy),
('/image/(.*)/', PPImage),
webapp2.Route(r'/login/', handler=NewLoginHandler, name='login'),
webapp2.Route(r'/logout/', handler=NewLogoutHandler, name='logout'
),
webapp2.Route(r'/secure/', handler=SecureRequestHandler,
name='secure'),
webapp2.Route(r'/create/', handler=CreateUserHandler,
name='create-user'),
], config=config)
因此,在添加新URI时,我必须同时添加到app.yaml,路由和处理程序clas以及不理想的模板,因为这些太多的地方只是为了从WSGI获得响应而添加内容。所以我想重新编写代码以使其使用更多默认值,例如,如果我添加一个RequestHandler类,那么它应该有一个默认路由,因为它已经有一个唯一的名称。框架能做到吗?
感谢您的回答或评论
答案 0 :(得分:1)
我认为创建默认路由不是一个好主意,但您应该能够创建它。例如:
import pages1
import pages2
def route_generator(modules):
urls = []
for m in modules:
for h in dir(m):
handler = eval("%s.%s"%(m.__name__, h))
if issubclass(handler, webapp.RequestHandler):
urls.append(('/%s/'%(handler.__name__), handler))
return urls
# list all module contained your handler class.
# and use a generator to generate the url mapping.
app = webapp2.WSGIApplication(route_generator([pages1,pages2], config=config)