Routes

一、关于Routes

Routes是一个Rails routes系统的python实现,用来在URLs 和 应用action之间做映射。同时,Routes可用来产生简洁明了的RestFull形式的URLs。Routes做映射时,支持基于域、cookies,HTTP 方法或是预定义的函数的映射,同时支持子域映射。

官网文献:http://routes.readthedocs.io/en/latest/

1. 配置使用Routes

结合下面例子进行说明routes的使用

# Setup a mapper
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")

# Match a URL, returns a dict or None if no match
6. result = map.match('/error/myapp/4')
7. # result == {'controller': 'error', 'action': 'myapp', 'id': '4'}

行1,2创建一个mapper。
行3 新建了一条路由规则。根据该规则,对于URL:/error/images/arrow.jpg将产生如下结果:{“controller”: “error”, “action”: “images”, “id”: “arrow.jpg”} 。 { }用来指定里面匹配的字段是什么, : 表示的是匹配字段的格式
行4和行3不同的是,该条路由规则取了名字,名为“home”.

行6.7定义了两条路由,该路由是一个正则表达式模式,可匹配所有的URL。

对于URL “/error/images/arrow.jpg”可以匹配 行3 和行7的规则。在解析URL时,是一条一条的按定义顺序匹配的,因此,该URL使用的是行3的路由规则。

如果某个URL没有匹配的规则,则mapper返回“match failded” conditions。

PS:主要函数说明
(1)connect(*args, **kargs) : 对mapper创建一条新的路由。
(2)match(url=None, environ=None) :Match a URL against against one of the routes contained.Will return None if no valid match is found.

2. conditions 使用

conditions 用于限制进行路由匹配,比如method.

from routes import Mapper  

map = Mapper()  
print map  
print type(map)  

#4.conditions  conditions=dict(method=['GET', 'HEAD'])  
map.connect('/user/list', controller = 'user', action = 'list', conditions={'method' : ['GET', 'HEAD']})  
result = map.match('/user/list')  

print result 

只匹配GET、HEAD请求。
POST:新建资源 GET:查询资源 PUT:更新资源 DELETE:删除资源 HEAD:验证,包括用户身份和资源的认证

参考文献:http://blog.csdn.net/li_101357/article/details/52750550#

3. Requirements

有时只想要匹配数字,或者匹配可选的几个条目。

map.connect(r'/blog/{id:\d+}')  
map.connect(r'/download/{platform:windows|linux/{filename}') 

\d([0-9])、+(匹配前一个字符一次或多次)、| 正则表达式知识点。
将上述可以改写成:

map.connect(r'/blog/{id}', requirements={'id':r'\d+'})  
map.connect(r'/blog/{platfrom}/{filename}', requirements={'platform':r'windows|linux'})  

参考文献:http://blog.csdn.net/li_101357/article/details/52750550#

猜你喜欢

转载自blog.csdn.net/youyou1543724847/article/details/71643063