MCPcopy
hub / github.com/encode/starlette / Response

Class Response

starlette/responses.py:29–170  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

27
28
29class Response:
30 media_type = None
31 charset = "utf-8"
32
33 def __init__(
34 self,
35 content: Any = None,
36 status_code: int = 200,
37 headers: Mapping[str, str] | None = None,
38 media_type: str | None = None,
39 background: BackgroundTask | None = None,
40 ) -> None:
41 self.status_code = status_code
42 if media_type is not None:
43 self.media_type = media_type
44 self.background = background
45 self.body = self.render(content)
46 self.init_headers(headers)
47
48 def render(self, content: Any) -> bytes | memoryview:
49 if content is None:
50 return b""
51 if isinstance(content, bytes | memoryview):
52 return content
53 return content.encode(self.charset) # type: ignore
54
55 def init_headers(self, headers: Mapping[str, str] | None = None) -> None:
56 if headers is None:
57 raw_headers: list[tuple[bytes, bytes]] = []
58 populate_content_length = True
59 populate_content_type = True
60 else:
61 raw_headers = [(k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items()]
62 keys = [h[0] for h in raw_headers]
63 populate_content_length = b"content-length" not in keys
64 populate_content_type = b"content-type" not in keys
65
66 body = getattr(self, "body", None)
67 if (
68 body is not None
69 and populate_content_length
70 and not (self.status_code < 200 or self.status_code in (204, 304))
71 ):
72 content_length = str(len(body))
73 raw_headers.append((b"content-length", content_length.encode("latin-1")))
74
75 content_type = self.media_type
76 if content_type is not None and populate_content_type:
77 if content_type.startswith("text/") and "charset=" not in content_type.lower():
78 content_type += "; charset=" + self.charset
79 raw_headers.append((b"content-type", content_type.encode("latin-1")))
80
81 self.raw_headers = raw_headers
82
83 @property
84 def headers(self) -> MutableHeaders:
85 if not hasattr(self, "_headers"):
86 self._headers = MutableHeaders(raw=self.raw_headers)

Callers 15

http_exceptionMethod · 0.90
appFunction · 0.90
appFunction · 0.90
test_response_phraseFunction · 0.90
test_populate_headersFunction · 0.90
test_head_methodFunction · 0.90
test_empty_responseFunction · 0.90
test_empty_204_responseFunction · 0.90
test_non_empty_responseFunction · 0.90
test_response_memoryviewFunction · 0.90
endpointFunction · 0.90

Calls

no outgoing calls

Tested by 15

appFunction · 0.72
appFunction · 0.72
test_response_phraseFunction · 0.72
test_populate_headersFunction · 0.72
test_head_methodFunction · 0.72
test_empty_responseFunction · 0.72
test_empty_204_responseFunction · 0.72
test_non_empty_responseFunction · 0.72
test_response_memoryviewFunction · 0.72
endpointFunction · 0.72
appFunction · 0.72