python--route
创始人
2024-05-25 11:09:17
0

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-8from 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'}, )
({}, )
({'action': 'h2'}, )
({'action': 'boy', 'id': '23'}, 

当映射规则很多的时候,需要使用很多次 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']})

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...