Declarative parsing and validation of HTTP request objects, with built-in support for popular web frameworks.
Central parsing functionality providing the foundation for request argument parsing and validation across web frameworks. The core parsing system includes the base Parser class, parsing methods, decorators for automatic argument injection, and extensible location-based data loading.
Base parser class that provides high-level implementation for parsing requests. Framework-specific parsers inherit from this class and implement framework-specific data loading methods.
class Parser:
"""
Base parser class for parsing HTTP requests.
Args:
location (str, optional): Default location to parse data from
unknown (str, optional): Default handling for unknown fields
error_handler (callable, optional): Custom error handler function
schema_class (type, optional): Default marshmallow schema class
"""
def __init__(self, location=None, *, unknown=None, error_handler=None, schema_class=None): ...Class attributes:
Parser.DEFAULT_LOCATION = "json"
Parser.DEFAULT_UNKNOWN_BY_LOCATION = {
"json": None,
"form": None,
"json_or_form": None,
"querystring": "EXCLUDE",
"query": "EXCLUDE",
"headers": "EXCLUDE",
"cookies": "EXCLUDE",
"files": "EXCLUDE"
}
Parser.DEFAULT_SCHEMA_CLASS = marshmallow.Schema
Parser.DEFAULT_VALIDATION_STATUS = 422
Parser.KNOWN_MULTI_FIELDS = [marshmallow.fields.List, marshmallow.fields.Tuple]
Parser.USE_ARGS_POSITIONAL = TrueCore parsing methods for extracting and validating data from HTTP requests.
def parse(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):
"""
Main request parsing method.
Args:
argmap: Schema, dict of field mappings, or callable returning schema
req: Request object to parse (uses default if None)
location (str): Where to parse data from ('json', 'query', 'form', 'headers', 'cookies', 'files')
unknown (str): How to handle unknown fields ('EXCLUDE', 'INCLUDE', 'RAISE')
validate: Validation function or list of validation functions
error_status_code (int): HTTP status code for validation errors
error_headers (dict): HTTP headers for validation errors
Returns:
dict: Parsed and validated arguments
Raises:
ValidationError: When validation fails
"""
def async_parse(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):
"""
Async variant of parse method with same signature.
Returns:
Awaitable[dict]: Parsed and validated arguments
"""Decorators that automatically parse request arguments and inject them into view functions.
def use_args(self, argmap, req=None, *, location=None, unknown=None, as_kwargs=False, arg_name=None, validate=None, error_status_code=None, error_headers=None):
"""
Decorator that injects parsed arguments into a view function.
Args:
argmap: Schema, dict of field mappings, or callable returning schema
req: Request object (uses framework detection if None)
location (str): Where to parse data from
unknown (str): How to handle unknown fields
as_kwargs (bool): Whether to inject as keyword arguments
arg_name (str): Name for positional argument (mutually exclusive with as_kwargs)
validate: Validation function or list of validation functions
error_status_code (int): HTTP status code for validation errors
error_headers (dict): HTTP headers for validation errors
Returns:
callable: Decorator function
"""
def use_kwargs(self, argmap, req=None, *, location=None, unknown=None, validate=None, error_status_code=None, error_headers=None):
"""
Decorator that injects parsed arguments as keyword arguments.
Shortcut for use_args with as_kwargs=True.
Returns:
callable: Decorator function
"""System for loading data from different parts of HTTP requests.
def location_loader(self, name):
"""
Decorator that registers a function for loading a request location.
Args:
name (str): Name of the location to register
Returns:
callable: Decorator function
Example:
@parser.location_loader("custom")
def load_custom_data(request, schema):
return request.custom_data
"""
def load_json(self, req, schema):
"""
Load JSON from request body.
Args:
req: Request object
schema: Marshmallow schema for field information
Returns:
dict or missing: Parsed JSON data or missing sentinel
"""
def load_querystring(self, req, schema):
"""Load query string parameters from request."""
def load_form(self, req, schema):
"""Load form data from request."""
def load_headers(self, req, schema):
"""Load headers from request."""
def load_cookies(self, req, schema):
"""Load cookies from request."""
def load_files(self, req, schema):
"""Load uploaded files from request."""
def load_json_or_form(self, req, schema):
"""Load JSON or form data with fallback."""Error handling and customization system.
def error_handler(self, func):
"""
Decorator that registers a custom error handling function.
Args:
func: Error handler function that receives (error, request, schema, error_status_code, error_headers)
Returns:
callable: The registered error handler
Example:
@parser.error_handler
def handle_error(error, req, schema, *, error_status_code, error_headers):
# Custom error handling logic
raise CustomError(error.messages)
"""
def handle_error(self, error, req, schema, *, error_status_code, error_headers):
"""
Default error handler that logs and re-raises the error.
Args:
error (ValidationError): The validation error
req: Request object
schema: Marshmallow schema used for parsing
error_status_code (int): HTTP status code for the error
error_headers (dict): HTTP headers for the error
Raises:
ValidationError: Re-raises the original error
"""Additional utility methods for parser customization.
def pre_load(self, location_data, *, schema, req, location):
"""
Hook for transforming data after location loading.
Args:
location_data: Raw data loaded from the request location
schema: Marshmallow schema being used
req: Request object
location (str): Location being parsed
Returns:
dict: Transformed data for schema loading
"""
def get_default_request(self):
"""
Hook for frameworks with thread-local request objects.
Returns:
Request or None: Default request object
"""
def get_request_from_view_args(self, view, args, kwargs):
"""
Extract request object from view function arguments.
Args:
view: View function being decorated
args: Positional arguments passed to view
kwargs: Keyword arguments passed to view
Returns:
Request or None: Extracted request object
"""
def get_default_arg_name(self, location, schema):
"""
Generate default argument name for use_args.
Args:
location (str): Location being parsed
schema: Schema or argument map
Returns:
str: Default argument name (format: "{location}_args")
"""Global utility functions for JSON parsing and MIME type detection.
def parse_json(s, *, encoding="utf-8"):
"""
Parse JSON string with proper encoding handling.
Args:
s (str or bytes): JSON string to parse
encoding (str): Character encoding for bytes input
Returns:
Any: Parsed JSON data
Raises:
json.JSONDecodeError: When JSON parsing fails
"""
def get_mimetype(content_type):
"""
Extract MIME type from Content-Type header.
Args:
content_type (str): Full content-type header value
Returns:
str: MIME type portion
"""
def is_json(mimetype):
"""
Check if MIME type indicates JSON content.
Args:
mimetype (str): MIME type to check
Returns:
bool: True if MIME type is JSON-related
"""DEFAULT_VALIDATION_STATUS = 422Request = TypeVar("Request")
# Generic type var with no particular meaning
T = TypeVar("T")
# Type var for callables, to make type-preserving decorators
C = TypeVar("C", bound=Callable)
# Type var for multidict proxy classes
MultiDictProxyT = TypeVar("MultiDictProxyT", bound=MultiDictProxy)
# Type var for a callable which is an error handler
ErrorHandlerT = TypeVar("ErrorHandlerT", bound=ErrorHandler)
ArgMapCallable = Callable[[Request], marshmallow.Schema]
ArgMap = Union[
marshmallow.Schema,
Type[marshmallow.Schema],
Mapping[str, marshmallow.fields.Field],
ArgMapCallable
]
ValidateArg = Union[None, Callable, Iterable[Callable]]
CallableList = list[Callable]
ErrorHandler = Callable[..., NoReturn]
AsyncErrorHandler = Callable[..., Awaitable[NoReturn]]Install with Tessl CLI
npx tessl i tessl/pypi-webargs