| 1 | class Response: |
| 2 | charset = "utf-8" |
| 3 | |
| 4 | def __init__(self, content, status_code=200, headers=None, media_type=None): |
| 5 | self.body = self.render(content) |
| 6 | self.status_code = status_code |
| 7 | self.headers = headers or {} |
| 8 | self.media_type = media_type |
| 9 | self.set_content_type() |
| 10 | self.set_content_length() |
| 11 | |
| 12 | async def __call__(self, scope, receive, send) -> None: |
| 13 | prefix = "websocket." if scope["type"] == "websocket" else "" |
| 14 | await send( |
| 15 | { |
| 16 | "type": prefix + "http.response.start", |
| 17 | "status": self.status_code, |
| 18 | "headers": [[key.encode(), value.encode()] for key, value in self.headers.items()], |
| 19 | } |
| 20 | ) |
| 21 | await send({"type": prefix + "http.response.body", "body": self.body}) |
| 22 | |
| 23 | def render(self, content) -> bytes: |
| 24 | if isinstance(content, bytes): |
| 25 | return content |
| 26 | return content.encode(self.charset) |
| 27 | |
| 28 | def set_content_length(self): |
| 29 | if "content-length" not in self.headers: |
| 30 | self.headers["content-length"] = str(len(self.body)) |
| 31 | |
| 32 | def set_content_type(self): |
| 33 | if self.media_type is not None and "content-type" not in self.headers: |
| 34 | content_type = self.media_type |
| 35 | if content_type.startswith("text/") and self.charset is not None: |
| 36 | content_type += "; charset=%s" % self.charset |
| 37 | self.headers["content-type"] = content_type |
no outgoing calls