File: response.py

package info (click to toggle)
flask-api 0.6.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 316 kB
  • ctags: 329
  • sloc: python: 1,284; sh: 21; makefile: 10
file content (37 lines) | stat: -rw-r--r-- 1,302 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# coding: utf8
from __future__ import unicode_literals
from flask import request, Response
from flask._compat import text_type, string_types


class APIResponse(Response):
    def __init__(self, content=None, *args, **kwargs):
        super(APIResponse, self).__init__(None, *args, **kwargs)

        media_type = None
        if isinstance(content, (list, dict, text_type, string_types)):
            renderer = request.accepted_renderer
            if content != '' or renderer.handles_empty_responses:
                media_type = request.accepted_media_type
                options = self.get_renderer_options()
                content = renderer.render(content, media_type, **options)
                if self.status_code == 204:
                    self.status_code = 200

        # From `werkzeug.wrappers.BaseResponse`
        if content is None:
            content = []
        if isinstance(content, (text_type, bytes, bytearray)):
            self.set_data(content)
        else:
            self.response = content

        if media_type is not None:
            self.headers['Content-Type'] = str(media_type)

    def get_renderer_options(self):
        return {
            'status': self.status,
            'status_code': self.status_code,
            'headers': self.headers
        }