Skip to main content

用于 HTTP 应用程序的简单路由器

项目描述

http-router – HTTP 应用程序的简单路由器

测试状态 PYPI 版本 Python 版本 <nav class="contents" id="topic-1" role="doc-toc">

内容

</nav>

要求

  • 蟒蛇> = 3.7

安装

http-router应该使用 pip 安装:

pip install http-router

用法

创建路由器:

from http_router import Router


# Initialize the router
router = Router(trim_last_slash=True)

定义路线:

@router.route('/simple')
def simple():
    return 'result from the fn'

使用 HTTP 路径和可选方法调用路由器以获取匹配结果。

match = router('/simple', method='GET')
assert match, 'HTTP path is ok'
assert match.target is simple

路由器也支持正则表达式对象:

import re

@router.route(re.compile(r'/regexp/\w{3}-\d{2}/?'))
def regex():
    return 'result from the fn'

但是 lib 有一个更简单的动态路由接口:

@router.route('/users/{username}')
def users():
    return 'result from the fn'

默认情况下,这将捕获到路径末尾或下一个 /的字符。

或者,您可以使用转换器来指定参数的类型,例如 {variable_name:converter}

转换器类型:

字符串

(默认)接受任何不带斜线的文本

整数

接受正整数

漂浮

接受正浮点值

小路

像字符串,但也接受斜杠

uuid

接受 UUID 字符串

转换器通过在它们前面加上一个冒号来使用,如下所示:

@router.route('/orders/{order_id:int}')
def orders():
    return 'result from the fn'

任何未知的转换器都将被解析为正则表达式:

@router.route('/orders/{order_id:\d{3}}')
def orders():
    return 'result from the fn'

还支持多条路径:

@router.route('/', '/home')
def index():
    return 'index'

处理 HTTP 方法:

@router.route('/only-post', methods=['POST'])
def only_post():
    return 'only-post'

下装路线:

subrouter = Router()

@subrouter('/items')
def items():
     pass

 router = Router()
 router.route('/api')(subrouter)


match = router('/api/items', method='GET')
assert match, 'HTTP path is ok'
assert match.target is items

错误跟踪器

如果您有任何建议、错误报告或烦恼,请将它们报告给https://github.com/klen/http-router/issues的问题跟踪器

贡献

该项目的开发发生在:https ://github.com/klen/http-router

执照

根据MIT 许可证获得许可

项目详情