A simple router for HTTP applications
Project description
http-router – A simple router for HTTP applications
Requirements
python >= 3.7
Installation
http-router should be installed using pip:
pip install http-router
Usage
Create a router:
from http_router import Router
# Initialize the router
router = Router(trim_last_slash=True)
Define routes:
@router.route('/simple')
def simple():
return 'result from the fn'
Call the router with HTTP path and optionally method to get a match result.
match = router('/simple', method='GET')
assert match, 'HTTP path is ok'
assert match.target is simple
The router supports regex objects too:
import re
@router.route(re.compile(r'/regexp/\w{3}-\d{2}/?'))
def regex():
return 'result from the fn'
But the lib has a simplier interface for the dynamic routes:
@router.route('/users/{username}')
def users():
return 'result from the fn'
By default this will capture characters up to the end of the path or the next /.
Optionally, you can use a converter to specify the type of the argument like {variable_name:converter}.
Converter types:
str |
(default) accepts any text without a slash |
int |
accepts positive integers |
float |
accepts positive floating point values |
path |
like string but also accepts slashes |
uuid |
accepts UUID strings |
Convertors are used by prefixing them with a colon, like so:
@router.route('/orders/{order_id:int}')
def orders():
return 'result from the fn'
Any unknown convertor will be parsed as a regex:
@router.route('/orders/{order_id:\d{3}}')
def orders():
return 'result from the fn'
Multiple paths are supported as well:
@router.route('/', '/home')
def index():
return 'index'
Handling HTTP methods:
@router.route('/only-post', methods=['POST'])
def only_post():
return 'only-post'
Submounting routes:
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
Bug tracker
If you have any suggestions, bug reports or annoyances please report them to the issue tracker at https://github.com/klen/http-router/issues
Contributing
Development of the project happens at: https://github.com/klen/http-router
License
Licensed under a MIT license.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distributions
Built Distribution
Hashes for http_router-2.0.16-cp37-cp37m-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0deb0e08c161e3b74ebdd83963e2222a5e69e18c8df0d0911a1f0691c9aee5b2 |
|
MD5 | 8ab2664f227cf8cad30d3205bc4aaea4 |
|
BLAKE2b-256 | ba5a9ae16d783160c3f2bc3ce3c8608edf47db0ff8afa284f79e952e606f159e |