CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-falcon

The ultra-reliable, fast ASGI+WSGI framework for building data plane APIs at scale.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utilities

Extensive utility functions and data structures for HTTP dates, URI handling, async/sync conversion, file operations, introspection, and common web development tasks in Falcon applications.

Capabilities

HTTP Utility Functions

Utilities for working with HTTP dates, status codes, and web-related operations.

def http_now() -> str:
    """
    Get current time as HTTP date string.
    
    Returns:
        RFC 1123 formatted HTTP date string
    """

def http_date_to_dt(http_date: str) -> datetime:
    """
    Convert HTTP date string to datetime object.
    
    Args:
        http_date: HTTP date string in RFC 1123 format
        
    Returns:
        Datetime object in UTC
    """

def dt_to_http(dt: datetime) -> str:
    """
    Convert datetime object to HTTP date string.
    
    Args:
        dt: Datetime object (assumed UTC if no timezone)
        
    Returns:
        RFC 1123 formatted HTTP date string
    """

def secure_filename(filename: str) -> str:
    """
    Sanitize filename for security by removing dangerous characters.
    
    Args:
        filename: Original filename
        
    Returns:
        Sanitized filename safe for filesystem use
    """

def code_to_http_status(status_code: int) -> str:
    """
    Convert numeric status code to HTTP status line.
    
    Args:
        status_code: Numeric HTTP status code (e.g., 200)
        
    Returns:
        Full HTTP status line (e.g., '200 OK')
    """

def http_status_to_code(status_line: str) -> int:
    """
    Extract status code from HTTP status line.
    
    Args:
        status_line: HTTP status line (e.g., '404 Not Found')
        
    Returns:
        Numeric status code (e.g., 404)
    """

def to_query_str(params: dict, comma_delimited_lists: bool = True, prefix: bool = True) -> str:
    """
    Build query string from parameters dictionary.
    
    Args:
        params: Parameters dictionary
        comma_delimited_lists: Use comma separation for list values
        prefix: Include '?' prefix
        
    Returns:
        URL-encoded query string
    """

HTTP Utilities Usage

import falcon
from datetime import datetime

# HTTP date handling
current_date = falcon.http_now()
# Returns: 'Wed, 07 Sep 2025 10:30:00 GMT'

# Parse HTTP date
dt = falcon.http_date_to_dt('Wed, 07 Sep 2025 10:30:00 GMT')
back_to_http = falcon.dt_to_http(dt)

# Secure filename handling
user_filename = "../../../etc/passwd"
safe_name = falcon.secure_filename(user_filename)
# Returns: 'etc_passwd'

# Status code conversion
status_line = falcon.code_to_http_status(404)
# Returns: '404 Not Found'

code = falcon.http_status_to_code('201 Created')
# Returns: 201

# Query string building
params = {'search': 'python', 'tags': ['web', 'api'], 'limit': 10}
query = falcon.to_query_str(params)
# Returns: '?search=python&tags=web,api&limit=10'

Async/Sync Conversion Utilities

Functions for converting between synchronous and asynchronous code patterns.

def async_to_sync(coroutine_func: callable) -> callable:
    """
    Convert async function to synchronous function.
    
    Args:
        coroutine_func: Async function to convert
        
    Returns:
        Synchronous wrapper function
    """

def sync_to_async(sync_func: callable) -> callable:
    """
    Convert synchronous function to async function.
    
    Args:
        sync_func: Synchronous function to convert
        
    Returns:
        Async wrapper function
    """

def create_task(coro: object) -> object:
    """
    Create asyncio task from coroutine.
    
    Args:
        coro: Coroutine object
        
    Returns:
        Asyncio Task object
    """

def get_running_loop() -> object:
    """
    Get currently running asyncio event loop.
    
    Returns:
        Current event loop or None
    """

def runs_sync(func: callable) -> bool:
    """
    Check if function is synchronous.
    
    Args:
        func: Function to check
        
    Returns:
        True if function is synchronous, False if async
    """

def wrap_sync_to_async(func: callable) -> callable:
    """
    Wrap synchronous function for async execution.
    
    Args:
        func: Synchronous function to wrap
        
    Returns:
        Async wrapper that executes func in thread pool
    """

def wrap_sync_to_async_unsafe(func: callable) -> callable:
    """
    Wrap synchronous function for async execution without thread safety.
    
    Args:
        func: Synchronous function to wrap
        
    Returns:
        Async wrapper (use with caution)
    """

Async/Sync Conversion Usage

import falcon
import asyncio

# Convert async function to sync
async def fetch_user_async(user_id):
    # Async database call
    return await db.get_user(user_id)

fetch_user_sync = falcon.async_to_sync(fetch_user_async)
user = fetch_user_sync(123)  # Can be called synchronously

# Convert sync function to async  
def compute_hash(data):
    # CPU intensive synchronous operation
    return hashlib.sha256(data).hexdigest()

compute_hash_async = falcon.sync_to_async(compute_hash)
hash_result = await compute_hash_async(b'data')

# Check if function is async
print(falcon.runs_sync(compute_hash))      # True
print(falcon.runs_sync(fetch_user_async))  # False

Data Structures

Specialized data structures for web applications.

class CaseInsensitiveDict(dict):
    def __init__(self, data: dict = None):
        """
        Case-insensitive dictionary (like HTTP headers).
        
        Args:
            data: Initial dictionary data
        """
    
    def __getitem__(self, key: str) -> object:
        """Get item with case-insensitive key"""
    
    def __setitem__(self, key: str, value: object):
        """Set item with case-insensitive key"""
    
    def __contains__(self, key: str) -> bool:
        """Check if key exists (case-insensitive)"""
    
    def get(self, key: str, default: object = None) -> object:
        """Get item with default fallback"""

class Context:
    def __init__(self, **kwargs):
        """
        Generic context container for request/response data.
        
        Args:
            **kwargs: Initial context data as keyword arguments
        """
    
    def __getattr__(self, name: str) -> object:
        """Get context attribute"""
    
    def __setattr__(self, name: str, value: object):
        """Set context attribute"""
    
    def __contains__(self, name: str) -> bool:
        """Check if attribute exists"""
    
    def get(self, name: str, default: object = None) -> object:
        """Get attribute with default fallback"""

class ETag:
    def __init__(self, value: str, is_weak: bool = False):
        """
        HTTP ETag representation.
        
        Args:
            value: ETag value
            is_weak: Whether ETag is weak (W/ prefix)
        """
    
    @property
    def value(self) -> str:
        """ETag value without quotes"""
    
    @property
    def is_weak(self) -> bool:
        """Whether ETag is weak"""
    
    def __str__(self) -> str:
        """Full ETag string representation"""
    
    def __eq__(self, other: object) -> bool:
        """Compare ETags for equality"""
    
    @classmethod
    def from_str(cls, etag_str: str) -> 'ETag':
        """
        Parse ETag from string.
        
        Args:
            etag_str: ETag string (e.g., '"abc123"' or 'W/"abc123"')
            
        Returns:
            ETag instance
        """

Data Structures Usage

import falcon

# Case-insensitive dictionary (useful for headers)
headers = falcon.CaseInsensitiveDict({
    'Content-Type': 'application/json',
    'authorization': 'Bearer token123'
})

print(headers['content-type'])     # 'application/json'
print(headers['AUTHORIZATION'])    # 'Bearer token123'
print('content-length' in headers)  # False

# Context for storing request data
class MyResource:
    def on_get(self, req, resp):
        # Store data in request context
        req.context.user_id = 123
        req.context.start_time = time.time()
        
        # Access context data
        if hasattr(req.context, 'user_id'):
            user = get_user(req.context.user_id)
            resp.media = user

# ETag handling
etag = falcon.ETag('abc123')
print(str(etag))  # '"abc123"'

weak_etag = falcon.ETag('def456', is_weak=True)
print(str(weak_etag))  # 'W/"def456"'

# Parse ETag from string
parsed = falcon.ETag.from_str('W/"xyz789"')
print(parsed.value)     # 'xyz789'
print(parsed.is_weak)   # True

Stream Utilities

Utilities for handling streaming data and file operations.

class BoundedStream:
    def __init__(self, stream: object, content_length: int):
        """
        Bounded stream wrapper that limits read operations.
        
        Args:
            stream: Underlying stream object
            content_length: Maximum bytes to read
        """
    
    def read(self, size: int = -1) -> bytes:
        """
        Read data from stream with bounds checking.
        
        Args:
            size: Number of bytes to read (-1 for all remaining)
            
        Returns:
            Read bytes (up to content_length limit)
        """
    
    def readline(self, size: int = -1) -> bytes:
        """Read line from stream with bounds checking"""
    
    def readlines(self, hint: int = -1) -> list:
        """Read lines from stream with bounds checking"""
    
    @property
    def eof(self) -> bool:
        """Whether end of stream reached"""

class BufferedReader:
    def __init__(self, stream: object, buffer_size: int = 8192):
        """
        Efficient buffered reader for file-like objects.
        
        Args:
            stream: Stream to read from
            buffer_size: Buffer size in bytes
        """
    
    def read(self, size: int = -1) -> bytes:
        """Read with internal buffering for efficiency"""
    
    def peek(self, size: int) -> bytes:
        """Peek at data without consuming it"""

Introspection Utilities

Functions for code inspection and reflection.

def get_argnames(func: callable) -> list:
    """
    Get function argument names.
    
    Args:
        func: Function to inspect
        
    Returns:
        List of argument names
    """

def get_bound_method(obj: object, method_name: str) -> callable:
    """
    Get bound method from object.
    
    Args:
        obj: Object instance
        method_name: Method name to get
        
    Returns:
        Bound method or None if not found
    """

def is_python_func(func: callable) -> bool:
    """
    Check if callable is a Python function.
    
    Args:
        func: Callable to check
        
    Returns:
        True if Python function, False otherwise
    """

URI Utilities

URI encoding, decoding, and manipulation functions.

# URI utilities (available as falcon.uri module)
def encode(uri: str, safe: str = '') -> str:
    """
    Percent-encode URI string.
    
    Args:
        uri: URI string to encode
        safe: Characters to not encode
        
    Returns:
        Percent-encoded URI
    """

def encode_check_escaped(uri: str, safe: str = '') -> str:
    """
    Encode URI, preserving existing percent-encoding.
    
    Args:
        uri: URI string to encode
        safe: Characters to not encode
        
    Returns:
        Encoded URI with existing encoding preserved
    """

def decode(encoded_uri: str, unquote_plus: bool = True) -> str:
    """
    Decode percent-encoded URI string.
    
    Args:
        encoded_uri: Percent-encoded URI
        unquote_plus: Whether to decode '+' as space
        
    Returns:
        Decoded URI string
    """

def encode_value(value: str) -> str:
    """
    Encode single URI value (like query parameter).
    
    Args:
        value: Value to encode
        
    Returns:
        Percent-encoded value
    """

def decode_value(encoded_value: str, unquote_plus: bool = True) -> str:
    """
    Decode single URI value.
    
    Args:
        encoded_value: Encoded value
        unquote_plus: Whether to decode '+' as space
        
    Returns:
        Decoded value
    """

URI Utilities Usage

import falcon.uri

# Encode URI components
encoded = falcon.uri.encode('hello world/path')
# Returns: 'hello%20world%2Fpath'

# Decode URI components  
decoded = falcon.uri.decode('hello%20world%2Fpath')
# Returns: 'hello world/path'

# Encode query parameter value
param_value = falcon.uri.encode_value('user@example.com')
# Returns: 'user%40example.com'

# Safe encoding (preserve certain characters)
safe_encoded = falcon.uri.encode('/api/v1/users', safe='/')
# Returns: '/api/v1/users'

Media Type Utilities

Functions for parsing and working with HTTP media types and headers.

def parse_header(header_value: str) -> tuple:
    """
    Parse HTTP header value with parameters.
    
    Args:
        header_value: HTTP header value string
        
    Returns:
        Tuple of (main_value, parameters_dict)
    """

Media Type Usage

# Parse Content-Type header
content_type = 'application/json; charset=utf-8; boundary=something'
media_type, params = falcon.parse_header(content_type)

print(media_type)  # 'application/json'
print(params)      # {'charset': 'utf-8', 'boundary': 'something'}

Time Utilities

Timezone and time-related utilities.

class TimezoneGMT:
    """GMT timezone implementation for datetime objects."""
    
    def utcoffset(self, dt: datetime) -> timedelta:
        """Return UTC offset (always 0 for GMT)"""
    
    def dst(self, dt: datetime) -> timedelta:
        """Return DST offset (always 0 for GMT)"""
    
    def tzname(self, dt: datetime) -> str:
        """Return timezone name ('GMT')"""

Deprecation Utilities

Tools for marking deprecated functionality.

def deprecated(instructions: str = None, is_property: bool = False) -> callable:
    """
    Mark function or property as deprecated.
    
    Args:
        instructions: Deprecation message or migration instructions
        is_property: Whether decorating a property
        
    Returns:
        Decorator that issues deprecation warnings
    """

Deprecation Usage

import falcon

class MyResource:
    @falcon.deprecated('Use new_method() instead')
    def old_method(self):
        """This method is deprecated"""
        return "old functionality"
    
    def new_method(self):
        """New improved method"""
        return "new functionality"

# Using deprecated method will issue warning
resource = MyResource()
result = resource.old_method()  # Issues deprecation warning

Types

# HTTP utilities
http_now: callable
http_date_to_dt: callable  
dt_to_http: callable
secure_filename: callable
code_to_http_status: callable
http_status_to_code: callable
to_query_str: callable

# Async/sync utilities
async_to_sync: callable
sync_to_async: callable
create_task: callable
get_running_loop: callable
runs_sync: callable
wrap_sync_to_async: callable
wrap_sync_to_async_unsafe: callable

# Data structures
CaseInsensitiveDict: type
Context: type
ETag: type

# Stream utilities
BoundedStream: type
BufferedReader: type

# Introspection utilities
get_argnames: callable
get_bound_method: callable
is_python_func: callable

# URI utilities (falcon.uri module)
encode: callable
encode_check_escaped: callable
decode: callable
encode_value: callable
decode_value: callable

# Media type utilities
parse_header: callable

# Time utilities
TimezoneGMT: type

# Deprecation utilities
deprecated: callable

Install with Tessl CLI

npx tessl i tessl/pypi-falcon

docs

application.md

asgi-websocket.md

error-handling.md

index.md

media.md

middleware-hooks.md

request-response.md

routing.md

testing.md

utilities.md

tile.json