@@ -32,17 +32,32 @@ class HTTPResponse:
32
32
# Response with 'Content-Length' header
33
33
@server.route(path, method)
34
34
def route_func(request):
35
+
35
36
response = HTTPResponse(request)
36
37
response.send("Some content", content_type="text/plain")
37
- # or
38
- @server.route(path, method)
39
- def route_func(request):
38
+
39
+ # or
40
+
41
+ response = HTTPResponse(request)
42
+ with response:
43
+ response.send(body='Some content', content_type="text/plain")
44
+
45
+ # or
46
+
40
47
with HTTPResponse(request) as response:
41
48
response.send("Some content", content_type="text/plain")
42
49
43
50
# Response with 'Transfer-Encoding: chunked' header
44
51
@server.route(path, method)
45
52
def route_func(request):
53
+
54
+ response = HTTPResponse(request, content_type="text/plain", chunked=True)
55
+ with response:
56
+ response.send_body_chunk("Some content")
57
+ response.send_body_chunk("Some more content")
58
+
59
+ # or
60
+
46
61
with HTTPResponse(request, content_type="text/plain", chunked=True) as response:
47
62
response.send_body_chunk("Some content")
48
63
response.send_body_chunk("Some more content")
@@ -68,7 +83,8 @@ def __init__( # pylint: disable=too-many-arguments
68
83
"""
69
84
Creates an HTTP response.
70
85
71
- Sets `status`, ``headers`` and `http_version`.
86
+ Sets `status`, ``headers`` and `http_version`
87
+ and optionally default ``content_type``.
72
88
73
89
To send the response, call `send` or `send_file`.
74
90
For chunked response use
@@ -122,7 +138,8 @@ def send(
122
138
"""
123
139
Sends response with `body` over the given socket.
124
140
Implicitly calls ``_send_headers`` before sending the body.
125
- Should be called only once per response.
141
+
142
+ Should be called **only once** per response.
126
143
"""
127
144
encoded_response_message_body = body .encode ("utf-8" )
128
145
@@ -139,6 +156,9 @@ def send_file(
139
156
) -> None :
140
157
"""
141
158
Send response with content of ``filename`` located in ``root_path`` over the given socket.
159
+ Implicitly calls ``_send_headers`` before sending the file content.
160
+
161
+ Should be called **only once** per response.
142
162
"""
143
163
if not root_path .endswith ("/" ):
144
164
root_path += "/"
@@ -162,7 +182,7 @@ def send_chunk_body(self, chunk: str = "") -> None:
162
182
"""
163
183
Send chunk of data to the given socket.
164
184
165
- Should be used only inside
185
+ Should be used ** only** inside
166
186
``with HTTPResponse(request, chunked=True) as response:`` context manager.
167
187
168
188
:param str chunk: String data to be sent.
0 commit comments