API¶
webargs.core¶
- class webargs.core.Parser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Base parser class that provides high-level implementation for parsing a request.
Descendant classes must provide lower-level implementations for reading data from different locations, e.g.
load_json,load_querystring, etc.- Parameters:
location (str) – Default location to use for data
unknown (str) – A default value to pass for
unknownwhen calling the schema’sloadmethod. Defaults tomarshmallow.EXCLUDEfor non-body locations andmarshmallow.RAISEfor request bodies. PassNoneto use the schema’s setting instead.error_handler (callable) – Custom error handler function.
- KNOWN_MULTI_FIELDS: list[type] = [<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>]¶
field types which should always be treated as if they set
is_multiple=True
- async async_parse(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Any[source]¶
Coroutine variant of
webargs.core.Parser.parse.Receives the same arguments as
webargs.core.Parser.parse.
- error_handler(func: ErrorHandlerT) ErrorHandlerT[source]¶
Decorator that registers a custom error handling function. The function should receive the raised error, request object,
marshmallow.Schemainstance used to parse the request, error status code, and headers to use for the error response. Overrides the parser’shandle_errormethod.Example:
from webargs import flaskparser parser = flaskparser.FlaskParser() class CustomError(Exception): pass @parser.error_handler def handle_error(error, req, schema, *, error_status_code, error_headers): raise CustomError(error.messages)
- Parameters:
func (callable) – The error callback to register.
- get_default_arg_name(location: str, schema: ArgMap[Request]) str[source]¶
This method provides the rule by which an argument name is derived for
use_args()if no explicitarg_nameis provided.By default, the format used is
{location}_args. Users may override this method to customize the default argument naming scheme.schemawill be the argument map or schema passed touse_args()unless a dict was used, in which case it will be the schema derived from that dict.
- get_default_request() Request | None[source]¶
Optional override. Provides a hook for frameworks that use thread-local request objects.
- get_request_from_view_args(view: Callable, args: tuple, kwargs: Mapping[str, Any]) Request | None[source]¶
Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the
use_argsanduse_kwargsto get a request object from a view’s arguments.- Parameters:
view (callable) – The view function or method being decorated by
use_argsoruse_kwargsargs (tuple) – Positional arguments passed to
view.kwargs (dict) – Keyword arguments passed to
view.
- handle_error(error: ValidationError, req: Request, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn[source]¶
Called if an error occurs while parsing args. By default, just logs and raises
error.
- load_cookies(req: Request, schema: Schema) Any[source]¶
Load the cookies from the request or return
missingif no value can be found.
- load_files(req: Request, schema: Schema) Any[source]¶
Load files from the request or return
missingif no values can be found.
- load_form(req: Request, schema: Schema) Any[source]¶
Load the form data of a request object or return
missingif no value can be found.
- load_headers(req: Request, schema: Schema) Any[source]¶
Load the headers or return
missingif no value can be found.
- load_json(req: Request, schema: Schema) Any[source]¶
Load JSON from a request object or return
missingif no value can be found.
- load_json_or_form(req: Request, schema: Schema) Any[source]¶
Load data from a request, accepting either JSON or form-encoded data.
The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.
- load_querystring(req: Request, schema: Schema) Any[source]¶
Load the query string of a request object or return
missingif no value can be found.
- location_loader(name: str) Callable[[C], C][source]¶
Decorator that registers a function for loading a request location. The wrapped function receives a schema and a request.
The schema will usually not be relevant, but it’s important in some cases – most notably in order to correctly load multidict values into list fields. Without the schema, there would be no way to know whether to simply
get()orgetall()from a multidict for a given value.Example:
from webargs import core parser = core.Parser() @parser.location_loader("name") def load_data(request, schema): return request.data
- Parameters:
name (str) – The name of the location to register.
- parse(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Any[source]¶
Main request parsing method.
- Parameters:
argmap – Either a
marshmallow.Schema, adictof argname ->marshmallow.fields.Fieldpairs, or a callable which accepts a request and returns amarshmallow.Schema.req – The request object to parse.
location (str) – Where on the request to load values. Can be any of the values in
__location_map__. By default, that means one of('json', 'query', 'querystring', 'form', 'headers', 'cookies', 'files', 'json_or_form').unknown (str) – A value to pass for
unknownwhen calling the schema’sloadmethod. Defaults tomarshmallow.EXCLUDEfor non-body locations andmarshmallow.RAISEfor request bodies. PassNoneto use the schema’s setting instead.validate (callable) – Validation function or list of validation functions that receives the dictionary of parsed arguments. Validator either returns a boolean or raises a
ValidationError.error_status_code (int) – Status code passed to error handler functions when a
ValidationErroris raised.error_headers (dict) –
- Headers passed to error handler functions when a
a
ValidationErroris raised.
- return:
A dictionary of parsed arguments
- pre_load(location_data: Mapping, *, schema: Schema, req: Request, location: str) Mapping[source]¶
A method of the parser which can transform data after location loading is done. By default it does nothing, but users can subclass parsers and override this method.
- use_args(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', as_kwargs: bool = False, arg_name: str | None = None, validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable][source]¶
Decorator that injects parsed arguments into a view function or method.
Example usage with Flask:
@app.route("/echo", methods=["get", "post"]) @parser.use_args({"name": fields.Str()}, location="querystring") def greet(querystring_args): return "Hello " + querystring_args["name"]
- Parameters:
argmap – Either a
marshmallow.Schema, adictof argname ->marshmallow.fields.Fieldpairs, or a callable which accepts a request and returns amarshmallow.Schema.location (str) – Where on the request to load values.
unknown (str) – A value to pass for
unknownwhen calling the schema’sloadmethod.as_kwargs (bool) – Whether to insert arguments as keyword arguments.
arg_name (str) – Keyword argument name to use for arguments. Mutually exclusive with as_kwargs.
validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns
False, the parser will raise aValidationError.error_status_code (int) – Status code passed to error handler functions when a
ValidationErroris raised.error_headers (dict) – Headers passed to error handler functions when a a
ValidationErroris raised.
- use_kwargs(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable][source]¶
Decorator that injects parsed arguments into a view function or method as keyword arguments.
This is a shortcut to
use_args()withas_kwargs=True.Example usage with Flask:
@app.route("/echo", methods=["get", "post"]) @parser.use_kwargs({"name": fields.Str()}) def greet(name): return "Hello " + name
Receives the same
argsandkwargsasuse_args().
- exception webargs.core.ValidationError(message: str | list | dict, field_name: str = '_schema', data: Mapping[str, Any] | Iterable[Mapping[str, Any]] | None = None, valid_data: list[Any] | dict[str, Any] | None = None, **kwargs)[source]¶
Raised when validation fails on a field or schema.
Validators and custom fields should raise this exception.
- Parameters:
message – An error message, list of error messages, or dict of error messages. If a dict, the keys are subitems and the values are error messages.
field_name – Field name to store the error on.
data – Raw input data.
valid_data – Valid (de)serialized data.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
webargs.fields¶
Field classes.
Includes all fields from marshmallow.fields in addition to DelimitedList.
All fields can optionally take a special location keyword argument, which
tells webargs where to parse the request argument from.
args = {
"active": fields.Bool(location="query"),
"content_type": fields.Str(data_key="Content-Type", location="headers"),
}
- class webargs.fields.DelimitedList(cls_or_instance: Field | type, *, delimiter: str | None = None, **kwargs)[source]¶
A field which is similar to a List, but takes its input as a delimited string (e.g. “foo,bar,baz”).
Like List, it can be given a nested field type which it will use to de/serialize each element of the list.
- Parameters:
cls_or_instance (Field) – A field class or instance.
delimiter (str) – Delimiter between values.
- class webargs.fields.Nested(nested: Schema | SchemaMeta | str | dict[str, Field] | Callable[[], Schema | SchemaMeta | dict[str, Field]], *, only: types.StrSequenceOrSet | None = None, exclude: types.StrSequenceOrSet = (), many: bool = False, unknown: types.UnknownOption | None = None, **kwargs: Unpack[_BaseFieldKwargs])[source]¶
Allows you to nest a
Schemainside a field.Examples:
class ChildSchema(Schema): id = fields.Str() name = fields.Str() # Use lambda functions when you need two-way nesting or self-nesting parent = fields.Nested(lambda: ParentSchema(only=("id",)), dump_only=True) siblings = fields.List( fields.Nested(lambda: ChildSchema(only=("id", "name"))) ) class ParentSchema(Schema): id = fields.Str() children = fields.List( fields.Nested(ChildSchema(only=("id", "parent", "siblings"))) ) spouse = fields.Nested(lambda: ParentSchema(only=("id",)))
When passing a
Schemainstance as the first argument, the instance’sexclude,only, andmanyattributes will be respected.Therefore, when passing the
exclude,only, ormanyarguments tofields.Nested, you should pass aSchemaclass (not an instance) as the first argument.# Yes author = fields.Nested(UserSchema, only=("id", "name")) # No author = fields.Nested(UserSchema(), only=("id", "name"))
- Parameters:
nested –
Schemainstance, class, class name (string), dictionary, or callable that returns aSchemaor dictionary. Dictionaries are converted withSchema.from_dict.exclude – A list or tuple of fields to exclude.
only – A list or tuple of fields to marshal. If
None, all fields are marshalled. This parameter takes precedence overexclude.many – Whether the field is a collection of objects.
unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use
EXCLUDE,INCLUDEorRAISE.kwargs – The same keyword arguments that
Fieldreceives.
- property schema: Schema¶
The nested Schema object.
webargs.multidictproxy¶
- class webargs.multidictproxy.MultiDictProxy(multidict: ~collections.abc.MutableMapping, schema: ~marshmallow.schema.Schema, known_multi_fields: tuple[type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]¶
A proxy object which wraps multidict types along with a matching schema Whenever a value is looked up, it is checked against the schema to see if there is a matching field where
is_multipleis True. If there is, then the data should be loaded as a list or tuple.In all other cases, __getitem__ proxies directly to the input multidict.
webargs.asyncparser¶
Asynchronous request parser.
- class webargs.asyncparser.AsyncParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Asynchronous variant of
webargs.core.Parser.The
parsemethod is redefined to beasync.- KNOWN_MULTI_FIELDS: list[type] = [<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>]¶
field types which should always be treated as if they set
is_multiple=True
- async async_parse(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Any¶
Coroutine variant of
webargs.core.Parser.parse.Receives the same arguments as
webargs.core.Parser.parse.
- error_handler(func: ErrorHandlerT) ErrorHandlerT¶
Decorator that registers a custom error handling function. The function should receive the raised error, request object,
marshmallow.Schemainstance used to parse the request, error status code, and headers to use for the error response. Overrides the parser’shandle_errormethod.Example:
from webargs import flaskparser parser = flaskparser.FlaskParser() class CustomError(Exception): pass @parser.error_handler def handle_error(error, req, schema, *, error_status_code, error_headers): raise CustomError(error.messages)
- Parameters:
func (callable) – The error callback to register.
- get_default_arg_name(location: str, schema: ArgMap[Request]) str¶
This method provides the rule by which an argument name is derived for
use_args()if no explicitarg_nameis provided.By default, the format used is
{location}_args. Users may override this method to customize the default argument naming scheme.schemawill be the argument map or schema passed touse_args()unless a dict was used, in which case it will be the schema derived from that dict.
- get_default_request() Request | None¶
Optional override. Provides a hook for frameworks that use thread-local request objects.
- get_request_from_view_args(view: Callable, args: tuple, kwargs: Mapping[str, Any]) Request | None¶
Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the
use_argsanduse_kwargsto get a request object from a view’s arguments.- Parameters:
view (callable) – The view function or method being decorated by
use_argsoruse_kwargsargs (tuple) – Positional arguments passed to
view.kwargs (dict) – Keyword arguments passed to
view.
- handle_error(error: ValidationError, req: Request, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn¶
Called if an error occurs while parsing args. By default, just logs and raises
error.
- load_cookies(req: Request, schema: Schema) Any¶
Load the cookies from the request or return
missingif no value can be found.
- load_files(req: Request, schema: Schema) Any¶
Load files from the request or return
missingif no values can be found.
- load_form(req: Request, schema: Schema) Any¶
Load the form data of a request object or return
missingif no value can be found.
- load_headers(req: Request, schema: Schema) Any¶
Load the headers or return
missingif no value can be found.
- load_json(req: Request, schema: Schema) Any¶
Load JSON from a request object or return
missingif no value can be found.
- load_json_or_form(req: Request, schema: Schema) Any¶
Load data from a request, accepting either JSON or form-encoded data.
The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.
- load_querystring(req: Request, schema: Schema) Any¶
Load the query string of a request object or return
missingif no value can be found.
- location_loader(name: str) Callable[[C], C]¶
Decorator that registers a function for loading a request location. The wrapped function receives a schema and a request.
The schema will usually not be relevant, but it’s important in some cases – most notably in order to correctly load multidict values into list fields. Without the schema, there would be no way to know whether to simply
get()orgetall()from a multidict for a given value.Example:
from webargs import core parser = core.Parser() @parser.location_loader("name") def load_data(request, schema): return request.data
- Parameters:
name (str) – The name of the location to register.
- async parse(argmap: core.ArgMap, req: core.Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: core.ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Any[source]¶
Coroutine variant of
webargs.core.Parser.Receives the same arguments as
webargs.core.Parser.parse.
- pre_load(location_data: Mapping, *, schema: Schema, req: Request, location: str) Mapping¶
A method of the parser which can transform data after location loading is done. By default it does nothing, but users can subclass parsers and override this method.
- use_args(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', as_kwargs: bool = False, arg_name: str | None = None, validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable]¶
Decorator that injects parsed arguments into a view function or method.
Example usage with Flask:
@app.route("/echo", methods=["get", "post"]) @parser.use_args({"name": fields.Str()}, location="querystring") def greet(querystring_args): return "Hello " + querystring_args["name"]
- Parameters:
argmap – Either a
marshmallow.Schema, adictof argname ->marshmallow.fields.Fieldpairs, or a callable which accepts a request and returns amarshmallow.Schema.location (str) – Where on the request to load values.
unknown (str) – A value to pass for
unknownwhen calling the schema’sloadmethod.as_kwargs (bool) – Whether to insert arguments as keyword arguments.
arg_name (str) – Keyword argument name to use for arguments. Mutually exclusive with as_kwargs.
validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns
False, the parser will raise aValidationError.error_status_code (int) – Status code passed to error handler functions when a
ValidationErroris raised.error_headers (dict) – Headers passed to error handler functions when a a
ValidationErroris raised.
- use_kwargs(argmap: ArgMap[Request], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable]¶
Decorator that injects parsed arguments into a view function or method as keyword arguments.
This is a shortcut to
use_args()withas_kwargs=True.Example usage with Flask:
@app.route("/echo", methods=["get", "post"]) @parser.use_kwargs({"name": fields.Str()}) def greet(name): return "Hello " + name
Receives the same
argsandkwargsasuse_args().
webargs.flaskparser¶
Flask request argument parsing module.
Example:
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
user_detail_args = {"per_page": fields.Int()}
@app.route("/user/<int:uid>")
@use_args(user_detail_args)
def user_detail(args, uid):
return ("The user page for user {uid}, showing {per_page} posts.").format(
uid=uid, per_page=args["per_page"]
)
- class webargs.flaskparser.FlaskParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Flask request argument parser.
- get_default_request() Request[source]¶
Override to use Flask’s thread-local request object by default
- handle_error(error: ValidationError, req: Request, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn[source]¶
Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error.
- load_files(req: Request, schema: Schema) Any[source]¶
Return files from the request as a MultiDictProxy.
- load_form(req: Request, schema: Schema) Any[source]¶
Return form values from the request as a MultiDictProxy.
- load_headers(req: Request, schema: Schema) Any[source]¶
Return headers from the request as a MultiDictProxy.
webargs.djangoparser¶
Django request argument parsing.
Example usage:
from django.views.generic import View
from django.http import HttpResponse
from marshmallow import fields
from webargs.djangoparser import use_args
hello_args = {"name": fields.Str(load_default="World")}
class MyView(View):
@use_args(hello_args)
def get(self, args, request):
return HttpResponse("Hello " + args["name"])
- class webargs.djangoparser.DjangoParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Django request argument parser.
Warning
DjangoParserdoes not overridehandle_error, so your Django views are responsible for catching anyValidationErrorsraised by the parser and returning the appropriateHTTPResponse.- get_request_from_view_args(view, args, kwargs)[source]¶
Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the
use_argsanduse_kwargsto get a request object from a view’s arguments.
webargs.bottleparser¶
Bottle request argument parsing module.
Example:
from bottle import route, run
from marshmallow import fields
from webargs.bottleparser import use_args
hello_args = {"name": fields.Str(load_default="World")}
@route("/", method="GET", apply=use_args(hello_args))
def index(args):
return "Hello " + args["name"]
if __name__ == "__main__":
run(debug=True)
- class webargs.bottleparser.BottleParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Bottle.py request argument parser.
webargs.tornadoparser¶
Tornado request argument parsing module.
Example:
import tornado.web
from marshmallow import fields
from webargs.tornadoparser import use_args
class HelloHandler(tornado.web.RequestHandler):
@use_args({"name": fields.Str(load_default="World")})
def get(self, args):
response = {"message": "Hello {}".format(args["name"])}
self.write(response)
- exception webargs.tornadoparser.HTTPError(*args: Any, **kwargs: Any)[source]¶
tornado.web.HTTPErrorthat stores validation errors.
- class webargs.tornadoparser.TornadoParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Tornado request argument parser.
- get_request_from_view_args(view: Any, args: tuple[Any, ...], kwargs: Mapping[str, Any]) HTTPServerRequest[source]¶
Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the
use_argsanduse_kwargsto get a request object from a view’s arguments.
- handle_error(error: ValidationError, req: HTTPServerRequest, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn[source]¶
Handles errors during parsing. Raises a
tornado.web.HTTPErrorwith a 400 error.
- load_cookies(req: HTTPServerRequest, schema: Schema) Any[source]¶
Return cookies from the request as a MultiDictProxy.
- load_files(req: HTTPServerRequest, schema: Schema) Any[source]¶
Return files from the request as a MultiDictProxy.
- load_form(req: HTTPServerRequest, schema: Schema) Any[source]¶
Return form values from the request as a MultiDictProxy.
- class webargs.tornadoparser.WebArgsTornadoCookiesMultiDictProxy(multidict: ~collections.abc.MutableMapping, schema: ~marshmallow.schema.Schema, known_multi_fields: tuple[type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]¶
And a special override for cookies because they come back as objects with a
valueattribute we need to extract. Also, does not use the_unicodedecoding step
- class webargs.tornadoparser.WebArgsTornadoMultiDictProxy(multidict: ~collections.abc.MutableMapping, schema: ~marshmallow.schema.Schema, known_multi_fields: tuple[type, ...] = (<class 'marshmallow.fields.List'>, <class 'marshmallow.fields.Tuple'>))[source]¶
Override class for Tornado multidicts, handles argument decoding requirements.
webargs.pyramidparser¶
Pyramid request argument parsing.
Example usage:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
from marshmallow import fields
from webargs.pyramidparser import use_args
hello_args = {"name": fields.Str(load_default="World")}
@use_args(hello_args)
def hello_world(request, args):
return Response("Hello " + args["name"])
if __name__ == "__main__":
config = Configurator()
config.add_route("hello", "/")
config.add_view(hello_world, route_name="hello")
app = config.make_wsgi_app()
server = make_server("0.0.0.0", 6543, app)
server.serve_forever()
- class webargs.pyramidparser.PyramidParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Pyramid request argument parser.
- handle_error(error: ValidationError, req: Request, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn[source]¶
Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error.
- load_cookies(req: Request, schema: Schema) Any[source]¶
Return cookies from the request as a MultiDictProxy.
- load_files(req: Request, schema: Schema) Any[source]¶
Return files from the request as a MultiDictProxy.
- load_form(req: Request, schema: Schema) Any[source]¶
Return form values from the request as a MultiDictProxy.
- load_headers(req: Request, schema: Schema) Any[source]¶
Return headers from the request as a MultiDictProxy.
- load_matchdict(req: Request, schema: Schema) Any[source]¶
Return the request’s
matchdictas a MultiDictProxy.
- load_querystring(req: Request, schema: Schema) Any[source]¶
Return query params from the request as a MultiDictProxy.
- use_args(argmap: core.ArgMap, req: Request | None = None, *, location: str | None = 'json', unknown: str | None = None, as_kwargs: bool = False, arg_name: str | None = None, validate: core.ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable][source]¶
Decorator that injects parsed arguments into a view callable. Supports the Class-based View pattern where
requestis saved as an instance attribute on a view class.- Parameters:
argmap (dict) – Either a
marshmallow.Schema, adictof argname ->marshmallow.fields.Fieldpairs, or a callable which accepts a request and returns amarshmallow.Schema.req – The request object to parse. Pulled off of the view by default.
location (str) – Where on the request to load values.
unknown (str) – A value to pass for
unknownwhen calling the schema’sloadmethod.as_kwargs (bool) – Whether to insert arguments as keyword arguments.
arg_name (str) – Keyword argument name to use for arguments. Mutually exclusive with as_kwargs.
validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns
False, the parser will raise aValidationError.error_status_code (int) – Status code passed to error handler functions when a
ValidationErroris raised.error_headers (dict) – Headers passed to error handler functions when a a
ValidationErroris raised.
- webargs.pyramidparser.use_args(argmap: core.ArgMap, req: Request | None = None, *, location: str | None = 'json', unknown: str | None = None, as_kwargs: bool = False, arg_name: str | None = None, validate: core.ValidateArg = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Callable[..., Callable]¶
Decorator that injects parsed arguments into a view callable. Supports the Class-based View pattern where
requestis saved as an instance attribute on a view class.- Parameters:
argmap (dict) – Either a
marshmallow.Schema, adictof argname ->marshmallow.fields.Fieldpairs, or a callable which accepts a request and returns amarshmallow.Schema.req – The request object to parse. Pulled off of the view by default.
location (str) – Where on the request to load values.
unknown (str) – A value to pass for
unknownwhen calling the schema’sloadmethod.as_kwargs (bool) – Whether to insert arguments as keyword arguments.
arg_name (str) – Keyword argument name to use for arguments. Mutually exclusive with as_kwargs.
validate (callable) – Validation function that receives the dictionary of parsed arguments. If the function returns
False, the parser will raise aValidationError.error_status_code (int) – Status code passed to error handler functions when a
ValidationErroris raised.error_headers (dict) – Headers passed to error handler functions when a a
ValidationErroris raised.
webargs.falconparser¶
Falcon request argument parsing module.
- class webargs.falconparser.FalconParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
Falcon request argument parser.
Defaults to using the
medialocation. Seeload_media()for details on the media location.- get_request_from_view_args(view, args, kwargs)[source]¶
Get request from a resource method’s arguments. Assumes that request is the second argument.
- handle_error(error, req: Request, schema, *, error_status_code, error_headers)[source]¶
Handles errors during parsing.
- load_files(req: Request, schema)[source]¶
Load files from the request or return
missingif no values can be found.
- load_form(req: Request, schema)[source]¶
Return form values from the request as a MultiDictProxy
Note
The request stream will be read and left at EOF.
- load_media(req: Request, schema)[source]¶
Return data unpacked and parsed by one of Falcon’s media handlers. By default, Falcon only handles JSON payloads.
To configure additional media handlers, see the Falcon documentation on media types.
Note
The request stream will be read and left at EOF.
- exception webargs.falconparser.HTTPError(status, errors, *args, **kwargs)[source]¶
HTTPError that stores a dictionary of validation error messages.
- code: int | None¶
An internal application code that a user can reference when requesting support for the error.
- status: ResponseStatus¶
HTTP status code or line (e.g.,
'200 OK').This may be set to a member of
http.HTTPStatus, an HTTP status line string or byte string (e.g.,'200 OK'), or anint.
webargs.aiohttpparser¶
aiohttp request argument parsing module.
Example:
import asyncio
from aiohttp import web
from webargs import fields
from webargs.aiohttpparser import use_args
hello_args = {"name": fields.Str(required=True)}
@asyncio.coroutine
@use_args(hello_args)
def index(request, args):
return web.Response(body="Hello {}".format(args["name"]).encode("utf-8"))
app = web.Application()
app.router.add_route("GET", "/", index)
- class webargs.aiohttpparser.AIOHTTPParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: ErrorHandler | None = None, schema_class: type[ma.Schema] | None = None)[source]¶
aiohttp request argument parser.
- get_request_from_view_args(view: Callable, args: Iterable, kwargs: Mapping)[source]¶
Get request object from a handler function or method. Used internally by
use_argsanduse_kwargs.
- handle_error(error: ValidationError, req, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn[source]¶
Handle ValidationErrors and return a JSON response of error messages to the client.
- load_cookies(req, schema: Schema) MultiDictProxy[source]¶
Return cookies from the request as a MultiDictProxy.
- load_files(req, schema: Schema) NoReturn[source]¶
Load files from the request or return
missingif no values can be found.
- async load_form(req, schema: Schema) MultiDictProxy[source]¶
Return form values from the request as a MultiDictProxy.
- load_headers(req, schema: Schema) MultiDictProxy[source]¶
Return headers from the request as a MultiDictProxy.
- async load_json_or_form(req, schema: Schema) dict | MultiDictProxy[source]¶
Load data from a request, accepting either JSON or form-encoded data.
The data will first be loaded as JSON, and, if that fails, it will be loaded as a form post.
- load_querystring(req, schema: Schema) MultiDictProxy[source]¶
Return query params from the request as a MultiDictProxy.
- exception webargs.aiohttpparser.HTTPUnprocessableEntity(*, headers: Mapping[str, str] | Mapping[istr, str] | CIMultiDict | CIMultiDictProxy | Iterable[Tuple[str | istr, str]] | None = None, reason: str | None = None, body: Any = None, text: str | None = None, content_type: str | None = None)[source]¶