The zaqar.common.api.utils
module¶
-
error_response
(req, exception, headers=None, error=None)¶
-
filter_fields
(document, spec)¶ Validates and retrieves typed fields from a single document.
Sanitizes a dict-like document by checking it against a list of field spec, and returning only those fields specified.
Parameters: - document – dict-like object
- spec – iterable describing expected fields, yielding tuples with the form of: (field_name, value_type). Note that value_type may either be a Python type, or the special string ‘*’ to accept any type.
Raises: BadRequest if any field is missing or not an instance of the specified type
Returns: A filtered dict containing only the fields listed in the spec
-
format_message
(message, claim_id=None)¶
-
get_checked_field
(document, name, value_type, default_value)¶ Validates and retrieves a typed field from a document.
This function attempts to look up doc[name], and raises appropriate errors if the field is missing or not an instance of the given type.
Parameters: - document – dict-like object
- name – field name
- value_type – expected value type, or ‘*’ to accept any type
- default_value – Default value to use if the value is missing, or None to make the value required.
Raises: BadRequest if the field is missing or not an instance of value_type
Returns: value obtained from doc[name]
-
get_client_uuid
(req)¶ Read a required Client-ID from a request.
Parameters: req – Request object Raises: BadRequest if the Client-ID header is missing or does not represent a valid UUID Returns: A UUID object
-
get_headers
(req)¶
-
on_exception_sends_500
(func)¶ Handles generic Exceptions in API endpoints
This decorator catches generic Exceptions and returns a generic Response.
-
sanitize
(document, spec=None, doctype=<type ‘dict’>)¶ Validates a document and drops undesired fields.
Parameters: - document – A dict to verify according to spec.
- spec –
(Default None) Iterable describing expected fields, yielding tuples with the form of:
(field_name, value_type, default_value)Note that value_type may either be a Python type, or the special string ‘*’ to accept any type. default_value is the default to give the field if it is missing, or None to require that the field be present.
If spec is None, the incoming documents will not be validated.
- doctype – type of document to expect; must be either JSONObject or JSONArray.
Raises: DocumentTypeNotSupported, TypeError
Returns: A sanitized, filtered version of the document. If the document is a list of objects, each object will be filtered and returned in a new list. If, on the other hand, the document is expected to contain a single object, that object’s fields will be filtered and the resulting object will be returned.