webargs.core.
WebargsError
[source]¶Base class for all webargs-related errors.
with_traceback
()¶Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
webargs.core.
ValidationError
(message, status_code=422, headers=None, **kwargs)[source]¶Raised when validation fails on user input. Same as
marshmallow.ValidationError
, with the addition of the status_code
and
headers
arguments.
with_traceback
()¶Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
webargs.core.
argmap2schema
(argmap, instance=False, **kwargs)[source]¶Generate a marshmallow.Schema
class given a dictionary of argument
names to Fields
.
webargs.core.
is_multiple
(field)[source]¶Return whether or not field
handles repeated/multi-value arguments.
webargs.core.
Parser
(locations=None, error_handler=None)[source]¶Base parser class that provides high-level implementation for parsing a request.
Descendant classes must provide lower-level implementations for parsing
different locations, e.g. parse_json
, parse_querystring
, etc.
locations (tuple) – Default locations to parse.
error_handler (callable) – Custom error handler function.
error_handler
(func)[source]¶Decorator that registers a custom error handling function. The
function should received the raised error. Overrides
the parser’s handle_error
method.
Example:
from webargs import core
parser = core.Parser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error):
raise CustomError(error)
func (callable) – The error callback to register.
get_default_request
()[source]¶Optional override. Provides a hook for frameworks that use thread-local request objects.
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_args
and use_kwargs
to get a request object from a
view’s arguments.
view (callable) – The view function or method being decorated by
use_args
or use_kwargs
args (tuple) – Positional arguments passed to view
.
kwargs (dict) – Keyword arguments passed to view
.
handle_error
(error)[source]¶Called if an error occurs while parsing args. By default, just logs and
raises error
.
location_handler
(name)[source]¶Decorator that registers a function for parsing a request location.
The wrapped function receives a request, the name of the argument, and
the corresponding Field
object.
Example:
from webargs import core
parser = core.Parser()
@parser.location_handler('name')
def parse_data(request, name, field):
return request.data.get(name)
name (str) – The name of the location to register.
parse
(argmap, req=None, locations=None, validate=None, force_all=False)[source]¶Main request parsing method.
argmap – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse.
locations (tuple) – Where on the request to search for values.
Can include one or more of ('json', 'querystring', 'form',
'headers', 'cookies', 'files')
.
validate (callable) –
that receives the dictionary of parsed arguments. Validator either returns a
boolean or raises a ValidationError
.
A dictionary of parsed arguments
parse_arg
(name, field, req, locations=None)[source]¶Parse a single argument from a request.
Note
This method does not perform validation on the argument.
name (str) – The name of the value.
field (marshmallow.fields.Field) – The marshmallow Field
for the request
parameter.
req – The request object to parse.
locations (tuple) – The locations (‘json’, ‘querystring’, etc.) where to search for the value.
The unvalidated argument value or missing
if the value cannot be found
on the request.
Pull a cookie value from the request or return missing
if the value
cannot be found.
parse_files
(req, name, arg)[source]¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, arg)[source]¶Pull a value from the form data of a request object or return
missing
if the value cannot be found.
parse_headers
(req, name, arg)[source]¶Pull a value from the headers or return missing
if the value
cannot be found.
parse_json
(req, name, arg)[source]¶Pull a JSON value from a request object or return missing
if the
value cannot be found.
parse_querystring
(req, name, arg)[source]¶Pull a value from the query string of a request object or return missing
if
the value cannot be found.
use_args
(argmap, req=None, locations=None, as_kwargs=False, validate=None)[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()})
def greet(args):
return 'Hello ' + args['name']
argmap – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
use_kwargs
(*args, **kwargs)[source]¶Decorator that injects parsed arguments into a view function or method as keyword arguments.
This is a shortcut to use_args()
with as_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 args
and kwargs
as use_args()
.
webargs.core.
get_value
(data, name, field, allow_many_nested=False)[source]¶Get a value from a dictionary. Handles MultiDict
types when
multiple=True
. If the value is not found, return missing
.
data (object) – Mapping (e.g. :type:`dict`) or list-like instance to pull the value from.
name (str) – Name of the key.
multiple (bool) – Whether to handle multiple values.
allow_many_nested (bool) – Whether to allow a list of nested objects
(it is valid only for JSON format, so it is set to True in parse_json
methods).
Field classes.
Includes all fields from marshmallow.fields
in addition to a custom
Nested
field and 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(load_from='Content-Type',
location='headers')
}
webargs.fields.
Nested
(nested, *args, **kwargs)[source]¶Same as marshmallow.fields.Nested
, except can be passed a dictionary as
the first argument, which will be converted to a marshmallow.Schema
.
webargs.fields.
DelimitedList
(cls_or_instance, delimiter=None, as_string=False, **kwargs)[source]¶Same as marshmallow.fields.List
, except can load from either a list or
a delimited string (e.g. “foo,bar,baz”).
Asynchronous request parser. Compatible with Python>=3.4.
webargs.async.
AsyncParser
(locations=None, error_handler=None)[source]¶Asynchronous variant of webargs.core.Parser
, where parsing methods may be
either coroutines or regular methods.
clear_cache
()¶Invalidate the parser’s cache.
error_handler
(func)¶Decorator that registers a custom error handling function. The
function should received the raised error. Overrides
the parser’s handle_error
method.
Example:
from webargs import core
parser = core.Parser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error):
raise CustomError(error)
func (callable) – The error callback to register.
get_default_request
()¶Optional override. Provides a hook for frameworks that use thread-local request objects.
get_request_from_view_args
(view, args, kwargs)¶Optional override. Returns the request object to be parsed, given a view function’s args and kwargs.
Used by the use_args
and use_kwargs
to get a request object from a
view’s arguments.
view (callable) – The view function or method being decorated by
use_args
or use_kwargs
args (tuple) – Positional arguments passed to view
.
kwargs (dict) – Keyword arguments passed to view
.
handle_error
(error)¶Called if an error occurs while parsing args. By default, just logs and
raises error
.
location_handler
(name)¶Decorator that registers a function for parsing a request location.
The wrapped function receives a request, the name of the argument, and
the corresponding Field
object.
Example:
from webargs import core
parser = core.Parser()
@parser.location_handler('name')
def parse_data(request, name, field):
return request.data.get(name)
name (str) – The name of the location to register.
parse
(argmap, req=None, locations=None, validate=None, force_all=False)[source]¶Coroutine variant of webargs.core.Parser
.
Receives the same arguments as webargs.core.Parser.parse
.
parse_arg
(name, field, req, locations=None)[source]¶Parse a single argument from a request.
Note
This method does not perform validation on the argument.
name (str) – The name of the value.
field (marshmallow.fields.Field) – The marshmallow Field
for the request
parameter.
req – The request object to parse.
locations (tuple) – The locations (‘json’, ‘querystring’, etc.) where to search for the value.
The unvalidated argument value or missing
if the value cannot be found
on the request.
Pull a cookie value from the request or return missing
if the value
cannot be found.
parse_files
(req, name, arg)¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, arg)¶Pull a value from the form data of a request object or return
missing
if the value cannot be found.
parse_headers
(req, name, arg)¶Pull a value from the headers or return missing
if the value
cannot be found.
parse_json
(req, name, arg)¶Pull a JSON value from a request object or return missing
if the
value cannot be found.
parse_querystring
(req, name, arg)¶Pull a value from the query string of a request object or return missing
if
the value cannot be found.
use_args
(argmap, req=None, locations=None, as_kwargs=False, validate=None)[source]¶Decorator that injects parsed arguments into a view function or method.
Warning
This will not work with async def
coroutines. Either use a generator-based
coroutine decorated with asyncio.coroutine
or use the
parse
method.
Receives the same arguments as webargs.core.Parser.use_args
.
use_kwargs
(*args, **kwargs)[source]¶Decorator that injects parsed arguments into a view function or method.
Warning
This will not work with async def
coroutines. Either use a generator-based
coroutine decorated with asyncio.coroutine
or use the
parse
method.
Receives the same arguments as webargs.core.Parser.use_kwargs
.
Flask request argument parsing module.
Example:
from flask import Flask
from webargs import fields
from webargs.flaskparser import use_args
app = Flask(__name__)
hello_args = {
'name': fields.Str(required=True)
}
@app.route('/')
@use_args(hello_args)
def index(args):
return 'Hello ' + args['name']
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(missing='World')
}
class MyView(View):
@use_args(hello_args)
def get(self, args, request):
return HttpResponse('Hello ' + args['name'])
webargs.djangoparser.
DjangoParser
(locations=None, error_handler=None)[source]¶Django request argument parser.
Warning
DjangoParser
does not override
handle_error
, so your Django
views are responsible for catching any ValidationErrors
raised by
the parser and returning the appropriate HTTPResponse
.
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_args
and use_kwargs
to get a request object from a
view’s arguments.
Pull the value from the cookiejar.
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(missing='World')
}
@route('/', method='GET')
@use_args(hello_args)
def index(args):
return 'Hello ' + args['name']
if __name__ == '__main__':
run(debug=True)
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(missing='World')})
def get(self, args):
response = {'message': 'Hello {}'.format(args['name'])}
self.write(response)
webargs.tornadoparser.
HTTPError
(*args, **kwargs)[source]¶tornado.web.HTTPError
that stores validation errors.
webargs.tornadoparser.
TornadoParser
(*args, **kwargs)[source]¶Tornado request argument parser.
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_args
and use_kwargs
to get a request object from a
view’s arguments.
handle_error
(error)[source]¶Handles errors during parsing. Raises a tornado.web.HTTPError
with a 400 error.
Pull a value from the header data.
webargs.tornadoparser.
decode_argument
(value, name=None)[source]¶Decodes an argument from the request.
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(missing='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()
webargs.pyramidparser.
PyramidParser
(locations=None, error_handler=None)[source]¶Pyramid request argument parser.
handle_error
(error)[source]¶Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error.
Pull the value from the cookiejar.
use_args
(argmap, req=None, locations='querystring', 'form', 'json', as_kwargs=False, validate=None)[source]¶Decorator that injects parsed arguments into a view callable.
Supports the Class-based View pattern where request
is saved as an instance
attribute on a view class.
argmap (dict) – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse. Pulled off of the view by default.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
webargs.pyramidparser.
use_args
(argmap, req=None, locations='querystring', 'form', 'json', as_kwargs=False, validate=None)¶Decorator that injects parsed arguments into a view callable.
Supports the Class-based View pattern where request
is saved as an instance
attribute on a view class.
argmap (dict) – Either a marshmallow.Schema
, a dict
of argname -> marshmallow.fields.Field
pairs, or a callable
which accepts a request and returns a marshmallow.Schema
.
req – The request object to parse. Pulled off of the view by default.
locations (tuple) – Where on the request to search for values.
as_kwargs (bool) – Whether to insert arguments as keyword arguments.
validate (callable) – Validation function that receives the dictionary
of parsed arguments. If the function returns False
, the parser
will raise a ValidationError
.
Falcon request argument parsing module.
webargs.falconparser.
FalconParser
(locations=None, error_handler=None)[source]¶Falcon request argument parser.
get_request_from_view_args
(view, args, kwargs)[source]¶Get request from a resource method’s arguments. Assumes that request is the second argument.
Pull a cookie value from the request.
parse_files
(req, name, field)[source]¶Pull a file from the request or return missing
if the value file
cannot be found.
parse_form
(req, name, field)[source]¶Pull a form value from the request.
Note
The request stream will be read and left at EOF.
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)
webargs.aiohttpparser.
AIOHTTPParser
(locations=None, error_handler=None)[source]¶aiohttp request argument parser.
get_request_from_view_args
(view, args, kwargs)[source]¶Get request object from a handler function or method. Used internally by
use_args
and use_kwargs
.
handle_error
(error)[source]¶Handle ValidationErrors and return a JSON response of error messages to the client.
Pull a value from the cookiejar.
webargs.aiohttpparser.
HTTPUnprocessableEntity
(*, headers: Union[Mapping[str, str], multidict._multidict.CIMultiDict, multidict._multidict.CIMultiDictProxy, None] = None, reason: Optional[str] = None, body: Any = None, text: Optional[str] = None, content_type: Optional[str] = None)[source]¶