对于routes的学习,感觉还是看官方文档理解的比较快,主要说明connect和resource

Setting up routes

It is assumed that you are using a framework that has preconfigured Routes for you. In Pylons, you define your routes in the make_map function in your myapp/config/routing.py module. Here is a typical configuration

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  1. from routes import Mapper
  2. map = Mapper()
  3. map.connect(None, "/error/{action}/{id}", controller="error")
  4. map.connect("home", "/", controller="main", action="index")
  5. # ADD CUSTOM ROUTES HERE
  6. map.connect(None, "/{controller}/{action}")
  7. map.connect(None, "/{controller}/{action}/{id}")

Lines 1 and 2 create a mapper.

Line 3 matches any three-component route that starts with “/error”, and sets the “controller” variable to a constant, so that a URL “/error/images/arrow.jpg” would produce:

  1. {"controller": "error", "action": "images", "id": "arrow.jpg"}

Line 4 matches the single URL “/”, and sets both the controller and action to constants. It also has a route name “home”, which can be used in generation. (The other routes have None instead of a name, so they don’t have names. It’s recommended to name all routes that may be used in generation, but it’s not necessary to name other routes.)

Line 6 matches any two-component URL, and line 7 matches any 3-component URL. These are used as catchall routes if we’re too lazy to define a separate route for every action. If you have defined a route for every action, you can delete these two routes.

Note that a URL “/error/images/arrow.jpg” could match both line 3 and line 7. The mapper resolves this by trying routes in the order defined, so this URL would match line 3.

If no routes match the URL, the mapper returns a “match failed” condition, which is seen in Pylons as HTTP 404 “Not Found”.

Here are some more examples of valid routes:

  1. m.connect("/feeds/{category}/atom.xml", controller="feeds", action="atom")
  2. m.connect("history", "/archives/by_eon/{century}", controller="archives",
  3. action="aggregate")
  4. m.connect("article", "/article/{section}/{slug}/{page}.html",
  5. controller="article", action="view")

Extra variables may be any Python type, not just strings. However, if the route is used in generation, str() will be called on the value unless the generation call specifies an overriding value.

Other argument syntaxes are allowed for compatibility with earlier versions of Routes. These are described in the Backward Compatibility section.

Route paths should always begin with a slash (“/”). Earlier versions of Routes allowed slashless paths, but their behavior now is undefined.

RESTful services

Routes makes it easy to configure RESTful web services. map.resource creates a set of add/modify/delete routes conforming to the Atom publishing protocol.

A resource route addresses members in a collection, and the collection itself. Normally a collection is a plural word, and a member is the corresponding singular word. For instance, consider a collection of messages:

Resource options

The map.resource method recognizes a number of keyword args which modifies its behavior:

controller

Use the specified controller rather than deducing it from the collection name.

collection

Additional URLs to allow for the collection. Example:

  1. map.resource("message", "messages", collection={"rss": "GET"})
  2. # "GET /message/rss" => ``Messages.rss()``.
  3. # Defines a named route "rss_messages".

member

Additional URLs to allow for a member. Example:

  1. map.resource('message', 'messages', member={'mark':'POST'})
  2. # "POST /message/1/mark" => ``Messages.mark(1)``
  3. # also adds named route "mark_message"

This can be used to display a delete confirmation form:

  1. map.resource("message", "messages", member={"ask_delete": "GET"}
  2. # "GET /message/1/ask_delete" => ``Messages.ask_delete(1)``.
  3. # Also adds a named route "ask_delete_message".

new

Additional URLs to allow for new-member functionality.

  1. map.resource("message", "messages", new={"preview": "POST"})
  2. # "POST /messages/new/preview"

path_prefix

Prepend the specified prefix to all URL patterns. The prefix may include path variables. This is mainly used to nest resources within resources.

name_prefix

Prefix the specified string to all route names. This is most often combined with path_prefix to nest resources:

  1. map.resource("message", "messages", controller="categories",
  2. path_prefix="/category/{category_id}",
  3. name_prefix="category_")
  4. # GET /category/7/message/1
  5. # Adds named route "category_message"

parent_resource

A dict containing information about the parent resource, for creating a nested resource. It should contain the member_name and collection_name of the parent resource. This dict will be available via the associated Route object which can be accessed during a request via request.environ["routes.route"].

If parent_resource is supplied and path_prefix isn’t, path_prefix will be generated from parent_resource as “<parent collection name>/:<parent member name>_id”.

If parent_resource is supplied and name_prefix isn’t, name_prefix will be generated from parent_resource as “<parent member name>_”.

Example:

  1. >>> m = Mapper()
  2. >>> m.resource('location', 'locations',
  3. ... parent_resource=dict(member_name='region',
  4. ... collection_name='regions'))
  5. >>> # path_prefix is "regions/:region_id"
  6. >>> # name prefix is "region_"
  7. >>> url('region_locations', region_id=13)
  8. '/regions/13/locations'
  9. >>> url('region_new_location', region_id=13)
  10. '/regions/13/locations/new'
  11. >>> url('region_location', region_id=13, id=60)
  12. '/regions/13/locations/60'
  13. >>> url('region_edit_location', region_id=13, id=60)
  14. '/regions/13/locations/60/edit'
  15.  
  16. Overriding generated path_prefix:
  17.  
  18. >>> m = Mapper()
  19. >>> m.resource('location', 'locations',
  20. ... parent_resource=dict(member_name='region',
  21. ... collection_name='regions'),
  22. ... path_prefix='areas/:area_id')
  23. >>> # name prefix is "region_"
  24. >>> url('region_locations', area_id=51)
  25. '/areas/51/locations'
  26.  
  27. Overriding generated name_prefix:
  28.  
  29. >>> m = Mapper()
  30. >>> m.resource('location', 'locations',
  31. ... parent_resource=dict(member_name='region',
  32. ... collection_name='regions'),
  33. ... name_prefix='')
  34. >>> # path_prefix is "regions/:region_id"
  35. >>> url('locations', region_id=51)
  36. '/regions/51/locations'
  1. map.resource("message", "messages")
  2.  
  3. # The above command sets up several routes as if you had typed the
  4. # following commands:
  5. map.connect("messages", "/messages",
  6. controller="messages", action="create",
  7. conditions=dict(method=["POST"]))
  8. map.connect("messages", "/messages",
  9. controller="messages", action="index",
  10. conditions=dict(method=["GET"]))
  11. map.connect("formatted_messages", "/messages.{format}",
  12. controller="messages", action="index",
  13. conditions=dict(method=["GET"]))
  14. map.connect("new_message", "/messages/new",
  15. controller="messages", action="new",
  16. conditions=dict(method=["GET"]))
  17. map.connect("formatted_new_message", "/messages/new.{format}",
  18. controller="messages", action="new",
  19. conditions=dict(method=["GET"]))
  20. map.connect("/messages/{id}",
  21. controller="messages", action="update",
  22. conditions=dict(method=["PUT"]))
  23. map.connect("/messages/{id}",
  24. controller="messages", action="delete",
  25. conditions=dict(method=["DELETE"]))
  26. map.connect("edit_message", "/messages/{id}/edit",
  27. controller="messages", action="edit",
  28. conditions=dict(method=["GET"]))
  29. map.connect("formatted_edit_message", "/messages/{id}.{format}/edit",
  30. controller="messages", action="edit",
  31. conditions=dict(method=["GET"]))
  32. map.connect("message", "/messages/{id}",
  33. controller="messages", action="show",
  34. conditions=dict(method=["GET"]))
  35. map.connect("formatted_message", "/messages/{id}.{format}",
  36. controller="messages", action="show",
  37. conditions=dict(method=["GET"]))

This establishes the following convention:

  1. GET /messages => messages.index() => url("messages")
  2. POST /messages => messages.create() => url("messages")
  3. GET /messages/new => messages.new() => url("new_message")
  4. PUT /messages/1 => messages.update(id) => url("message", id=1)
  5. DELETE /messages/1 => messages.delete(id) => url("message", id=1)
  6. GET /messages/1 => messages.show(id) => url("message", id=1)
  7. GET /messages/1/edit => messages.edit(id) => url("edit_message", id=1)

routes 学习的更多相关文章

  1. [转]学习Nop中Routes的使用

    本文转自:http://www.cnblogs.com/miku/archive/2012/09/27/2706276.html 1. 映射路由 大型MVC项目为了扩展性,可维护性不能像一般项目在Gl ...

  2. Flutter学习笔记(15)--MaterialApp应用组件及routes路由详解

    如需转载,请注明出处:Flutter学习笔记(15)--MaterialApp应用组件及routes路由详解 最近一段时间生病了,整天往医院跑,也没状态学东西了,现在是好了不少了,也该继续学习啦!!! ...

  3. ACM学习历程—CodeForces 601A The Two Routes(最短路)

    题目链接:http://codeforces.com/problemset/problem/601/A 题目大意是有铁路和陆路两种路,而且两种方式走的交通工具不能在中途相遇. 此外,有铁路的地方肯定没 ...

  4. MVC系列——MVC源码学习:打造自己的MVC框架(三:自定义路由规则)

    前言:上篇介绍了下自己的MVC框架前两个版本,经过两天的整理,版本三基本已经完成,今天还是发出来供大家参考和学习.虽然微软的Routing功能已经非常强大,完全没有必要再“重复造轮子”了,但博主还是觉 ...

  5. MVC系列——MVC源码学习:打造自己的MVC框架(二:附源码)

    前言:上篇介绍了下 MVC5 的核心原理,整篇文章比较偏理论,所以相对比较枯燥.今天就来根据上篇的理论一步一步进行实践,通过自己写的一个简易MVC框架逐步理解,相信通过这一篇的实践,你会对MVC有一个 ...

  6. MVC系列——MVC源码学习:打造自己的MVC框架(一:核心原理)

    前言:最近一段时间在学习MVC源码,说实话,研读源码真是一个痛苦的过程,好多晦涩的语法搞得人晕晕乎乎.这两天算是理解了一小部分,这里先记录下来,也给需要的园友一个参考,奈何博主技术有限,如有理解不妥之 ...

  7. ASP.Net MVC开发基础学习笔记:一、走向MVC模式

    一.ASP.Net的两种开发模式 1.1 ASP.Net WebForm的开发模式 (1)处理流程 在传统的WebForm模式下,我们请求一个例如http://www.aspnetmvc.com/bl ...

  8. 【NodeJS 学习笔记04】新闻发布系统

    前言 昨天,我们跟着这位大哥的博客(https://github.com/nswbmw/N-blog/wiki/_pages)进行了nodeJS初步的学习,最后也能将数据插入数据库了 但是一味的跟着别 ...

  9. MVC学习系列14--Bundling And Minification【捆绑和压缩】--翻译国外大牛的文章

    这个系列是,基础学习系列的最后一部分,这里,我打算翻译一篇国外的技术文章结束这个基础部分的学习:后面打算继续写深入学习MVC系列的文章,之所以要写博客,我个人觉得,做技术的,首先得要懂得分享,说不定你 ...

随机推荐

  1. 使用MQTTBox连接阿里云平台

    这篇只做一个简单的介绍,和上一篇没有根本的区别.只是就两个客户端的差异介绍一下. 一.需要参考的内容: 使用MQTT.fx连接阿里云平台: https://www.cnblogs.com/mhtc/p ...

  2. 计算机二级-C语言-程序设计题-190112记录-结构体的遍历和结构体的数据的交换处理,文件的操作。

    //程序设计题:学生的记录由学号和成绩组成,N名学生的数据已在主函数中放入结构体数组s中,请编写函数fun,它的功能是:把分数低的学生数据放在b所指的数组中,注意:分数最低的学生可能不止一个,函数返回 ...

  3. 记C++中发现的隐式转换问题

    #include <iostream> #include <string> using std::cin; using std::cout; using std::endl; ...

  4. Robot Framework 使用【2】-- MAC系统搭建Robot Framework

    前言 上一篇中讲述了如何在windows环境下搭建Robot Framework,发完帖后有几位小伙伴就私下留言有没有MAC版本的搭建过程,由于笔者MAC上是安装了旧版本的,经过笔者本周零碎时间的尝试 ...

  5. 【转】获取Jenkins构建时Git Change Log

    原文:https://www.jianshu.com/p/513ab6915dbd 在基于Jenkins进行CI持续集成的工作,在构建后上传蒲公英时想将本次版本的git commit信息同步到蒲公英的 ...

  6. Codeforces Round #589 (Div. 2)E(组合数,容斥原理,更高复杂度做法为DP)

    #define HAVE_STRUCT_TIMESPEC#include<bits/stdc++.h>using namespace std;int f[257],fac[257],ifa ...

  7. Rect Native 使用

    参见 Rect Native 中文官网. 依赖环境: Homebrew.npm.Node.js.Watchman(监测Bug和文件变化,触发指定操作).flow(JS静态类型检查仪,以方便找出代码中错 ...

  8. PB开启源码文件

    下载的源码没有pbw文件,新建workspace,然后new Target选existing application

  9. php 算法知识 冒泡排序

    function bubble_order($arr){ //得到长度 $count_num=count($arr); for($k=1;$k<$count_num;$k++){ //对长度越来 ...

  10. selenium webdriver 相关网站

    ITeye:http://shijincheng0223.iteye.com/blog/1481446 http://ztreeapi.iteye.com/blog/1750554 http://sm ...