Python flask.wrappers.Response() Examples

The following are 8 code examples of flask.wrappers.Response(). 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 flask.wrappers , or try the search function .
Example #1
Source File: __init__.py    From Flask-Large-Application-Example with MIT License 5 votes vote down vote up
def request(self) -> Response:
        return self.client.open(
            method=self.method,
            path=self.path.format(**self.path_parameters),
            json=self.json,
            query_string=self.query_string,
        ) 
Example #2
Source File: base_view.py    From Penny-Dreadful-Tools with GNU General Public License v3.0 5 votes vote down vote up
def response(self) -> wrappers.Response:
        return make_response(self.page()) 
Example #3
Source File: core.py    From flask-boilerplate with MIT License 5 votes vote down vote up
def all_exception_handler(error: Exception) -> Tuple[Response, int]:
    """Catches and handles all exceptions, add more specific error Handlers.
    :param Exception
    :returns Tuple of a Flask Response and int
    """
    return create_response(message=str(error), status=500) 
Example #4
Source File: conftest.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def response_factory():
    def create_response(
            data, status_code=200, content_type='application/json'):
        return Response(data, status=status_code, content_type=content_type)
    return create_response 
Example #5
Source File: controller.py    From flaskerize with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete(self, widgetId: int) -> Response:
        """Delete Single Widget"""
        from flask import jsonify

        id = WidgetService.delete_by_id(widgetId)
        return jsonify(dict(status="Success", id=id)) 
Example #6
Source File: resource.py    From flask-rest-jsonapi with MIT License 4 votes vote down vote up
def dispatch_request(self, *args, **kwargs):
        """Logic of how to handle a request"""
        method = getattr(self, request.method.lower(), None)
        if method is None and request.method == 'HEAD':
            method = getattr(self, 'get', None)
        assert method is not None, 'Unimplemented method {}'.format(request.method)

        headers = {'Content-Type': 'application/vnd.api+json'}

        response = method(*args, **kwargs)

        if isinstance(response, Response):
            response.headers.add('Content-Type', 'application/vnd.api+json')
            return response

        if not isinstance(response, tuple):
            if isinstance(response, dict):
                response.update({'jsonapi': {'version': '1.0'}})
            return make_response(json.dumps(response, cls=JSONEncoder), 200, headers)

        try:
            data, status_code, headers = response
            headers.update({'Content-Type': 'application/vnd.api+json'})
        except ValueError:
            pass

        try:
            data, status_code = response
        except ValueError:
            pass

        if isinstance(data, dict):
            data.update({'jsonapi': {'version': '1.0'}})

        if isinstance(data, FlaskResponse):
            data.headers.add('Content-Type', 'application/vnd.api+json')
            data.status_code = status_code
            return data
        elif isinstance(data, str):
            json_reponse = data
        else:
            json_reponse = json.dumps(data, cls=JSONEncoder)

        return make_response(json_reponse, status_code, headers) 
Example #7
Source File: utils.py    From amivapi with GNU Affero General Public License v3.0 4 votes vote down vote up
def open(self, *args, **kwargs):
        """Modified request.

        Adds token and headers and asserts status code.
        """
        # We are definetly going to add some headers
        if 'headers' not in kwargs:
            kwargs['headers'] = {}

        # Add token
        token = kwargs.pop('token', None)

        if token:
            kwargs['headers'].update({
                # We support a auth header of the form "Token <thetoken>"
                'Authorization': 'Token ' + token
            })

        # Add content-type: json header if nothing else is provided
        if (not("content-type" in kwargs['headers']) and
                ("data" in kwargs)):
            # Parse data
            kwargs['data'] = json.dumps(kwargs['data'])
            # Set header
            kwargs['content_type'] = "application/json"

        # get the actual response and assert status
        expected_code = kwargs.pop('status_code', None)

        response = super().open(*args, **kwargs)

        status_code = response.status_code

        if (expected_code is not None and expected_code != status_code):
            raise AssertionError(
                "Expected a status code of %i, but got %i instead\n"
                "Response:\n%s\n%s\n%s" % (expected_code, status_code,
                                           response, response.data,
                                           response.status))
        elif ((expected_code == 422) and
              ('exception' in response.json.get('_issues', {}))):
            # The validator swallows exceptions and turns them into 'exception'
            # validation errors. Ensure that tests do not miss this by raising
            # them properly.
            error = response.json['_issues']['exception']
            raise AssertionError("Expected a validation error but the "
                                 "validator raised an exception: %s" % error)

        return response 
Example #8
Source File: __init__.py    From frest with MIT License 4 votes vote down vote up
def API(method=None):
    if method is None:
        return partial(API)

    @wraps(method)
    def decorated(*args, **kwargs):
        _return = method(*args, **kwargs)

        if isinstance(_return, Response):
            return _return

        if request.url.find('v' + str(API_VERSION)) > 0:
            try:
                if request.headers['Accept'] == API_ACCEPT_HEADER:
                    ret, code = _return
                else:
                    raise KeyError
            except KeyError:
                ret, code = ("Please check request accept again.", status.HTTP_406_NOT_ACCEPTABLE)
        else:
            ret, code = ("API has been updated. The latest version is v" + str(API_VERSION), status.HTTP_301_MOVED_PERMANENTLY)

        return serialize(ret, code)

    def serialize(ret, code):
        _return = {'code': code}

        if not status.is_success(code):
            _return['status'] = 'fail'

            if ret is not None:
                if isinstance(ret, dict):
                    _return.update(ret)
                else:
                    _return['message'] = ret
        else:
            _return['status'] = 'success'

            if ret is not None:
                if isinstance(ret, dict):
                    _return.update(ret)
                else:
                    _return['data'] = ret

        return _return, code

    return decorated