def 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. :param document: dict-like object :param name: field name :param value_type: expected value type, or '*' to accept any type :param 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] """ try: value = document[name] except KeyError: if default_value is not None: value = default_value else: description = _(u'Missing "{name}" field.').format(name=name) raise api_errors.BadRequest(description) # PERF(kgriffs): We do our own little spec thing because it is way # faster than jsonschema. if value_type == '*' or isinstance(value, value_type): return value description = _(u'The value of the "{name}" field must be a {vtype}.') description = description.format(name=name, vtype=value_type.__name__) raise api_errors.BadRequest(description)
def get_client_uuid(req): """Read a required Client-ID from a request. :param req: Request object :raises: BadRequest if the Client-ID header is missing or does not represent a valid UUID :returns: A UUID object """ try: return uuid.UUID(req._headers.get('Client-ID')) except ValueError: description = _(u'Malformed hexadecimal UUID.') raise api_errors.BadRequest(description)