def response_builder(response):
    """
    Marshals & transforms `Response` object to the response format supported by Flask-Restful, and return it.

    :param response: instance of `Response` class as returned by controller's action method.

    :return: `response data`, `status code`, `response headers`
    """
    # Actual response structure in the form of JSON.
    marshal_fields = {
        "success": fields.Boolean,
        "message": fields.String,
        "data": fields.Raw,
        "errors": fields.Raw
    }

    if response.data and not isinstance(
            response.data, (list, set, dict, str, tuple, int, float, bool)):
        return FlaskResponse(response.data, mimetype=response.mimetype)

    marshaled_res = marshal(response, marshal_fields)
    headers = dict(response.headers) if response.headers else None
    return marshaled_res, response.status_code, headers
    def test_it_recreates_a_get_response_for_multiple_apps(self, fixture):
        modified_app = deepcopy(fixture)
        modified_app['id'] = '/xablau'

        fixtures = [fixture, modified_app]
        expected_response = deepcopy(fixtures)
        with application.test_request_context('/v2/apps/',
                                              method='GET', data=b'') as ctx:
            response = FlaskResponse(response=json.dumps({"apps": fixtures}),
                                     status=HTTPStatus.OK,
                                     headers={})
            response = Response(ctx.request, response)

        with patch.object(response, 'marathon_client') as client:
            original_apps = [AsgardApp.from_json(app) for app in fixtures]
            client.get_app.side_effect = original_apps
            apps = list(response.split())

            joined_response = response.join(apps)

            self.assertIsInstance(joined_response, FlaskResponse)
            self.assertDictEqual(json.loads(joined_response.data),
                                 {'apps': expected_response})
Exemple #3
0
    def response(
        content: Any = None,
        code: Optional[int] = None,
        headers: Optional[Dict[str, str]] = None,
        head_method: bool = False,
        allow_html: bool = False,
    ) -> Response:

        if headers is None:
            headers = {}

        if code is None:
            code = 200

        if content is None and code != 204 and not head_method:
            log.warning("RESPONSE: Warning, no data and no errors")
            code = 204

        # Do not bypass FlaskApiSpec response management otherwise marshalling
        # will be not applied. Consider the following scenario:
        # @marshal(OnlyOneFieldSchema)
        # def get():
        #    return self.response(all_information)
        # If you bypass the marshalling you will expose the all_information by
        # retrieving it from a browser (or by forcing the Accept header)
        # If you accept the risk or you do not use marshalling unlock html responses
        # by the adding `allow_html=True` flag
        if allow_html:
            if "text/html" in ResponseMaker.get_accepted_formats():
                content, headers = ResponseMaker.get_html(
                    content, code, headers)
                return FlaskResponse(content,
                                     mimetype="text/html",
                                     status=code,
                                     headers=headers)

        return (content, code, headers)
    def test_remove_from_response_apps_outside_same_prefix_namespace(self):
        """
        Uma app com namespace `/developers/` deve ser removida quando o usuário faz
        parte do namespace ´/dev/`, mesmo os namespaces começando pelo mesmo prefixo
        """
        with application.test_request_context("/v2/apps/", method="GET") as ctx:
            single_full_app_one = deepcopy(self.single_full_app_fixture)
            single_full_app_one['id'] = '/dev/foo'

            single_full_app_two = deepcopy(self.single_full_app_fixture)
            single_full_app_two['id'] = '/dev/other-app'

            single_full_app_three = deepcopy(self.single_full_app_fixture)
            single_full_app_three['id'] = '/developers/other-app'

            with RequestsMock() as rsps:
                rsps.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/apps//dev/foo',
                         body=json.dumps({'app': single_full_app_one}), status=200)
                rsps.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/apps//dev/other-app',
                         body=json.dumps({'app': single_full_app_two}), status=200)
                rsps.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/apps//developers/other-app',
                         body=json.dumps({'app': single_full_app_three}), status=200)

                original_response = FlaskResponse(response=json.dumps({'apps': [single_full_app_one, single_full_app_two, single_full_app_three]}),
                                                  status=200, headers={})

                ctx.request.user = self.user
                response_wrapper = Response(ctx.request, original_response)
                final_response = dispatch(user=self.user,
                                          request=response_wrapper,
                                          filters_pipeline=FILTERS_PIPELINE[FilterType.RESPONSE],
                                          filter_method_name_callback=lambda *args: "response"
                                 )
                response_data = json.loads(final_response.data)
                self.assertEqual(200, final_response.status_code)
                self.assertEqual(2, len(response_data['apps']))
                self.assertEqual(["/foo", "/other-app"], [app['id'] for app in response_data['apps']])
Exemple #5
0
    def test_response_apps_remove_outside_current_namespace(self):
        with application.test_request_context("/v2/apps/",
                                              method="GET") as ctx:
            single_full_app_one = deepcopy(self.single_full_app_fixture)
            single_full_app_one["id"] = "/dev/foo"

            single_full_app_two = deepcopy(self.single_full_app_fixture)
            single_full_app_two["id"] = "/dev/other-app"

            single_full_app_three = deepcopy(self.single_full_app_fixture)
            single_full_app_three["id"] = "/othernamespace/other-app"

            original_response = FlaskResponse(
                response=json.dumps({
                    "apps": [
                        single_full_app_one,
                        single_full_app_two,
                        single_full_app_three,
                    ]
                }),
                status=200,
                headers={},
            )

            ctx.request.user = self.user
            response_wrapper = Response(ctx.request, original_response)
            final_response = dispatch(
                user=self.user,
                request=response_wrapper,
                filters_pipeline=FILTERS_PIPELINE[FilterType.RESPONSE],
                filter_method_name_callback=lambda *args: "response",
            )
            response_data = json.loads(final_response.data)
            self.assertEqual(200, final_response.status_code)
            self.assertEqual(2, len(response_data["apps"]))
            self.assertEqual("/foo", response_data["apps"][0]["id"])
            self.assertEqual("/other-app", response_data["apps"][1]["id"])
Exemple #6
0
    def test_do_not_call_filter_if_it_doesnt_implement_response_method(self):
        class DummyRequestFilter:
            def write(self, user, request_app):
                return request_app

        with application.test_request_context("/v2/apps/foo",
                                              method="GET") as ctx:
            single_full_app_one = deepcopy(self.single_full_app_fixture)
            single_full_app_one["id"] = "/dev/foo"

            with RequestsMock() as rsps:
                rsps.add(
                    method="GET",
                    url=conf.MARATHON_ADDRESSES[0] + "/v2/apps//foo",
                    json={"app": single_full_app_one},
                    status=200,
                )

                original_response = FlaskResponse(
                    response=json.dumps({"app": single_full_app_one}),
                    status=200,
                    headers={},
                )

                ctx.request.user = self.user
                response_wrapper = Response(ctx.request, original_response)
                final_response = dispatch(
                    user=self.user,
                    request=response_wrapper,
                    filters_pipeline={
                        OperationType.READ: [DummyRequestFilter()]
                    },
                    filter_method_name_callback=lambda *args: "response",
                )
                response_data = json.loads(final_response.data)
                self.assertEqual(200, final_response.status_code)
                self.assertEqual("/dev/foo", response_data["app"]["id"])
Exemple #7
0
    def test_join_groups(self, group_dev_namespace_fixture):
        with application.test_request_context("/v2/groups/",
                                              method="GET") as ctx:
            response = FlaskResponse(
                response=json.dumps(group_dev_namespace_fixture),
                status=HTTPStatus.OK,
                headers={},
            )

            ctx.request.user = self.user
            response = Response(ctx.request, response)
            groups_tuple = list(response.split())
            joined_response = response.join(groups_tuple)

            joined_response_data = json.loads(joined_response.data)
            self.assertEqual("/dev", joined_response_data["id"])
            self.assertEqual("/dev/group-b",
                             joined_response_data["groups"][0]["id"])
            self.assertEqual([], joined_response_data["dependencies"]
                             )  # Groups should be reendered in full
            self.assertEqual(1, len(joined_response_data["groups"][0]["apps"]))
            self.assertEqual(
                [], joined_response_data["groups"][0]["apps"][0]
                ["constraints"])  # Apps should also be renderen in full
    def test_join_groups(self, group_dev_namespace_fixture):
        with application.test_request_context('/v2/groups/', method='GET') as ctx:
            response = FlaskResponse(
                response=json.dumps(group_dev_namespace_fixture),
                status=HTTPStatus.OK,
                headers={}
            )
            with RequestsMock() as rsps:
                rsps.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/groups//dev/',
                         body=json.dumps(deepcopy(group_dev_namespace_fixture)), status=200)
                rsps.add(method='GET', url=conf.MARATHON_ADDRESSES[0] + '/v2/groups//dev/group-b',
                         body=json.dumps(deepcopy(group_dev_namespace_fixture['groups'][0])), status=200)

                ctx.request.user = self.user
                response = Response(ctx.request, response)
                groups_tuple = list(response.split())
                joined_response = response.join(groups_tuple)

                joined_response_data = json.loads(joined_response.data)
                self.assertEqual("/dev", joined_response_data['id'])
                self.assertEqual("/dev/group-b", joined_response_data['groups'][0]['id'])
                self.assertEqual([], joined_response_data['dependencies']) # Groups should be reendered in full
                self.assertEqual(1, len(joined_response_data['groups'][0]['apps']))
                self.assertEqual([], joined_response_data['groups'][0]['apps'][0]['constraints']) # Apps should also be renderen in full
Exemple #9
0
 def flask(self,
           in_headers=False,
           headers=None,
           **kwargs):
     """
     Return the values and error to be used in flask.
     So far, it returns a fixed context. We should store/generate different
     contexts if the plugin adds more aliases.
     """
     headers = headers or {}
     kwargs["with_context"] = True
     js = self.jsonld(**kwargs)
     if in_headers:
         url = js["@context"]
         del js["@context"]
         headers.update({
             "Link": ('<%s>;'
                      'rel="http://www.w3.org/ns/json-ld#context";'
                      ' type="application/ld+json"' % url)
         })
     return FlaskResponse(json.dumps(js, indent=2, sort_keys=True),
                          status=getattr(self, "status", 200),
                          headers=headers,
                          mimetype="application/json")
    def test_response_task_remove_from_response_tasks_outside_same_prefix_namespace(self, tasks_multinamespace_fixure):
        """
        Confirmamos que uma task do namespace "developers" *deve ser removida* quando o usuário faz parte
        do namespace "dev", mesmo esses dois namespaces começando pelo mesmo prefixo
        """
        with application.test_request_context("/v2/tasks/", method="GET") as ctx:

            original_response = FlaskResponse(response=json.dumps(tasks_multinamespace_fixure),
                                              status=200)

            ctx.request.user = self.user
            response_wrapper = Response(ctx.request, original_response)
            final_response = dispatch(user=self.user,
                                          request=response_wrapper,
                                          filters_pipeline=FILTERS_PIPELINE[FilterType.RESPONSE],
                                          filter_method_name_callback=lambda *args: "response_task"
                                 )
            response_data = json.loads(final_response.data)
            self.assertEqual(200, final_response.status_code)
            self.assertEqual([
                "waiting.01339ffa-ce9c-11e7-8144-2a27410e5638",
                "waiting.0432fd4b-ce9c-11e7-8144-2a27410e5638",
            ], [task['id'] for task in response_data['tasks']])
            self.assertEqual(2, len(response_data['tasks']))
Exemple #11
0
def robotstxt() -> FlaskResponse:
    blockall = 'User-Agent: *\nDisallow: /\n'
    r = FlaskResponse(response=blockall, status=200, mimetype='text/plain')
    r.headers['Content-Type'] = 'text/plain; charset=utf-8'
    return r
Exemple #12
0
def __wrap_in_response_instance(data, to_wrap):
    if isinstance(data, FlaskResponse):
        data.set_data(to_wrap)
        return data
    return FlaskResponse(to_wrap)
 def success(data, http_code=200):
     return FlaskResponse(JSONEncoder().encode({
         "data": data,
         "error": None
     }), status=http_code, mimetype='application/json')
def requests_to_flask_response(r):
    return FlaskResponse(r.content,
                         status=r.status_code,
                         headers=dict(r.headers))
Exemple #15
0
 def to_flask(self):
     headers = {'Content-Type': 'application/json'}
     flask_response = FlaskResponse(json.dumps(self.json_object()),
                                    self.status_code,
                                    headers=headers)
     return flask_response
def problem(type, status, title, detail=None, instance=None, headers={}):
    """Create a Response that includes a Problem Detail Document."""
    status, headers, data = problem_raw(type, status, title, detail, instance,
                                        headers)
    return FlaskResponse(data, status, headers)
Exemple #17
0
 def wrapper(*args, **kwargs):
     res = func(*args, **kwargs)
     return FlaskResponse(res.toxml(), mimetype='text/xml')
Exemple #18
0
def requests_response_to_flask_response(
        requests_response: RequestsResponse) -> FlaskResponse:
    requests_response.headers.pop('content-encoding', '')
    return FlaskResponse(response=requests_response.content,
                         status=requests_response.status_code,
                         headers=dict(requests_response.headers))
Exemple #19
0
def get_recorded_position():
    return FlaskResponse(myp.get_recorded_position(), mimetype='application/json')
Exemple #20
0
def dict_response_to_flask_response(dict_response: dict) -> FlaskResponse:
    return FlaskResponse(
        response=json.dumps(dict_response['body']),
        status=dict_response['status'],
        headers=dict_response['headers'],
    )
Exemple #21
0
def render_flask_response(response, function_name):
    body, status = render_response(response, function_name)
    return FlaskResponse(body, status=status, mimetype='application/json')