routes是用python重新实现的Rails routes系统,用于将url映射到应用程序的actions ,并反过来生成url
它也是在openstack实现restful通信的方式,它被用来做将 URL 映射为 App 的 action,以及为 App的action 产生 URL

两个重要的方法:map.connect (定义映射规则) 和 map.match (获取映射结果)

map.connect映射规则:(map名称,路由地址,controller,action,conditions,requirements)
除了路由地址,其余都是附加参数,对映射进行一些处理
controller:资源控制类
action:资源处理操作
requirements:对输入格式进行限制
conditions:路由方式

map.routematch返回结果:如果匹配到了,会返回一个二元元组,元组第一个元素为匹配到的字典,第二个元素一个Route对象
map.match:比routematch少返回了一个route对象
# !/usr/bin/env python # coding: utf-8 from routes.mapper import Mapper #
实例化一个Mapper对象 mapper = Mapper() # 注册一个/hi路由 mapper.connect("/hi") mapper.connect
(None, "/error/{action}/{id}", controller="error") mapper.connect("home", "/hi2"
, controller="main", action="index") mapper.connect('/hi2/{action}') mapper.
connect('/hi3/{action}/{id}') m4_res = mapper.routematch("/error/az/a") print(
m4_res) # 查找/hi m_result = mapper.routematch("/hi") print(m_result) # 查找/hi2
m2_result= mapper.routematch("/hi2/h2") print(m2_result) # 查找/hi3 m3_result =
mapper.routematch("/hi3/boy/23") print(m3_result)
执行结果如下:
({'action': 'az', 'id': 'a', 'controller': 'error'}, <routes.route.Route object
at0x0000020481DF5D90>) ({}, <routes.route.Route object at 0x0000020481DF5D00>)
({'action': 'h2'}, <routes.route.Route object at 0x0000020481DF5B50>) ({'action'
: 'boy', 'id': '23'}, <routes.route.Route object at 0x0000020481DF57C0>
当映射规则很多的时候,需要使用很多次 map.connect,这时可以使用 map.resource 方法
map.resource内部定义了默认的匹配条件
第一个参数message为
member_name(资源名),第二个参数messages为collection_name(资源集合名),一般定义资源集合名为资源名的复数
collection_name作为访问的路径名,且当没有传入参数controller时,controller=collection_name
from routes.mapper import Mapper # 实例化一个Mapper对象 mapper = Mapper(always_scan=
True) mapper.resource("message", "messages", controller="testuse") # 等同于以下匹配条件:
mapper.connect('/messages', controller="testuse", action='index', conditions={
'method': ['GET']}) mapper.connect('/messages', controller="testuse", action=
'create', conditions={'method': ['POST']}) mapper.connect(
'/messages/{id:[0-9]+}', controller="testuse", action='show', conditions={
'method': ['GET']}) mapper.connect('/messages/{id}', controller="testuse",
action='update', conditions={'method': ['PUT']}, requirements=dict(id=r"[a-z]+")
) mapper.connect('/messages/{id:[XYZ]}', controller="testuse", action='delete',
conditions={'method': ['DELETE']})

技术
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信