Python falcon.HTTPUnsupportedMediaType() Examples

The following are 10 code examples of falcon.HTTPUnsupportedMediaType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: decorators.py    From certidude with MIT License 6 votes vote down vote up
def serialize(func):
    """
    Falcon response serialization
    """
    import falcon
    def wrapped(instance, req, resp, **kwargs):
        retval = func(instance, req, resp, **kwargs)
        if not resp.body and not resp.location:
            if not req.client_accepts("application/json"):
                logger.debug("Client did not accept application/json")
                raise falcon.HTTPUnsupportedMediaType(
                    "Client did not accept application/json")
            resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate")
            resp.set_header("Pragma", "no-cache")
            resp.set_header("Expires", "0")
            resp.body = json.dumps(retval, cls=MyEncoder)
    return wrapped 
Example #2
Source File: revoked.py    From certidude with MIT License 6 votes vote down vote up
def on_get(self, req, resp):
        # Primarily offer DER encoded CRL as per RFC5280
        # This is also what StrongSwan expects
        if req.client_accepts("application/x-pkcs7-crl"):
            resp.set_header("Content-Type", "application/x-pkcs7-crl")
            resp.append_header(
                "Content-Disposition",
                ("attachment; filename=%s.crl" % const.HOSTNAME))
            # Convert PEM to DER
            logger.debug("Serving revocation list (DER) to %s", req.context.get("remote_addr"))
            resp.body = self.authority.export_crl(pem=False)
        elif req.client_accepts("application/x-pem-file"):
            resp.set_header("Content-Type", "application/x-pem-file")
            resp.append_header(
                "Content-Disposition",
                ("attachment; filename=%s-crl.pem" % const.HOSTNAME))
            logger.debug("Serving revocation list (PEM) to %s", req.context.get("remote_addr"))
            resp.body = self.authority.export_crl()
        else:
            logger.debug("Client %s asked revocation list in unsupported format" % req.context.get("remote_addr"))
            raise falcon.HTTPUnsupportedMediaType(
                "Client did not accept application/x-pkcs7-crl or application/x-pem-file") 
Example #3
Source File: api.py    From butterknife with MIT License 6 votes vote down vote up
def serialize(func):
    """
    Falcon response serialization
    """
    def wrapped(instance, req, resp, **kwargs):
        assert not req.get_param("unicode") or req.get_param("unicode") == u"✓", "Unicode sanity check failed"
        resp.set_header("Cache-Control", "no-cache, no-store, must-revalidate");
        resp.set_header("Pragma", "no-cache");
        resp.set_header("Expires", "0");
        r = func(instance, req, resp, **kwargs)
        if not resp.body:
            if not req.client_accepts_json:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports the JSON media type.',
                    href='http://docs.examples.com/api/json')
            resp.set_header('Content-Type', 'application/json')
            resp.body = json.dumps(r, cls=MyEncoder)
        return r
    return wrapped 
Example #4
Source File: test_resources.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_require_representation_unsupported_media_type():
    resource = TestResource()

    # invalid content type format
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'foo bar'},
    )

    with pytest.raises(falcon.HTTPUnsupportedMediaType):
        resource.require_representation(Request(env))

    # valid format but surely unsupported (RFC-1437)
    env = create_environ(
        body=json.dumps({'one': 'foo', 'two': 'foo'}),
        headers={'Content-Type': 'matter-transport/sentient-life-form'},
    )

    with pytest.raises(falcon.HTTPUnsupportedMediaType):
        resource.require_representation(Request(env)) 
Example #5
Source File: firewall.py    From certidude with MIT License 5 votes vote down vote up
def whitelist_content_types(*content_types):
    def wrapper(func):
        def wrapped(self, req, resp, *args, **kwargs):
            for content_type in content_types:
                if req.get_header("Content-Type") == content_type:
                    return func(self, req, resp, *args, **kwargs)
            raise falcon.HTTPUnsupportedMediaType(
                "This API call accepts only %s content type" % ", ".join(content_types))
        return wrapped
    return wrapper 
Example #6
Source File: request.py    From certidude with MIT License 5 votes vote down vote up
def on_get(self, req, resp, cn):
        """
        Fetch certificate signing request as PEM
        """

        try:
            path, buf, _, submitted = self.authority.get_request(cn)
        except errors.RequestDoesNotExist:
            logger.warning("Failed to serve non-existant request %s to %s",
                cn, req.context.get("remote_addr"))
            raise falcon.HTTPNotFound()

        resp.set_header("Content-Type", "application/pkcs10")
        logger.debug("Signing request %s was downloaded by %s",
            cn, req.context.get("remote_addr"))

        preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))

        if preferred_type == "application/x-pem-file":
            # For certidude client, curl scripts etc
            resp.set_header("Content-Type", "application/x-pem-file")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
            resp.body = buf
        elif preferred_type == "application/json":
            # For web interface events
            resp.set_header("Content-Type", "application/json")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
            resp.body = json.dumps(dict(
                submitted = submitted,
                common_name = cn,
                address = getxattr(path, "user.request.address").decode("ascii"), # TODO: move to authority.py
                md5sum = hashlib.md5(buf).hexdigest(),
                sha1sum = hashlib.sha1(buf).hexdigest(),
                sha256sum = hashlib.sha256(buf).hexdigest(),
                sha512sum = hashlib.sha512(buf).hexdigest()), cls=MyEncoder)
        else:
            raise falcon.HTTPUnsupportedMediaType(
                "Client did not accept application/json or application/x-pem-file") 
Example #7
Source File: base.py    From graceful with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def require_representation(self, req):
        """Require raw representation dictionary from falcon request object.

        This does not perform any field parsing or validation but only uses
        allowed content-encoding handler to decode content body.

        Note:
            Currently only JSON is allowed as content type.

        Args:
            req (falcon.Request): request object

        Returns:
            dict: raw dictionary of representation supplied in request body

        """
        try:
            type_, subtype, _ = parse_mime_type(req.content_type)
            content_type = '/'.join((type_, subtype))
        except:
            raise falcon.HTTPUnsupportedMediaType(
                description="Invalid Content-Type header: {}".format(
                    req.content_type
                )
            )

        if content_type == 'application/json':
            body = req.stream.read()
            return json.loads(body.decode('utf-8'))
        else:
            raise falcon.HTTPUnsupportedMediaType(
                description="only JSON supported, got: {}".format(content_type)
            ) 
Example #8
Source File: validation.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def validate_content_type(req, allowed):
    """Validates content type.

    Method validates request against correct
    content type.

    If content-type cannot be established (i.e. header is missing),
    :py:class:`falcon.HTTPMissingHeader` is thrown.
    If content-type is not **application/json** or **text/plain**,
    :py:class:`falcon.HTTPUnsupportedMediaType` is thrown.


    :param falcon.Request req: current request
    :param iterable allowed: allowed content type

    :exception: :py:class:`falcon.HTTPMissingHeader`
    :exception: :py:class:`falcon.HTTPUnsupportedMediaType`
    """
    content_type = req.content_type

    LOG.debug('Content-Type is %s', content_type)

    if content_type is None or len(content_type) == 0:
        raise falcon.HTTPMissingHeader('Content-Type')

    if content_type not in allowed:
        sup_types = ', '.join(allowed)
        details = ('Only [%s] are accepted as logs representations'
                   % str(sup_types))
        raise falcon.HTTPUnsupportedMediaType(description=details) 
Example #9
Source File: validation.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def validate_content_type(req, allowed):
    """Validates content type.

    Method validates request against correct
    content type.

    If content-type cannot be established (i.e. header is missing),
    :py:class:`falcon.HTTPMissingHeader` is thrown.
    If content-type is not **application/json** or **text/plain**,
    :py:class:`falcon.HTTPUnsupportedMediaType` is thrown.


    :param falcon.Request req: current request
    :param iterable allowed: allowed content type

    :exception: :py:class:`falcon.HTTPMissingHeader`
    :exception: :py:class:`falcon.HTTPUnsupportedMediaType`
    """
    content_type = req.content_type

    LOG.debug('Content-Type is %s', content_type)

    if content_type is None or len(content_type) == 0:
        raise falcon.HTTPMissingHeader('Content-Type')

    if content_type not in allowed:
        sup_types = ', '.join(allowed)
        details = ('Only [%s] are accepted as logs representations'
                   % str(sup_types))
        raise falcon.HTTPUnsupportedMediaType(description=details) 
Example #10
Source File: signed.py    From certidude with MIT License 4 votes vote down vote up
def on_get(self, req, resp, cn):

        preferred_type = req.client_prefers(("application/json", "application/x-pem-file"))
        try:
            path, buf, cert, signed, expires = self.authority.get_signed(cn)
        except EnvironmentError:
            logger.warning("Failed to serve non-existant certificate %s to %s",
                cn, req.context.get("remote_addr"))
            raise falcon.HTTPNotFound()

        if preferred_type == "application/x-pem-file":
            resp.set_header("Content-Type", "application/x-pem-file")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.pem" % cn))
            resp.body = buf
            logger.debug("Served certificate %s to %s as application/x-pem-file",
                cn, req.context.get("remote_addr"))
        elif preferred_type == "application/json":
            resp.set_header("Content-Type", "application/json")
            resp.set_header("Content-Disposition", ("attachment; filename=%s.json" % cn))
            try:
                signer_username = getxattr(path, "user.signature.username").decode("ascii")
            except IOError:
                signer_username = None

            attributes = {}
            for key in listxattr(path):
                if key.startswith(b"user.machine."):
                    attributes[key[13:].decode("ascii")] = getxattr(path, key).decode("ascii")

            # TODO: dedup
            resp.body = json.dumps(dict(
                common_name = cn,
                signer = signer_username,
                serial = "%040x" % cert.serial_number,
                organizational_unit = cert.subject.native.get("organizational_unit_name"),
                signed = cert["tbs_certificate"]["validity"]["not_before"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
                expires = cert["tbs_certificate"]["validity"]["not_after"].native.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z",
                sha256sum = hashlib.sha256(buf).hexdigest(),
                attributes = attributes or None,
                lease = None,
                extensions = dict([
                    (e["extn_id"].native, e["extn_value"].native)
                    for e in cert["tbs_certificate"]["extensions"]
                    if e["extn_id"].native in ("extended_key_usage",)])

            ))
            logger.debug("Served certificate %s to %s as application/json",
                cn, req.context.get("remote_addr"))
        else:
            logger.debug("Client did not accept application/json or application/x-pem-file")
            raise falcon.HTTPUnsupportedMediaType(
                "Client did not accept application/json or application/x-pem-file")