JSON Middleware

class smarter.lib.django.middleware.json.SmarterJsonErrorMiddleware(get_response, *args, **kwargs)[source]

Bases: SmarterMiddlewareMixin

Middleware that converts non-JSON error responses into JSON responses for clients requesting JSON content.

async async_process_response(request, response)[source]

Async version of process_response().

Parameters:
Return type:

HttpResponseBase

Returns:

The response, or a JsonResponse with the same status code.

static build_error_payload(response)[source]

Build the JSON error payload that replaces an error response.

Parameters:

response (HttpResponseBase) – The error response.

Return type:

dict[str, Any]

Returns:

{"error": {"status_code": ..., "message": ...}}, with the response’s status code and reason phrase.

client_accepts_json(request)[source]

Return whether the client accepts JSON responses.

Parameters:

request (HttpRequest) – The request.

Return type:

bool

Returns:

True if the Accept header names one of JSON_CONTENT_TYPES.

property formatted_class_name: str[source]

Return the formatted class name for logging.

It names the instance, not a request.

normalize_json_error_response(request, response)[source]

Convert non-JSON error responses into JsonResponse objects.

Only responses with a status of 400 or more, to clients that accept JSON, are converted.

Parameters:
Return type:

HttpResponseBase

Returns:

The response, or a JsonResponse with the same status code.

process_response(request, response)[source]

Convert an error response to JSON for clients that accept JSON.

It does nothing unless the ENABLE_MIDDLEWARE_SMARTER_JSON_ERROR waffle switch is active.

Parameters:
Return type:

HttpResponseBase

Returns:

The response, or a JsonResponse with the same status code.

static response_is_json(response)[source]

Return whether the response is already JSON.

Parameters:

response (HttpResponseBase) – The response from the view.

Return type:

bool

Returns:

True if its Content-Type contains json.