dservercore.sort

Sort feature

Introduces and parses sort parameter for blueprints.

Classes

CommaSeparatedListFlaskParser([location, ...])

Parses nested query args

SortMetadataSchema(*[, only, exclude, many, ...])

Sort metadata schema

SortMixin()

Extend Blueprint to add Sort feature

SortParameters(sort)

Holds sort arguments

class dservercore.sort.CommaSeparatedListFlaskParser(location: str | None = None, *, unknown: str | None = '_default', error_handler: Callable[[...], NoReturn] | None = None, schema_class: type[Schema] | None = None)

Bases: FlaskParser

Parses nested query args

This parser handles sort arguments of the comma-separated list format

?sort=+username,-is_admin

or similar.

For example, the URL query params `?sort=+username,-is_admin will yield the following dict:

{

‘sort’: [‘+username’, ‘-is_admin’]

}

load_querystring(req, schema)

Return query params from the request as a MultiDictProxy.

DEFAULT_LOCATION: str = 'json'

Default location to check for data

DEFAULT_SCHEMA_CLASS

alias of Schema

DEFAULT_UNKNOWN_BY_LOCATION: dict[str, str | None] = {'cookies': 'exclude', 'files': 'exclude', 'form': None, 'headers': 'exclude', 'json': None, 'json_or_form': None, 'path': 'raise', 'query': 'exclude', 'querystring': 'exclude', 'view_args': 'raise'}
DEFAULT_VALIDATION_MESSAGE: str = 'Invalid value.'

Default error message for validation errors

DEFAULT_VALIDATION_STATUS: int = 422

Default status code to return for validation errors

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

USE_ARGS_POSITIONAL: bool = True
__init__(location: str | None = None, *, unknown: str | None = '_default', error_handler: Callable[[...], NoReturn] | None = None, schema_class: type[Schema] | None = None) None
async async_parse(argmap: Schema | Type[Schema] | Mapping[str, Field | Type[Field]] | Callable[[Request], Schema], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: None | Callable | Iterable[Callable] = 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.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, *, error_status_code, error_headers):
    raise CustomError(error.messages)
Parameters:

func (callable) – The error callback to register.

get_default_arg_name(location: str, schema: Schema | Type[Schema] | Mapping[str, Field | Type[Field]] | Callable[[Request], Schema]) str

This method provides the rule by which an argument name is derived for use_args() if no explicit arg_name is provided.

By default, the format used is {location}_args. Users may override this method to customize the default argument naming scheme.

schema will be the argument map or schema passed to use_args() unless a dict was used, in which case it will be the schema derived from that dict.

get_default_request() Request

Override to use Flask’s thread-local request object by default

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_args and use_kwargs to get a request object from a view’s arguments.

Parameters:
  • 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: ValidationError, req: Request, schema: Schema, *, error_status_code: int | None, error_headers: Mapping[str, str] | None) NoReturn

Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error.

load_cookies(req: Request, schema: Schema) Any

Return cookies from the request.

load_files(req: Request, schema: Schema) Any

Return files from the request as a MultiDictProxy.

load_form(req: Request, schema: Schema) Any

Return form values from the request as a MultiDictProxy.

load_headers(req: Request, schema: Schema) Any

Return headers from the request as a MultiDictProxy.

load_json(req: Request, schema: Schema) Any

Load JSON from a request object or return missing if 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_view_args(req: Request, schema: Schema) Any

Return the request’s view_args or missing if there are none.

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() or .getall() 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: Schema | Type[Schema] | Mapping[str, Field | Type[Field]] | Callable[[Request], Schema], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: None | Callable | Iterable[Callable] = None, error_status_code: int | None = None, error_headers: Mapping[str, str] | None = None) Any

Main request parsing method.

Parameters:
  • 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.

  • 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 unknown when calling the schema’s load method. Defaults to marshmallow.EXCLUDE for non-body locations and marshmallow.RAISE for request bodies. Pass None to 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 ValidationError is raised.

  • error_headers (dict) –

    Headers passed to error handler functions when a

    a ValidationError is raised.

    return:

    A dictionary of parsed arguments

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: Schema | Type[Schema] | Mapping[str, Field | Type[Field]] | Callable[[Request], Schema], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', as_kwargs: bool = False, arg_name: str | None = None, validate: None | Callable | Iterable[Callable] = 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, a dict of argname -> marshmallow.fields.Field pairs, or a callable which accepts a request and returns a marshmallow.Schema.

  • location (str) – Where on the request to load values.

  • unknown (str) – A value to pass for unknown when calling the schema’s load method.

  • 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 a ValidationError.

  • error_status_code (int) – Status code passed to error handler functions when a ValidationError is raised.

  • error_headers (dict) – Headers passed to error handler functions when a a ValidationError is raised.

use_kwargs(argmap: Schema | Type[Schema] | Mapping[str, Field | Type[Field]] | Callable[[Request], Schema], req: Request | None = None, *, location: str | None = None, unknown: str | None = '_default', validate: None | Callable | Iterable[Callable] = 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() 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().

class dservercore.sort.SortParameters(sort)

Bases: object

Holds sort arguments

Parameters:
  • sort (list of str) – list of fields

  • order (list of int) – ASCENDING (1) or DESCENDING (-1)

__init__(sort)
property order
class dservercore.sort.SortMetadataSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: Schema

Sort metadata schema

Used to serialize sort metadata. Its main purpose is to document the sort metadata.

class Meta

Bases: object

ordered = True
OPTIONS_CLASS

alias of SchemaOpts

TYPE_MAPPING: Dict[type, Type[ma_fields.Field]] = {<class 'bool'>: <class 'marshmallow.fields.Boolean'>, <class 'bytes'>: <class 'marshmallow.fields.String'>, <class 'datetime.date'>: <class 'marshmallow.fields.Date'>, <class 'datetime.datetime'>: <class 'marshmallow.fields.DateTime'>, <class 'datetime.time'>: <class 'marshmallow.fields.Time'>, <class 'datetime.timedelta'>: <class 'marshmallow.fields.TimeDelta'>, <class 'decimal.Decimal'>: <class 'marshmallow.fields.Decimal'>, <class 'float'>: <class 'marshmallow.fields.Float'>, <class 'int'>: <class 'marshmallow.fields.Integer'>, <class 'list'>: <class 'marshmallow.fields.Raw'>, <class 'set'>: <class 'marshmallow.fields.Raw'>, <class 'str'>: <class 'marshmallow.fields.String'>, <class 'tuple'>: <class 'marshmallow.fields.Raw'>, <class 'uuid.UUID'>: <class 'marshmallow.fields.UUID'>}
__init__(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool = False, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)
property dict_class: type
dump(obj: Any, *, many: bool | None = None)

Serialize an object to native Python data types according to this Schema’s fields.

Parameters:
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns:

Serialized data

Added in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

Changed in version 3.0.0rc9: Validation no longer occurs upon serialization.

dumps(obj: Any, *args, many: bool | None = None, **kwargs)

Same as dump(), except return a JSON-encoded string.

Parameters:
  • obj – The object to serialize.

  • many – Whether to serialize obj as a collection. If None, the value for self.many is used.

Returns:

A json string

Added in version 1.0.0.

Changed in version 3.0.0b7: This method returns the serialized data rather than a (data, errors) duple. A ValidationError is raised if obj is invalid.

error_messages: Dict[str, str] = {}

Overrides for default schema-level error messages

classmethod from_dict(fields: dict[str, Field | type], *, name: str = 'GeneratedSchema') type

Generate a Schema class given a dictionary of fields.

from marshmallow import Schema, fields

PersonSchema = Schema.from_dict({"name": fields.Str()})
print(PersonSchema().load({"name": "David"}))  # => {'name': 'David'}

Generated schemas are not added to the class registry and therefore cannot be referred to by name in Nested fields.

Parameters:
  • fields (dict) – Dictionary mapping field names to field instances.

  • name (str) – Optional name for the class, which will appear in the repr for the class.

Added in version 3.0.0.

get_attribute(obj: Any, attr: str, default: Any)

Defines how to pull values from an object to serialize.

Added in version 2.0.0.

Changed in version 3.0.0a1: Changed position of obj and attr.

handle_error(error: ValidationError, data: Any, *, many: bool, **kwargs)

Custom error handler function for the schema.

Parameters:
  • error – The ValidationError raised during (de)serialization.

  • data – The original input data.

  • many – Value of many on dump or load.

  • partial – Value of partial on load.

Added in version 2.0.0.

Changed in version 3.0.0rc9: Receives many and partial (on deserialization) as keyword arguments.

load(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Deserialize a data structure to an object defined by this Schema’s fields.

Parameters:
  • data – The data to deserialize.

  • many – Whether to deserialize data as a collection. If None, the value for self.many is used.

  • partial – Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

Returns:

Deserialized data

Added in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

loads(json_data: str, *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None, **kwargs)

Same as load(), except it takes a JSON string as input.

Parameters:
  • json_data – A JSON string of the data to deserialize.

  • many – Whether to deserialize obj as a collection. If None, the value for self.many is used.

  • partial – Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

  • unknown – Whether to exclude, include, or raise an error for unknown fields in the data. Use EXCLUDE, INCLUDE or RAISE. If None, the value for self.unknown is used.

Returns:

Deserialized data

Added in version 1.0.0.

Changed in version 3.0.0b7: This method returns the deserialized data rather than a (data, errors) duple. A ValidationError is raised if invalid data are passed.

on_bind_field(field_name: str, field_obj: Field) None

Hook to modify a field when it is bound to the Schema.

No-op by default.

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
set_class

alias of OrderedSet

validate(data: Mapping[str, Any] | Iterable[Mapping[str, Any]], *, many: bool | None = None, partial: bool | Sequence[str] | AbstractSet[str] | None = None) dict[str, list[str]]

Validate data against the schema, returning a dictionary of validation errors.

Parameters:
  • data – The data to validate.

  • many – Whether to validate data as a collection. If None, the value for self.many is used.

  • partial – Whether to ignore missing fields and not require any fields declared. Propagates down to Nested fields as well. If its value is an iterable, only missing fields listed in that iterable will be ignored. Use dot delimiters to specify nested fields.

Returns:

A dictionary of validation errors.

Added in version 1.1.0.

fields: Dict[str, ma_fields.Field]

Dictionary mapping field_names -> Field objects

class dservercore.sort.SortMixin

Bases: object

Extend Blueprint to add Sort feature

SORT_ARGUMENTS_PARSER = <dservercore.sort.CommaSeparatedListFlaskParser object>
SORT_HEADER_NAME = 'X-Sort'
DEFAULT_ALLOWED_SORT_FIELDS = []
DEFAULT_SORT_PARAMETERS = {'sort': []}
sort(*, sort=None, allowed_sort_fields=None)

Decorator adding sorting to the endpoint

Parameters:
  • sort (str) – Default requested sort string

  • allowed_sort_fields (list of str) – Allowed sort fields

The decorated function may return a tuple including status and/or headers, like a typical flask view function. It may not return a Response object.