Exemplo n.º 1
0
    def process_response(self, req: Request, resp: Response,
                         resource: BaseController, _: bool) -> None:

        # check if the controller allow logging
        if resource is not None and resource.bypass_logger_middleware:
            return

        _res_size = 1
        if resp is not None and resp.body is not None:
            _res_size = len(resp.body)

        log = {
            'app':
            'pubsub',
            'date':
            str(datetime.now()),
            'reqId':
            resp.get_header(REQUEST_ID),
            'resCode':
            int(resp.status[:3]),
            'resTime':
            math.ceil((time.time() - float(resp.get_header('timer'))) * 1000),
            'resSize':
            _res_size,
            'method':
            req.method,
            'route':
            req.relative_uri,
            'details': {}
        }

        # if there is an error, add the message to the log
        if self._is_info_response(resp):
            try:
                body = json.loads(resp.body)
                body['payload'] = req.json
            except (TypeError, AttributeError, JSONDecodeError):
                body = {}

            log['details'] = body

            log['level'] = 'error'
            LoggerUtils.error(json.dumps(log))
        else:
            # generate stdout
            log['level'] = 'info'
            log['details'] = req.json
            LoggerUtils.info(json.dumps(log))
Exemplo n.º 2
0
 def test_on_head(self):
     """
     need to check if status of the response is set for 200 and
     """
     env = create_environ(path='/')
     req = Request(env)
     req.context = {'doc': {}}
     req.params[mongoengine.CollectionResource.PARAM_TOTAL_COUNT] = '1'
     resp = Response()
     resource = mongoengine.CollectionResource(
         objects_class=Mock(return_value=[1, 2, 3]), max_limit=2)
     resource.get_object_list = Mock(return_value=[1, 2])
     resource.get_total_objects = Mock(return_value={'total_count': 3})
     resource.on_head(req=req, resp=resp)
     self.assertIsNot(resp.body, [1, 2, 3])
     self.assertEqual(resp.get_header('x-api-total'), '3')
     self.assertEqual(resp.get_header('x-api-returned'), '2')
Exemplo n.º 3
0
    def process_response(
        self,
        req: falcon.Request,
        resp: falcon.Response,
        resource: object,
        req_succeeded: bool,
    ):
        """ Intercepts outgoing responses and handles incoming CORS OPTIONS
            preflight requests.

        Args:
            req (falcon.Request): The Falcon `Request` object.
            resp (falcon.Response): The Falcon `Response` object.
            resource (object): Resource object to which the request was routed.
                May be None if no route was found for the request.
            req_succeeded (bool): True if no exceptions were raised while the
                framework processed and routed the request; otherwise False.
        """

        # Set the `Access-Control-Allow-Origin` header.
        resp.set_header('Access-Control-Allow-Origin', '*')

        # Skip the request if it doesn't exhibit the characteristics of a CORS
        # OPTIONS preflight request.
        if not self.is_req_cors(req=req):
            return None

        msg_fmt = "Processing CORS preflight OPTIONS request."
        self.logger.info(msg_fmt)

        # Retrieve and remove the `Allow` header from the response.
        allow = resp.get_header('Allow')
        resp.delete_header('Allow')

        # Retrieve the `Access-Control-Request-Headers` header from the
        # request.
        allow_headers = req.get_header('Access-Control-Request-Headers',
                                       default='*')

        # Set the appropriate CORS headers in the response.
        resp.set_header(name="Access-Control-Allow-Methods", value=allow)
        resp.set_header(
            name="Access-Control-Allow-Headers",
            value=allow_headers,
        )
        resp.set_header(name="Access-Control-Max-Age", value='86400')
Exemplo n.º 4
0
 def test_on_options(self):
     """
     need to check if status of the response is set for 200 and
     """
     env = create_environ(path='/')
     req = Request(env)
     req.context = {'doc': {}}
     resp = Response()
     resource = mongoengine.CollectionResource(objects_class=FakeObjectList,
                                               max_limit=2)
     resource.on_options(req=req, resp=resp)
     self.assertEqual(resp.get_header('Allow'),
                      'GET, HEAD, OPTIONS, POST, PUT')
     self.assertEqual(
         resp.body, {
             'name': 'FakeObjectList',
             'description':
             'Extend list to match interface of List resource',
         })
Exemplo n.º 5
0
    def on_post(self, req: Request, resp: Response) -> Response:

        service = MessageService()

        try:
            service.validate(req)
            msg_guid = service.publish(req)

            # process request and build response
            response = {
                'status': HTTP_202,
                'data': {
                    'msg_guid': msg_guid,
                    'reqId': resp.get_header(REQUEST_ID)
                }
            }

            resp.body = json.dumps(response)
            resp.status = HTTP_202
        except PubSubBaseException as e:
            self.manage_application_exception(e, resp)
        except HTTPUnprocessableEntity as e:
            raise e