django rest_framework中将json输出字符强制为utf-8编码
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django rest_framework中将json输出字符强制为utf-8编码相关的知识,希望对你有一定的参考价值。
最近在和日本外包合作开发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 JSONRenderer class 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编码的主要内容,如果未能解决你的问题,请参考以下文章
Django.rest_framework:如何序列化一对多?