有没有简单的方法可以覆盖DjangoJSONEncoder.ensure_ascii并将其设置为False或以其他任何方式在django.http.JsonResponse中输出非ASCII文本?

最佳答案

从Django 1.9开始,您可以通过输入JSONResponse argument的值来配置ensure_ascii以禁用json_dumps_params开关:

return JsonResponse(response_data, safe=False, json_dumps_params={'ensure_ascii': False})


对于ensure_ascii=Falsejson.dumps()输出非ASCII代码点的UTF-8数据。

您可以将JsonResponse子类化为默认值,除非另行设置:

from django.http.response import JsonResponse

class UTF8JsonResponse(JsonResponse):
    def __init__(self, *args, json_dumps_params=None, **kwargs):
        json_dumps_params = {"ensure_ascii": False, **(json_dumps_params or {})}
        super().__init__(*args, json_dumps_params=json_dumps_params, **kwargs)


然后整个使用它而不是JsonResponse。

在最末端,您可以通过猴子修补类将默认情况下的ensure_ascii设置为False。将以下内容放入Django应用程序的合适模块中(例如,放在名为patches.py的文件中):

import logging
from functools import wraps
from django.http.response import JsonResponse

logger = logging.getLogger(__name__)

def patch_jsonresponse_disable_ensure_ascii():
    if getattr(JsonResponse, '_utf8_patched', False):
        # Already patched. Add warning in logs with stack to see what location
        # is trying to patch this a second time.
        logger.warning("JSONResponse UTF8 patch already applied", stack_info=True)
        return

    logger.debug("Patching JSONResponse to disable ensure_ascii")
    orig_init = JsonResponse.__init__

    @wraps(orig_init)
    def utf8_init(self, *args, json_dumps_params=None, **kwargs):
        json_dumps_params = {"ensure_ascii": False, **(json_dumps_params or {})}
        orig_init(self, *args, json_dumps_params, **kwargs)

    JsonResponse.__init__ = utf8_init
    JsonResponse._utf8_patched = True  # to prevent accidental re-patching


然后将patch_jsonresponse_disable_ensure_ascii导入到Django设置文件中,并根据所需的配置进行调用:

from yourapp.patches import patch_jsonresponse_disable_ensure_ascii

JSON_RESPONSES_UTF8 = True

if JSON_RESPONSES_UTF8:
    patch_jsonresponse_disable_ensure_ascii()

关于json - 在Django中创建UTF-8 JsonResponse,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34798703/

10-09 23:50