CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask

A simple framework for building complex web applications.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

routing.mddocs/

Routing and URL Handling

Flask's routing system maps URLs to view functions and provides utilities for URL generation. It supports dynamic URL segments, HTTP method restrictions, and flexible URL patterns.

Capabilities

Route Registration

Decorators and methods for registering URL routes with view functions.

def route(self, rule: str, **options) -> Callable:
    """
    Decorator to register a view function for a URL rule.
    
    Args:
        rule: URL rule string (e.g., '/user/<name>')
        **options: Additional routing options
            - methods: HTTP methods (default: ['GET'])
            - endpoint: Endpoint name (defaults to function name)
            - defaults: Default values for URL variables
            - strict_slashes: Whether to enforce trailing slashes
            - redirect_to: Redirect to another endpoint
            - alias: Create URL alias
            - host: Host matching pattern
            - subdomain: Subdomain pattern
            
    Returns:
        Decorator function
    """

def add_url_rule(
    self,
    rule: str,
    endpoint: str | None = None,
    view_func: Callable | None = None,
    provide_automatic_options: bool | None = None,
    **options: Any
) -> None:
    """
    Register a URL rule with the application.
    
    Args:
        rule: URL rule string
        endpoint: Endpoint name (defaults to view function name)
        view_func: View function to call
        provide_automatic_options: Add OPTIONS method automatically
        **options: Additional routing options
    """

HTTP Method Decorators

Convenience decorators for specific HTTP methods.

def get(self, rule: str, **options) -> Callable:
    """
    Register a route that only accepts GET requests.
    
    Args:
        rule: URL rule string
        **options: Additional routing options
        
    Returns:
        Decorator function
    """

def post(self, rule: str, **options) -> Callable:
    """
    Register a route that only accepts POST requests.
    
    Args:
        rule: URL rule string  
        **options: Additional routing options
        
    Returns:
        Decorator function
    """

def put(self, rule: str, **options) -> Callable:
    """
    Register a route that only accepts PUT requests.
    
    Args:
        rule: URL rule string
        **options: Additional routing options
        
    Returns:
        Decorator function
    """

def delete(self, rule: str, **options) -> Callable:
    """
    Register a route that only accepts DELETE requests.
    
    Args:
        rule: URL rule string
        **options: Additional routing options
        
    Returns:
        Decorator function
    """

def patch(self, rule: str, **options) -> Callable:
    """
    Register a route that only accepts PATCH requests.
    
    Args:
        rule: URL rule string
        **options: Additional routing options
        
    Returns:
        Decorator function
    """

URL Generation

Functions for generating URLs from endpoint names.

def url_for(
    endpoint: str,
    *,
    _anchor: str | None = None,
    _method: str | None = None,  
    _scheme: str | None = None,
    _external: bool | None = None,
    **values: Any,
) -> str:
    """
    Generate a URL for the given endpoint.
    
    Args:
        endpoint: Endpoint name (function name or custom endpoint)
        _anchor: URL anchor/fragment
        _method: HTTP method for URL generation
        _scheme: URL scheme (http/https)
        _external: Generate external URL with hostname
        **values: Variable values for URL rule and query parameters
        
    Returns:
        Generated URL string
        
    Raises:
        BuildError: If URL cannot be built
    """

URL Processing

Functions for preprocessing URLs and handling URL defaults.

def url_value_preprocessor(self, f: Callable) -> Callable:
    """
    Decorator to register URL value preprocessor.
    
    Args:
        f: Function that receives (endpoint, values) and can modify values
        
    Returns:
        The original function
    """

def url_defaults(self, f: Callable) -> Callable:
    """
    Decorator to register URL defaults function.
    
    Args:
        f: Function that receives (endpoint, values) and can add defaults
        
    Returns:
        The original function
    """

Endpoint Registration

Direct endpoint registration without URL rules.

def endpoint(self, endpoint: str) -> Callable:
    """
    Decorator to register a function as an endpoint.
    
    Args:
        endpoint: Endpoint name
        
    Returns:
        Decorator function
    """

URL Adapter Creation

Methods for creating URL adapters for URL matching and building.

def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
    """
    Create a URL adapter for the current request.
    
    Args:
        request: Current request object or None
        
    Returns:
        URL adapter instance or None
    """

Usage Examples

Basic Routing

from flask import Flask

app = Flask(__name__)

# Simple route
@app.route('/')
def home():
    return 'Home Page'

# Route with variable
@app.route('/user/<name>')
def user_profile(name):
    return f'User: {name}'

# Route with typed variable
@app.route('/post/<int:post_id>')
def show_post(post_id):
    return f'Post ID: {post_id}'

# Route with multiple variables
@app.route('/user/<name>/post/<int:post_id>')
def user_post(name, post_id):
    return f'Post {post_id} by {name}'

HTTP Methods

from flask import Flask, request

app = Flask(__name__)

# Multiple methods
@app.route('/api/data', methods=['GET', 'POST', 'PUT'])
def api_data():
    if request.method == 'GET':
        return 'Getting data'
    elif request.method == 'POST':
        return 'Creating data'
    elif request.method == 'PUT':
        return 'Updating data'

# Method-specific decorators
@app.get('/items')
def get_items():
    return 'Getting items'

@app.post('/items')
def create_item():
    return 'Creating item'

@app.put('/items/<int:item_id>')
def update_item(item_id):
    return f'Updating item {item_id}'

@app.delete('/items/<int:item_id>')
def delete_item(item_id):
    return f'Deleting item {item_id}'

URL Generation

from flask import Flask, url_for, redirect

app = Flask(__name__)

@app.route('/')
def home():
    return 'Home'

@app.route('/user/<name>')
def user_profile(name):
    return f'User: {name}'

@app.route('/admin')
def admin():
    # Redirect to user profile
    return redirect(url_for('user_profile', name='admin'))

@app.route('/nav')
def navigation():
    # Generate URLs
    home_url = url_for('home')
    user_url = url_for('user_profile', name='john')
    admin_url = url_for('admin')
    
    return f'''
    <a href="{home_url}">Home</a><br>
    <a href="{user_url}">John's Profile</a><br>
    <a href="{admin_url}">Admin</a>
    '''

Advanced Routing Options

from flask import Flask

app = Flask(__name__)

# Route with defaults
@app.route('/blog/')
@app.route('/blog/<int:page>')
def blog(page=1):
    return f'Blog page {page}'

# Route with custom endpoint name
@app.route('/about', endpoint='about_page')
def about_us():
    return 'About Us'

# Route with host matching
@app.route('/api/status', host='api.example.com')
def api_status():
    return 'API Status'

# Route with subdomain
@app.route('/', subdomain='blog')
def blog_index():
    return 'Blog Home'

# Strict slashes
@app.route('/path', strict_slashes=True)
def strict_path():
    return 'Strict path (no trailing slash allowed)'

@app.route('/flexible/', strict_slashes=False)  
def flexible_path():
    return 'Flexible path (trailing slash optional)'

URL Converters

from flask import Flask
from werkzeug.routing import BaseConverter

app = Flask(__name__)

# Built-in converters
@app.route('/string/<string:text>')  # Default converter
def show_string(text):
    return f'String: {text}'

@app.route('/int/<int:number>')
def show_int(number):
    return f'Integer: {number}'

@app.route('/float/<float:number>')
def show_float(number):
    return f'Float: {number}'

@app.route('/path/<path:filepath>')
def show_path(filepath):
    return f'Path: {filepath}'

@app.route('/uuid/<uuid:id>')
def show_uuid(id):
    return f'UUID: {id}'

# Custom converter
class ListConverter(BaseConverter):
    def to_python(self, value):
        return value.split(',')
    
    def to_url(self, values):
        return ','.join(BaseConverter.to_url(value) for value in values)

app.url_map.converters['list'] = ListConverter

@app.route('/tags/<list:tags>')
def show_tags(tags):
    return f'Tags: {", ".join(tags)}'

URL Processing

from flask import Flask, g

app = Flask(__name__)

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    if values is not None:
        g.lang_code = values.pop('lang_code', None)

@app.url_defaults
def inject_lang_code(endpoint, values):
    if 'lang_code' in values or not g.get('lang_code'):
        return
    if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
        values['lang_code'] = g.lang_code

@app.route('/<lang_code>/')
@app.route('/<lang_code>/page')
def index(lang_code):
    return f'Language: {lang_code}'

Programmatic Route Registration

from flask import Flask

app = Flask(__name__)

def hello_world():
    return 'Hello World!'

def user_profile(username):
    return f'User: {username}'

# Register routes programmatically
app.add_url_rule('/', 'index', hello_world)
app.add_url_rule('/user/<username>', 'profile', user_profile)

# With options
app.add_url_rule(
    '/api/data',
    'api_data',
    lambda: 'API Data',
    methods=['GET', 'POST']
)

Install with Tessl CLI

npx tessl i tessl/pypi-flask

docs

blueprints.md

cli.md

configuration.md

context-globals.md

core-application.md

helpers.md

index.md

json-support.md

request-response.md

routing.md

sessions.md

signals.md

templates.md

testing.md

tile.json