[docs]classjson(dict):""" This is a marked dict type that our view event listener will recognize and serialize to json in a response. Usage:: def handler(): return json({"foo": "bar"}) """pass
defserialize(value):returnorjson.dumps(value,option=orjson.OPT_NON_STR_KEYS|orjson.OPT_NAIVE_UTC,default=default,)asyncdefon_json_response(event:ViewEvent):ifisinstance(event.value,json):content_type="application/json"try:serialized=serialize(event.value)event.set_response(HttpResponse(serialized,status=200,content_type=content_type),)exceptTypeErrorasexc:event.set_response(HttpResponse(orjson.dumps({"error":"Cannot serialize response to json.","type":type(exc).__name__,"message":str(exc),"traceback":traceback.format_exc(),"value":repr(event.value),},),status=500,content_type=content_type,),)defregister(dispatcher:IAsyncEventDispatcher):dispatcher.add_listener(EVENT_CORE_VIEW,on_json_response)