authentik.api.renderers
1from typing import Any 2from uuid import UUID 3 4from django.db.models.enums import ChoicesType 5from django.utils.functional import Promise 6from msgspec.json import Encoder 7from rest_framework.renderers import BaseRenderer 8from rest_framework.settings import api_settings 9 10 11def enc_hook(obj: Any) -> Any: 12 if isinstance(obj, dict): 13 return dict(obj) 14 if isinstance(obj, list): 15 return list(obj) 16 if isinstance(obj, (str, UUID, Promise, ChoicesType)): 17 return str(obj) 18 if hasattr(obj, "tolist"): 19 return obj.tolist() 20 if hasattr(obj, "__iter__"): 21 return list(item for item in obj) 22 return None 23 24 25_ENCODER = Encoder( 26 enc_hook=enc_hook, 27 decimal_format="string" if api_settings.COERCE_DECIMAL_TO_STRING else "number", 28) 29 30 31class MsgspecJSONRenderer(BaseRenderer): 32 media_type = "application/json" 33 format = "json" 34 35 def render(self, data: Any, accepted_media_type=None, renderer_context=None) -> bytes: 36 if data is None: 37 return b"" 38 39 return _ENCODER.encode(data)
def
enc_hook(obj: Any) -> Any:
12def enc_hook(obj: Any) -> Any: 13 if isinstance(obj, dict): 14 return dict(obj) 15 if isinstance(obj, list): 16 return list(obj) 17 if isinstance(obj, (str, UUID, Promise, ChoicesType)): 18 return str(obj) 19 if hasattr(obj, "tolist"): 20 return obj.tolist() 21 if hasattr(obj, "__iter__"): 22 return list(item for item in obj) 23 return None
class
MsgspecJSONRenderer(rest_framework.renderers.BaseRenderer):
32class MsgspecJSONRenderer(BaseRenderer): 33 media_type = "application/json" 34 format = "json" 35 36 def render(self, data: Any, accepted_media_type=None, renderer_context=None) -> bytes: 37 if data is None: 38 return b"" 39 40 return _ENCODER.encode(data)
All renderers should extend this class, setting the media_type
and format attributes, and override the .render() method.