2024-07-12 02:30:25 +02:00
|
|
|
from collections.abc import Iterator, Mapping
|
|
|
|
from typing import Any
|
2020-06-11 00:54:34 +02:00
|
|
|
|
2020-08-07 01:09:47 +02:00
|
|
|
import orjson
|
2022-01-31 13:44:02 +01:00
|
|
|
from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed
|
2023-10-12 19:43:45 +02:00
|
|
|
from typing_extensions import override
|
2012-11-06 20:31:53 +01:00
|
|
|
|
2022-07-13 03:29:39 +02:00
|
|
|
from zerver.lib.exceptions import JsonableError, UnauthorizedError
|
2013-03-21 20:15:27 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-08-25 18:41:46 +02:00
|
|
|
class MutableJsonResponse(HttpResponse):
|
|
|
|
def __init__(
|
|
|
|
self,
|
2024-07-12 02:30:17 +02:00
|
|
|
data: dict[str, Any],
|
2022-08-25 18:41:46 +02:00
|
|
|
*,
|
|
|
|
content_type: str,
|
|
|
|
status: int,
|
|
|
|
) -> None:
|
|
|
|
# Mirror the behavior of Django's TemplateResponse and pass an
|
|
|
|
# empty string for the initial content value. Because that will
|
|
|
|
# set _needs_serialization to False, we initialize it to True
|
|
|
|
# after the call to super __init__.
|
|
|
|
super().__init__("", content_type=content_type, status=status)
|
|
|
|
self._data = data
|
|
|
|
self._needs_serialization = True
|
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def get_data(self) -> dict[str, Any]:
|
2022-08-25 18:41:46 +02:00
|
|
|
"""Get data for this MutableJsonResponse. Calling this method
|
|
|
|
after the response's content has already been serialized
|
|
|
|
will mean the next time the response's content is accessed
|
|
|
|
it will be reserialized because the caller may have mutated
|
|
|
|
the data."""
|
|
|
|
self._needs_serialization = True
|
|
|
|
return self._data
|
|
|
|
|
|
|
|
# This always returns bytes, but in Django's HttpResponse the return
|
|
|
|
# value can be bytes, an iterable of bytes or some other object. Any
|
|
|
|
# is used here to encompass all of those return values.
|
|
|
|
# See https://github.com/typeddjango/django-stubs/commit/799b41fe47cfe2e56be33eee8cfbaf89a9853a8e
|
|
|
|
# and https://github.com/python/mypy/issues/3004.
|
2023-10-12 19:43:45 +02:00
|
|
|
@override # type: ignore[explicit-override] # https://github.com/python/mypy/issues/15900
|
2022-08-25 18:41:46 +02:00
|
|
|
@property
|
|
|
|
def content(self) -> Any:
|
|
|
|
"""Get content for the response. If the content hasn't been
|
|
|
|
overridden by the property setter, it will be the response data
|
|
|
|
serialized lazily to JSON."""
|
|
|
|
if self._needs_serialization:
|
|
|
|
# Because we don't pass a default handler, OPT_PASSTHROUGH_DATETIME
|
|
|
|
# actually causes orjson to raise a TypeError on datetime objects. This
|
|
|
|
# helps us avoid relying on the particular serialization used by orjson.
|
|
|
|
self.content = orjson.dumps(
|
|
|
|
self._data,
|
|
|
|
option=orjson.OPT_APPEND_NEWLINE | orjson.OPT_PASSTHROUGH_DATETIME,
|
|
|
|
)
|
|
|
|
return super().content
|
|
|
|
|
|
|
|
# There are two ways this might be called. The first is in the getter when
|
|
|
|
# the response data is being serialized into JSON. The second is when it
|
|
|
|
# is called from some other part of the code. This happens for instance in
|
|
|
|
# the parent class constructor. In this case, the new content overrides the
|
|
|
|
# serialized JSON.
|
|
|
|
@content.setter
|
|
|
|
def content(self, value: Any) -> None:
|
|
|
|
"""Set the content for the response."""
|
|
|
|
assert isinstance(HttpResponse.content, property)
|
|
|
|
assert HttpResponse.content.fset is not None
|
|
|
|
HttpResponse.content.fset(self, value)
|
|
|
|
self._needs_serialization = False
|
|
|
|
|
|
|
|
# The superclass HttpResponse defines an iterator that doesn't access the content
|
|
|
|
# property, so in order to not break the implementation of the superclass with
|
|
|
|
# our lazy content generation, we override the iterator to access `self.content`
|
|
|
|
# through our getter.
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
2022-08-25 18:41:46 +02:00
|
|
|
def __iter__(self) -> Iterator[bytes]:
|
|
|
|
return iter([self.content])
|
|
|
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def json_unauthorized(
|
2024-07-12 02:30:23 +02:00
|
|
|
message: str | None = None, www_authenticate: str | None = None
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2022-07-13 03:29:39 +02:00
|
|
|
return json_response_from_error(
|
|
|
|
UnauthorizedError(msg=message, www_authenticate=www_authenticate)
|
2020-08-07 01:09:47 +02:00
|
|
|
)
|
2013-07-30 23:20:16 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2024-07-12 02:30:17 +02:00
|
|
|
def json_method_not_allowed(methods: list[str]) -> HttpResponseNotAllowed:
|
2013-03-21 20:15:27 +01:00
|
|
|
resp = HttpResponseNotAllowed(methods)
|
2021-02-12 08:19:30 +01:00
|
|
|
resp.content = orjson.dumps(
|
|
|
|
{"result": "error", "msg": "Method Not Allowed", "allowed_methods": methods}
|
|
|
|
)
|
2013-03-21 20:15:27 +01:00
|
|
|
return resp
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def json_response(
|
|
|
|
res_type: str = "success", msg: str = "", data: Mapping[str, Any] = {}, status: int = 200
|
2022-08-25 18:41:46 +02:00
|
|
|
) -> MutableJsonResponse:
|
2012-11-06 20:31:53 +01:00
|
|
|
content = {"result": res_type, "msg": msg}
|
2020-06-13 03:34:01 +02:00
|
|
|
content.update(data)
|
2020-08-07 01:09:47 +02:00
|
|
|
|
2022-08-25 18:41:46 +02:00
|
|
|
return MutableJsonResponse(
|
|
|
|
data=content,
|
2021-02-12 08:20:45 +01:00
|
|
|
content_type="application/json",
|
2020-08-07 01:09:47 +02:00
|
|
|
status=status,
|
|
|
|
)
|
2012-11-06 20:31:53 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-08-25 18:41:46 +02:00
|
|
|
def json_success(request: HttpRequest, data: Mapping[str, Any] = {}) -> MutableJsonResponse:
|
2012-11-06 20:31:53 +01:00
|
|
|
return json_response(data=data)
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-08-25 18:41:46 +02:00
|
|
|
def json_response_from_error(exception: JsonableError) -> MutableJsonResponse:
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2017-07-25 22:17:55 +02:00
|
|
|
This should only be needed in middleware; in app code, just raise.
|
|
|
|
|
|
|
|
When app code raises a JsonableError, the JsonErrorHandler
|
|
|
|
middleware takes care of transforming it into a response by
|
|
|
|
calling this function.
|
2021-02-12 08:19:30 +01:00
|
|
|
"""
|
2023-04-04 07:09:30 +02:00
|
|
|
response_type = "error"
|
|
|
|
if 200 <= exception.http_status_code < 300:
|
|
|
|
response_type = "success"
|
2021-02-12 08:19:30 +01:00
|
|
|
response = json_response(
|
2023-04-04 07:09:30 +02:00
|
|
|
response_type, msg=exception.msg, data=exception.data, status=exception.http_status_code
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2020-11-27 16:33:01 +01:00
|
|
|
|
|
|
|
for header, value in exception.extra_headers.items():
|
|
|
|
response[header] = value
|
|
|
|
|
|
|
|
return response
|
2022-05-27 01:06:39 +02:00
|
|
|
|
|
|
|
|
|
|
|
class AsynchronousResponse(HttpResponse):
|
|
|
|
"""
|
|
|
|
This response is just a sentinel to be discarded by Tornado and replaced
|
|
|
|
with a real response later; see zulip_finish.
|
|
|
|
"""
|
|
|
|
|
|
|
|
status_code = 399
|