File: responses.py

package info (click to toggle)
python-openapi-core 0.22.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,104 kB
  • sloc: python: 19,979; makefile: 44
file content (41 lines) | stat: -rw-r--r-- 1,286 bytes parent folder | download | duplicates (2)
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
38
39
40
41
"""OpenAPI core contrib starlette responses module"""

from typing import Optional

from starlette.datastructures import Headers
from starlette.responses import Response
from starlette.responses import StreamingResponse


class StarletteOpenAPIResponse:
    def __init__(self, response: Response, data: Optional[bytes] = None):
        if not isinstance(response, Response):
            raise TypeError(f"'response' argument is not type of {Response}")
        self.response = response

        if data is None and isinstance(response, StreamingResponse):
            raise RuntimeError(
                f"'data' argument is required for {StreamingResponse}"
            )
        self._data = data

    @property
    def data(self) -> bytes:
        if self._data is not None:
            return self._data
        if isinstance(self.response.body, bytes):
            return self.response.body
        assert isinstance(self.response.body, str)
        return self.response.body.encode("utf-8")

    @property
    def status_code(self) -> int:
        return self.response.status_code

    @property
    def content_type(self) -> str:
        return self.response.headers.get("Content-Type") or ""

    @property
    def headers(self) -> Headers:
        return self.response.headers