webapp2.Route带有可选的前导部分

zen*_*bor 4 google-app-engine webapp2

我正在学习webapp2框架及其强大的Route机制.

我的应用程序应该接受这样的URI:

/poll/abc-123
/poll/abc-123/
/poll/abc-123/vote/       # post new vote
/poll/abc-123/vote/456    # view/update a vote
Run Code Online (Sandbox Code Playgroud)

民意调查可以选择组织成类别,因此上述所有内容也应该如下:

/mycategory/poll/abc-123
/mycategory/poll/abc-123/
/mycategory/poll/abc-123/vote/
/mycategory/poll/abc-123/vote/456
Run Code Online (Sandbox Code Playgroud)

我的配置错误:

app = webapp2.WSGIApplication([
    webapp2.Route('/<category>/poll/<poll_id><:/?>', PollHandler),
    webapp2.Route('/<category>/poll/<poll_id>/vote/<vote_id>', VoteHandler),
], debug=True)
Run Code Online (Sandbox Code Playgroud)

问题:如何修复配置?

如果可能,应针对GAE CPU时间/托管费进行优化.例如,如果我为每个条目添加两行可能会更快:一行包含类别,另一行没有类别...

mor*_*aes 7

webapp2有一种重用公共前缀的机制,但在这种情况下它们会有所不同,因此您无法避免重复这些路由,如:

app = webapp2.WSGIApplication([
    webapp2.Route('/poll/<poll_id><:/?>', PollHandler),
    webapp2.Route('/poll/<poll_id>/vote/<vote_id>', VoteHandler),
    webapp2.Route('/<category>/poll/<poll_id><:/?>', PollHandler),
    webapp2.Route('/<category>/poll/<poll_id>/vote/<vote_id>', VoteHandler),
], debug=True)
Run Code Online (Sandbox Code Playgroud)

您不必担心添加许多路线.他们建造和匹配真的很便宜.除非你有成千上万,否则减少路线数量无关紧要.

小注意:第一个路由接受可选的结束斜杠.您可以改为使用RedirectRoute仅接受一个,如果访问另一个,则使用该选项重定向strict_slash=True.这没有很好的记录,但已经存在了一段时间.请参阅docstring中说明.