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=None, headers=None, **kwargs)[source]¶Raised when validation fails on user input.
Changed in version 4.2.0: status_code and headers arguments are deprecated. Pass
error_status_code and error_headers to Parser.parse
,
Parser.use_args
, and Parser.use_kwargs
instead.
with_traceback
()¶Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
webargs.core.
dict2schema
(dct)[source]¶Generate a marshmallow.Schema
class given a dictionary of
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.
Parameters: |
|
---|
DEFAULT_VALIDATION_MESSAGE
= 'Invalid value.'¶Default error message for validation errors
DEFAULT_VALIDATION_STATUS
= 422¶Default status code to return for validation errors
error_handler
(func)[source]¶Decorator that registers a custom error handling function. The
function should receive the raised error, request object,
marshmallow.Schema
instance used to parse the request, error status code,
and headers to use for the error response. Overrides
the parser’s handle_error
method.
Example:
from webargs import flaskparser
parser = flaskparser.FlaskParser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
Parameters: | 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.
Parameters: |
|
---|
handle_error
(error, req, schema, error_status_code=None, error_headers=None)[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)
Parameters: | name (str) – The name of the location to register. |
---|
parse
(argmap, req=None, locations=None, validate=None, force_all=False, error_status_code=None, error_headers=None)[source]¶Main request parsing method.
Parameters: |
|
---|
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.
Parameters: |
|
---|---|
Returns: | The unvalidated argument value or |
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, force_all=None, error_status_code=None, error_headers=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']
Parameters: |
|
---|
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
.
Parameters: |
|
---|
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(data_key='Content-Type',
location='headers')
}
Note: data_key
replaced load_from
in marshmallow 3. When using marshmallow 2, use load_from
.
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”).
Parameters: |
---|
Asynchronous request parser. Compatible with Python>=3.5.
webargs.asyncparser.
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 receive the raised error, request object,
marshmallow.Schema
instance used to parse the request, error status code,
and headers to use for the error response. Overrides
the parser’s handle_error
method.
Example:
from webargs import flaskparser
parser = flaskparser.FlaskParser()
class CustomError(Exception):
pass
@parser.error_handler
def handle_error(error, req, schema, status_code, headers):
raise CustomError(error.messages)
Parameters: | 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.
Parameters: |
|
---|
handle_error
(error, req, schema, error_status_code=None, error_headers=None)¶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)
Parameters: | name (str) – The name of the location to register. |
---|
parse
(argmap, req=None, locations=None, validate=None, force_all=False, error_status_code=None, error_headers=None)[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.
Parameters: |
|
---|---|
Returns: | The unvalidated argument value or |
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, force_all=None, error_status_code=None, error_headers=None)[source]¶Decorator that injects parsed arguments into a view function or 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.
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']
webargs.flaskparser.
FlaskParser
(locations=None, error_handler=None)[source]¶Flask request argument parser.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error.
Pull a value from the cookiejar.
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.
Parameters: |
---|
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', apply=use_args(hello_args))
def index(args):
return 'Hello ' + args['name']
if __name__ == '__main__':
run(debug=True)
webargs.bottleparser.
BottleParser
(locations=None, error_handler=None)[source]¶Bottle.py request argument parser.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing. Aborts the current request with a 400 error.
Pull a value from the cookiejar.
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.
Parameters: |
---|
handle_error
(error, req, schema, error_status_code, error_headers)[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, req, schema, error_status_code, error_headers)[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, force_all=None, error_status_code=None, error_headers=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.
Parameters: |
|
---|
Webapp2 request argument parsing module.
Example:
import webapp2
from marshmallow import fields
from webargs.webobparser import use_args
hello_args = {
'name': fields.Str(missing='World')
}
class MainPage(webapp2.RequestHandler):
@use_args(hello_args)
def get_args(self, args):
self.response.write('Hello, {name}!'.format(name=args['name']))
@use_kwargs(hello_args)
def get_kwargs(self, name=None):
self.response.write('Hello, {name}!'.format(name=name))
app = webapp2.WSGIApplication([
webapp2.Route(r'/hello', MainPage, handler_method='get_args'),
webapp2.Route(r'/hello_dict', MainPage, handler_method='get_kwargs'),
], debug=True)
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.
handle_error
(error, req, schema, error_status_code, error_headers)[source]¶Handles errors during parsing.
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, req, schema, error_status_code, error_headers)[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]¶