Ejemplo n.º 1
0
    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))
Ejemplo n.º 2
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        if req.method in ('POST', 'PUT'):
            if req.content_type is None:
                raise falcon.HTTPUnsupportedMediaType(
                    'No encoding given. This API only supports requests encoded as JSON.',
                    href='https://github.com/eoss-cloud/madxxx_catalog_api')
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='https://github.com/eoss-cloud/madxxx_catalog_api')
Ejemplo n.º 3
0
    def on_post(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.')

        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')

        data = json.loads(req.stream.read().decode('utf-8'))
        print(data)
        action = data['action']
        result = {'action': action, 'result': 0}

        if action == 'add':
            add_result = self.contacts.insert_one(data['data'])
            result['result'] = str(add_result.inserted_id)

        elif action == 'delete':
            delete_result = self.contacts.delete_one(
                {'_id': ObjectId(data['id'])})
            if (delete_result.deleted_count):
                result['result'] = data['id']

        elif action == 'update':
            update_result = self.contacts.replace_one(
                {'_id': ObjectId(data['id'])}, data['data'])
            if (update_result.modified_count):
                result['result'] = data['id']

        resp.content_type = 'application/json'
        resp.body = json_util.dumps(result)
Ejemplo n.º 4
0
    def process_request(self, request, response):
        if not request.client_accepts_json:
            raise falcon.HTTPNotAcceptable('Response encoded as JSON')

        if request.method in ('POST'):
            if 'application/json' not in request.content_type:
                raise falcon.HTTPUnsupportedMediaType('Requests encoded as JSON')
Ejemplo n.º 5
0
    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:
            By default, 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))
        return self.media_handler.handle_request(req,
                                                 content_type=content_type)
Ejemplo n.º 6
0
    def process_request(self, req, resp):
        """
        # req.stream corresponds to the WSGI wsgi.input environ variable,
        # and allows you to read bytes from the request body.
        #
        # See also: PEP 3333

        :param req:
        :param resp:
        :return:
        """

        if req.content_length in (None, 0):
            # Nothing to do
            return

        try:
            if 'application/json' in req.content_type:
                body = req.stream.read()
                if not body:
                    raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.')
                req.context['doc'] = json.loads(body.decode('utf-8'))
            elif 'multipart/form-data' in (req.content_type or ''):
                parse(req)
            else:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON or multipart/form-data.')
        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753,
                                   'Malformed JSON',
                                   'Could not decode the request body. The '
                                   'JSON was incorrect or not encoded as '
                                   'UTF-8.')
Ejemplo n.º 7
0
    def process_request(self, req, resp):
        logger.info('Incoming request ' + req.path)

        enforce = False
        if self.paths is None:
            enforce = True
        else:
            for path in self.paths:
                if req.path.startswith(path):
                    enforce = True

        if enforce:
            if not req.client_accepts_json:
                logger.info(
                    'Client does not accept an JSON answer for {path}'.format(
                        path=req.path))
                raise falcon.HTTPNotAcceptable(
                    'This API only supports responses encoded as JSON.',
                    href='http://docs.examples.com/api/json')

            if req.method in ('POST', 'PUT'):
                logger.info(
                    'For path {method}: {path} only JSON requests are accepted'
                    .format(method=req.method, path=req.path))
                if 'application/json' not in req.content_type:
                    raise falcon.HTTPUnsupportedMediaType(
                        'This API only supports requests encoded as JSON.',
                        href='http://docs.examples.com/api/json')
Ejemplo n.º 8
0
 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"
         )
Ejemplo n.º 9
0
def check_media_type(req, resp, params):
    if req.client_accepts_json:
        return
    raise falcon.HTTPUnsupportedMediaType(
        'Media Type not Supported',
        'This API only supports the JSON media type.',
        'http://docs.examples.com/api/json')
Ejemplo n.º 10
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable('This API only supports responses encoded as JSON.')

        if req.method in ('POST', 'PUT', 'PATCH', 'DELETE'):
            if not req.content_type or 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType('This API only supports requests encoded as JSON.')
def _validate_content_type(req):
    """Validate content type.

    Function 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**(supported contents

    types are define in SUPPORTED_CONTENT_TYPES variable),
    :py:class:`falcon.HTTPUnsupportedMediaType` is thrown.

    :param falcon.Request req: current request

    :exception: :py:class:`falcon.HTTPMissingHeader`
    :exception: :py:class:`falcon.HTTPUnsupportedMediaType`
    """
    content_type = req.content_type
    LOG.debug('Content-type is {0}'.format(content_type))

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

    if content_type not in SUPPORTED_CONTENT_TYPES:
        types = ','.join(SUPPORTED_CONTENT_TYPES)
        details = (
            'Only [{0}] are accepted as events representation'.format(types))
        raise falcon.HTTPUnsupportedMediaType(description=details)
Ejemplo n.º 12
0
    def on_get(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')

        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='http://docs.examples.com/api/json')

        #id = req.get_param('id')
        #profiles = RetrieveProfile().ExtractUsersData()
        #for profile in profiles:
        #    profile.addTag()

        #recommendations = Recommendation.RetrieveProfileAndCalculate(profiles)

        #resp.content_type = falcon.MEDIA_JSON

        #simples = []
        #for recommendation in recommendations:
        #    simple = Simple(recommendation.profile.id, recommendation.recommendations)
        #    simples.append(simple)

        url = "https://8yibsgfqyb.execute-api.us-east-1.amazonaws.com/default/testConnectionMongoDB"
        payload = {}
        headers = {}
        response = requests.request("GET", url, headers=headers, data=payload)
        print(response.text.encode('utf8'))
        resp.body = response.text.encode('utf8')
        resp.status = falcon.HTTP_200
Ejemplo n.º 13
0
 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))
Ejemplo n.º 14
0
    def before_resource(self, req, resp, resource, params):

        # RequestHeader check
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.')
        
        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.')
        
        if req.content_length in (None, 0):
            # Nothing to do
            return

        # convert to json
        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body')
        
        try:
            req.context['data'] = json.loads(body.decode('utf-8'))

        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON')
Ejemplo n.º 15
0
 def test_http_unsupported_media_type_no_title_and_desc_and_challenges(
         self):
     try:
         raise falcon.HTTPUnsupportedMediaType()
     except falcon.HTTPUnsupportedMediaType as e:
         self.assertEqual(None, e.description,
                          'The description should be None')
Ejemplo n.º 16
0
    def process_request(self, req, resp):
        """Performs content type enforcement on behalf of REST verbs."""
        valid_content_types = ['application/x-yaml']

        # GET and DELETE should never carry a message body, and have
        # no content type. Check for content-length or
        # transfer-encoding to determine if a content-type header
        # is required.
        requires_content_type = (req.method not in ['GET', 'DELETE'] and (
            (req.content_length is not None and req.content_length > 0)
            or req.get_header('transfer-encoding') is not None))

        if requires_content_type:
            content_type = (req.content_type.split(';', 1)[0].strip()
                            if req.content_type else '')

            if not content_type:
                raise falcon.HTTPMissingHeader('Content-Type')
            elif content_type not in valid_content_types:
                message = (
                    "Unexpected content type: {type}. Expected content types "
                    "are: {expected}.").format(type=six.b(
                        req.content_type).decode('utf-8'),
                                               expected=valid_content_types)
                raise falcon.HTTPUnsupportedMediaType(description=message)
Ejemplo n.º 17
0
    def lookup_handler(self, media_type, default_media_type=None):
        """Lookup media handler by media type.

        Args:
            media_type (str): A media type of the registered media handler
            default_media_type (str): The default media type to use when
                `media_type` is not specified

        Returns:
            BaseMediaHandler: A media handler.

        Raises:
            falcon.HTTPUnsupportedMediaType: If `content_type` is not supported

        """
        if media_type == '*/*' or not media_type:
            media_type = default_media_type or self.media_type
        handler = self.handlers.get(media_type, None)
        if handler is None:
            try:
                resolved = mimeparse.best_match(self.handlers, media_type)
                assert not resolved
                handler = self.handlers[resolved]
            except (AssertionError, KeyError, ValueError):
                allowed = ', '.join("'{}'".format(media_type)
                                    for media_type in self.allowed_media_types)
                raise falcon.HTTPUnsupportedMediaType(
                    description="'{}' is an unsupported media type, supported "
                    "media types: {}".format(media_type, allowed))
            else:
                self.handlers[media_type] = handler
        return handler
Ejemplo n.º 18
0
    def on_post(self, req, resp, service):
        try:
            svc = self.service_instances[service]
        except KeyError:
            self.log.error("Unknown service '%s'", service)
            raise falcon.HTTPNotFound()

        if req.content_type and "application/json" not in req.content_type:
            self.log.error("Unsupported request content type '%s'", req.content_type)
            raise falcon.HTTPUnsupportedMediaType()

        try:
            body = req.bounded_stream.read()
            headers = req.headers
            svc_req = Request.from_http(body, headers)
        except Exception as exc:
            self.log.error(
                "Bad request (body: %s, headers: %s): %s", body, headers, exc
            )
            exc = errors.BadRequest(str(exc))
            resp.status = exc.http_response_code
            resp.data = json.dumps(exc.as_dict()).encode("utf-8")
            self.log.debug("Response body: %s", resp.data)
        else:
            svc_resp = svc._execute(svc_req)
            resp.status = svc_resp.http_status
            resp.data = svc_resp.http_body
            for k, v in svc_resp.http_headers.items():
                resp.append_header(k, v)
Ejemplo n.º 19
0
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)
Ejemplo n.º 20
0
 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).encode("ascii"))
         # Convert PEM to DER
         logger.debug(u"Serving revocation list (DER) to %s",
                      req.context.get("remote_addr"))
         resp.body = export_crl(pem=False)
     elif req.client_accepts("application/x-pem-file"):
         if req.get_param_as_bool("wait"):
             url = config.LONG_POLL_SUBSCRIBE % "crl"
             resp.status = falcon.HTTP_SEE_OTHER
             resp.set_header("Location", url.encode("ascii"))
             logger.debug(u"Redirecting to CRL request to %s", url)
             resp.body = "Redirecting to %s" % url
         else:
             resp.set_header("Content-Type", "application/x-pem-file")
             resp.append_header("Content-Disposition",
                                ("attachment; filename=%s-crl.pem" %
                                 const.HOSTNAME).encode("ascii"))
             logger.debug(u"Serving revocation list (PEM) to %s",
                          req.context.get("remote_addr"))
             resp.body = export_crl()
     else:
         logger.debug(
             u"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"
         )
Ejemplo n.º 21
0
 def test_http_unsupported_media_type_with_title_and_desc_and_challenges(
         self):
     try:
         raise falcon.HTTPUnsupportedMediaType(
             description='Testdescription')
     except falcon.HTTPUnsupportedMediaType as e:
         self.assertEqual('Testdescription', e.description,
                          'Description should be "Testdescription"')
 def on_get(self, req, resp,type,id):
     if type not in ('study','viewer'):
          raise falcon.HTTPNotFound()
     file = '%s/%s.hdf5' % (self.viewer_path if type == 'viewer' else self.study_path,id)
     format = req.params.get('format','png')
     if format not in ('png','pdf'):
         raise falcon.HTTPUnsupportedMediaType('Only png and pdf formats are supported')
     _qq_plot(file,resp,req)
Ejemplo n.º 23
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable('Require Json')

        if req.method in ('POST', 'PUT'):
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'Invalid Content-Type(Require Json)')
Ejemplo n.º 24
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                description='JSON is the only supported response format')

        if req.method in ('POST', 'PUT'):
            if req.content_type and 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    description='JSON is the only supported request format')
Ejemplo n.º 25
0
def require_json(req, resp, resource, params):
    if not req.client_accepts_json:
        raise falcon.HTTPNotAcceptable(
            'This API only supports responses encoded as JSON.')

    if req.method in ('POST', 'PUT'):
        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')
Ejemplo n.º 26
0
    def process_request(self, req, resp):
        if not req.client_accepts('application/python-pickle'):
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as pickle.')

        if req.method in ('POST', 'PUT'):
            if 'application/python-pickle' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as pickle.')
Ejemplo n.º 27
0
    def process_request(self, req, resp):
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports JSON-encoded responses')

        if req.method in ['POST']:
            if 'application/json' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports JSON-encoded requests')
Ejemplo n.º 28
0
def RequireJson(**request_handler_args):
    req = request_handler_args['req']
    if not req.client_accepts_json:
        raise falcon.HTTPNotAcceptable(
            'This API only supports responses encoded as JSON.')
    if req.method in ('POST', 'PUT', 'GET'):
        if 'application/json' not in req.content_type:
            raise falcon.HTTPUnsupportedMediaType(
                'This API only supports requests encoded as JSON.')
Ejemplo n.º 29
0
 def process_resource(self, req: falcon.Request, _resp: falcon.Response,
                      resource, _params):
     if req.method in HTTP_WRITE_METHODS:
         content_type = getattr(resource, 'content_type',
                                'application/x-www-form-urlencoded')
         if content_type and content_type not in req.content_type:
             raise falcon.HTTPUnsupportedMediaType(
                 description="This API only supports requests encoded as '"
                 + content_type + "'")
Ejemplo n.º 30
0
 def process_resource(self, req, resp, resource, params):
     if _get_response_schema(resource, req) and not req.client_accepts_json:
         raise falcon.HTTPNotAcceptable(
             'This API supports only JSON-encoded responses')
     if req.method in ('POST', 'PUT', 'PATCH'):
         if _get_request_schema(req, resource) is not None:
             if req.content_type is None or 'application/json' not in req.content_type:
                 raise falcon.HTTPUnsupportedMediaType(
                     'This API supports only JSON-encoded requests')