Routes
Routes is a Python library that re-implements the Rails routing system, enabling developers to map URLs to application actions and generate URLs. It focuses on creating clean, concise, and RESTful URLs with features like named routes, conditional matching, and sub-domain support. The library is currently in maintenance mode, meaning active development is limited, but bug fixes via pull requests are still accepted. The latest stable version is 2.5.1.
Warnings
- deprecated Routes is in maintenance mode. While bug reports are accepted and pull requests with tests will be applied, active feature development is unlikely. Consider this when planning long-term projects or expecting new features.
- breaking Versions prior to 2.5.0 had specific Python version requirements. Support for Python 2.6, 3.3, and 3.4 was removed in 2.5.0.
- gotcha Older versions (prior to 2.1) had issues with URL generation and caching, particularly when `SCRIPT_NAME` was involved or with specific parameter passing (e.g., 'host', 'protocol', 'anchor').
- breaking In version 1.9, the `Mapper` object's `hardcode_names` argument defaulted to `True`. This means routes generated by name must strictly adhere to the URL pattern.
Install
-
pip install routes
Imports
- Mapper
from routes import Mapper
- middleware
from routes import middleware
Quickstart
from routes import Mapper
# Setup a mapper
map = Mapper()
# Connect routes
map.connect(None, '/error/{action}/{id}', controller='error')
map.connect('home', '/', controller='main', action='index')
# Match a URL
result = map.match('/error/myapp/4')
print(f"Match result for '/error/myapp/4': {result}")
result_home = map.match('/')
print(f"Match result for '/': {result_home}")
# Generate a URL
url = map.generate(controller='main', action='index')
print(f"Generated URL for main index: {url}")
error_url = map.generate(controller='error', action='display', id=123)
print(f"Generated URL for error: {error_url}")