【问题标题】:Google App engine Url Mapping using WSGIAppl and regex grouping Help NeededGoogle App engine Url Mapping using WSGIAppl and regex grouping 需要帮助
【发布时间】:2010-05-19 10:05:36
【问题描述】:

以谷歌文档为例

class BrowseHandler(webapp.RequestHandler):

>     def get(self, category, product_id):
>         # Display product with given ID in the given category.
> 
> 
> # Map URLs like /browse/(category)/(product_id) to
> BrowseHandler. application =
> webapp.WSGIApplication([(r'/browse/(.*)/(.*)',
> BrowseHandler)
>                                      ],
>                                      debug=True)
> 
> def main():
>     run_wsgi_app(application)
> 
> if __name__ == '__main__':
>     main()

如何更改 regx 分组以便产品 id 是可选的

即在上面的当前示例中,URL http://yourdomain.com/category 将被发送到浏览处理程序,您必须在类别之后添加产品 ID 或至少 /

http://yourdomain.com/category/

r'/browse/(.)/(.)'

有什么想法吗?

【问题讨论】:

    标签: google-app-engine url-mapping


    【解决方案1】:

    您可以使用映射到同一个处理程序的两个正则表达式:

    class BrowseHandler(webapp.RequestHandler):
    
        def get(self, category, product_id=None):
            # Display product with given ID in the given category.
    
    
    # Map URLs like /browse/(category)/(product_id) to
    BrowseHandler. application =
    webapp.WSGIApplication([(r'/browse/(.*)/(.*)', BrowseHandler),
                            (r'/browse/(.*)', BrowseHandler),
                           ], debug=True)
    
    def main():
        run_wsgi_app(application)
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

    • 此解决方案有效,但映射需要以相反的顺序 - 简单错误。 (r'/(.*)/(.*)', ns_cardHandler), (r'/(.*)', ns_cardHandler) 工作正常!
    • 如果我想选择 mime 类型比如 path.html 或 path.rss 或 path.json 那么在我的处理程序中我可以有 def get(self, category, product_id=None, mime ): 所以一个有效的路径可能是 tv/1010.html 我可以这样做是正则表达式并将其传递给处理程序吗?
    【解决方案2】:

    尝试添加“?”在你的正则表达式结束之前:

    r'/browse/(.)/(.)?'
    

    【讨论】:

    • 不,这不起作用会在应用程序引擎 python 中引发错误 - 我还需要 /(.*) 是可选的 Jbochi 解决方案将工作,因为第一个 regx 只需要一个 arg。这可以使用一个表达式来完成吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多