【问题标题】:What's the best practice to use named Route in AppEngine?在 AppEngine 中使用命名路由的最佳做法是什么?
【发布时间】:2012-09-19 07:31:30
【问题描述】:

在 app.yaml 文件中,我放了 2 行来指定 url 映射:

  • 网址:/blog/.* 脚本:blog.app

  • 网址:/ 脚本:home.app

问题是我不能使用“uri_for”函数为home.py中的博客模块生成一个url,如果主页模块中没有添加路由:

这是 home 模块中的代码:

    app = webapp2.WSGIApplication([
       webapp2.Route(r'/', handler=HomeHandler, name='home')
    ], debug = SITE_CONFIG['is_debug'], config=SITE_CONFIG)

和 blog.py 中的代码:

    app = webapp2.WSGIApplication([
    webapp2.Route(r'/blog/<blog_id:\d+>', handler=BlogHandler,    name="blog")
    ], debug = SITE_CONFIG['is_debug'], config=SITE_CONFIG)

所以,如果我在 home.html 中有这样的代码:{{ uri_for('blog', blog_id=blabla) }},它就无法工作。

【问题讨论】:

    标签: google-app-engine


    【解决方案1】:

    您应该将这些路线整合到一个应用程序中。

    app = webapp2.WSGIApplication([
           webapp2.Route(r'/', handler=HomeHandler, name='home'),
           webapp2.Route(r'/blog/<blog_id:\d+>', handler=BlogHandler, name="blog")
        ], debug = SITE_CONFIG['is_debug'], config=SITE_CONFIG)
    

    实际上这些只是查看博客帖子的路线。

    如果您想做一个完整的 CRUD 应用程序,您可能需要添加更多内容。

    app = webapp2.WSGIApplication([
            webapp2.Route(r'/admin/blog', handler='admin.AdminBlogHandler:list, name="admin.blog.list"),
            webapp2.Route(r'/admin/blog/new', handler='admin.AdminBlogHandler:new', name='admin.blog.edit'),
            webapp2.Route(r'/admin/blog/<id:[^/]+>/edit', handler='admin.AdminBlogHandler:edit', name='admin.blog.edit'),
            webapp2.Route(r'/admin/blog/<id:[^/]+>', handler='admin.AdminBlogHandler:view', name='admin.blog.view')
        ], debug = SITE_CONFIG['is_debug'], config=SITE_CONFIG)
    

    这些例子的注意事项:

    1) 为从不同文件加载处理程序的名称添加前缀(admin.AdminBlogHandler 将在 'admin.py' 中查找 'class AdminBlogHandler'

    2) 在处理程序名称之后,冒号之后指定要运行的方法。

    3) 在每种方法中,我都在为获取和发布创建功能,因此没有用于编辑和更新的离散 RESTful URL。

    【讨论】:

      猜你喜欢
      • 2011-07-14
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2012-10-14
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      相关资源
      最近更新 更多