分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

django rest_framework中将json输出字符强制为utf-8编码

发布时间:2023-09-06 01:07责任编辑:沈小雨关键词:jsjsondjango

最近在和日本外包合作开发JIRA对接发布系统的版本单时,

遇到这个问题。

就是我们这边的输出浏览器显示为中文,而到了JIRA端就出现乱码。

查了文档,原来django rest_framework的默认json是没指定编码的,

需要随接收方的环境编码来显示。

于是,因为项目进度,我们对了强制编码操作。

查看rest framework的源代码:

class JSONRenderer(BaseRenderer): ???""" ???Renderer which serializes to JSON. ???""" ???media_type = ‘application/json‘ ???format = ‘json‘ ???encoder_class = encoders.JSONEncoder ???ensure_ascii = not api_settings.UNICODE_JSON ???compact = api_settings.COMPACT_JSON ???# We don‘t set a charset because JSON is a binary encoding, ???# that can be encoded as utf-8, utf-16 or utf-32. ???# See: http://www.ietf.org/rfc/rfc4627.txt ???# Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/ ???charset = None

  于是,我们重写了一个继承自JSONRenderer的Utf8JSONRenderer。然后,指定一个renderer_classes属性值即可。

from rest_framework.renderers import JSONRendererclass Utf8JSONRenderer(JSONRenderer): ???charset = ‘utf-8‘

  

class DeployPoolViewSet(viewsets.ModelViewSet): ???""" ???This viewset automatically provides `list`, `create`, `retrieve`, ???`update` and `destroy` actions. ???Additionally we also provide an extra `highlight` action. ???""" ???serializer_class = DeployPoolSerializer ???authentication_classes = (TokenAuthentication,) ???renderer_classes = (Utf8JSONRenderer,)

  

django rest_framework中将json输出字符强制为utf-8编码

原文地址:http://www.cnblogs.com/aguncn/p/7461531.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved