How to use the webargs.core.Parser function in webargs

To help you get started, we’ve selected a few webargs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github marshmallow-code / webargs / tests / test_core.py View on Github external
def test_locations_as_init_arguments(parse_headers, web_request):
    p = Parser(locations=("headers",))
    p.parse({"foo": fields.Field()}, web_request)
    assert parse_headers.called
github marshmallow-code / webargs / tests / test_core.py View on Github external
def test_value_error_raised_if_parse_arg_called_with_invalid_location(web_request):
    field = fields.Field()
    p = Parser()
    with pytest.raises(ValueError) as excinfo:
        p.parse_arg("foo", field, web_request, locations=("invalidlocation", "headers"))
    msg = "Invalid locations arguments: {0}".format(["invalidlocation"])
    assert msg in str(excinfo.value)
github marshmallow-code / webargs / tests / test_core.py View on Github external
def test_custom_default_schema_class(parse_json, web_request):
    class CustomSchema(Schema):
        @pre_load
        def pre_load(self, data, **kwargs):
            data["value"] += " world"
            return data

    class CustomParser(Parser):
        DEFAULT_SCHEMA_CLASS = CustomSchema

    parse_json.return_value = "hello"
    argmap = {"value": fields.Str()}
    p = CustomParser()
    ret = p.parse(argmap, web_request)
    assert ret == {"value": "hello world"}
github marshmallow-code / webargs / tests / test_core.py View on Github external
def test_parse_json_called_by_parse_arg(parse_json, web_request):
    field = fields.Field()
    p = Parser()
    p.parse_arg("foo", field, web_request)
    parse_json.assert_called_with(web_request, "foo", field)
github marshmallow-code / webargs / src / webargs / bottleparser.py View on Github external
'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)
"""
import bottle

from webargs import core
from webargs.core import json


class BottleParser(core.Parser):
    """Bottle.py request argument parser."""

    def parse_querystring(self, req, name, field):
        """Pull a querystring value from the request."""
        return core.get_value(req.query, name, field)

    def parse_form(self, req, name, field):
        """Pull a form value from the request."""
        return core.get_value(req.forms, name, field)

    def parse_json(self, req, name, field):
        """Pull a json value from the request."""
        json_data = self._cache.get("json")
        if json_data is None:
            try:
                self._cache["json"] = json_data = req.json
github marshmallow-code / webargs / src / webargs / falconparser.py View on Github external
"""HTTPError that stores a dictionary of validation error messages.
    """

    def __init__(self, status, errors, *args, **kwargs):
        self.errors = errors
        super(HTTPError, self).__init__(status, *args, **kwargs)

    def to_dict(self, *args, **kwargs):
        """Override `falcon.HTTPError` to include error messages in responses."""
        ret = super(HTTPError, self).to_dict(*args, **kwargs)
        if self.errors is not None:
            ret["errors"] = self.errors
        return ret


class FalconParser(core.Parser):
    """Falcon request argument parser."""

    def parse_querystring(self, req, name, field):
        """Pull a querystring value from the request."""
        return core.get_value(req.params, name, field)

    def parse_form(self, req, name, field):
        """Pull a form value from the request.

        .. note::

            The request stream will be read and left at EOF.
        """
        form = self._cache.get("form")
        if form is None:
            self._cache["form"] = form = parse_form_body(req)
github elemental-lf / benji / src / benji / amqp / rpc.py View on Github external
def _setup_common_queues(channel, queue: str):
    arguments = {'x-message-ttl': AMQP_MESSAGE_TTL}
    auto_delete = False
    if queue == '':
        arguments['x-expires'] = AMQP_AUTO_DELETE_QUEUE_TIMEOUT
        auto_delete = True
    queue_declare_result = channel.queue_declare(queue=queue,
                                                 durable=True,
                                                 auto_delete=auto_delete,
                                                 arguments=arguments)
    return queue_declare_result.method.queue


class _ArgumentsParser(Parser):

    def load_json(self, req, schema) -> Any:
        return req

    def load_json_or_form(self, req, schema):
        return missing

    def load_headers(self, req, schema) -> MultiDictProxy:
        return MultiDictProxy({'Content-Type': 'application/json; charset="utf-8"'})

    def handle_error(self, error, req, schema, *, error_status_code, error_headers) -> None:
        raise TypeError(error)

    def get_request_from_view_args(self, view, args, kwargs) -> Dict[str, Any]:
        return args[0]
github marshmallow-code / webargs / src / webargs / aiohttpparser.py View on Github external
continue
        exception_map[obj.status_code] = obj


# Collect all exceptions from aiohttp.web_exceptions
_find_exceptions()
del _find_exceptions


class AIOHTTPParser(AsyncParser):
    """aiohttp request argument parser."""

    __location_map__ = dict(
        match_info="parse_match_info",
        path="parse_match_info",
        **core.Parser.__location_map__
    )

    def parse_querystring(self, req: Request, name: str, field: Field) -> typing.Any:
        """Pull a querystring value from the request."""
        return core.get_value(req.query, name, field)

    async def parse_form(self, req: Request, name: str, field: Field) -> typing.Any:
        """Pull a form value from the request."""
        post_data = self._cache.get("post")
        if post_data is None:
            self._cache["post"] = await req.post()
        return core.get_value(self._cache["post"], name, field)

    async def parse_json(self, req: Request, name: str, field: Field) -> typing.Any:
        """Pull a json value from the request."""
        json_data = self._cache.get("json")
github marshmallow-code / webargs / src / webargs / pyramidparser.py View on Github external
def use_args(
        self,
        argmap,
        req=None,
        locations=core.Parser.DEFAULT_LOCATIONS,
        as_kwargs=False,
        validate=None,
        error_status_code=None,
        error_headers=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.

        :param dict 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`.
        :param req: The request object to parse. Pulled off of the view by default.
        :param tuple locations: Where on the request to search for values.
        :param bool as_kwargs: Whether to insert arguments as keyword arguments.
        :param callable validate: Validation function that receives the dictionary
github marshmallow-code / webargs / src / webargs / pyramidparser.py View on Github external
app = config.make_wsgi_app()
        server = make_server('0.0.0.0', 6543, app)
        server.serve_forever()
"""
import collections
import functools

from webob.multidict import MultiDict
from pyramid.httpexceptions import exception_response

from webargs import core
from webargs.core import json
from webargs.compat import text_type


class PyramidParser(core.Parser):
    """Pyramid request argument parser."""

    __location_map__ = dict(
        matchdict="parse_matchdict",
        path="parse_matchdict",
        **core.Parser.__location_map__
    )

    def parse_querystring(self, req, name, field):
        """Pull a querystring value from the request."""
        return core.get_value(req.GET, name, field)

    def parse_form(self, req, name, field):
        """Pull a form value from the request."""
        return core.get_value(req.POST, name, field)

webargs

Declarative parsing and validation of HTTP request objects, with built-in support for popular web frameworks, including Flask, Django, Bottle, Tornado, Pyramid, Falcon, and aiohttp.

MIT
Latest version published 4 months ago

Package Health Score

88 / 100
Full package analysis

Similar packages