博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django rest_framework中将json输出字符强制为utf-8编码
阅读量:7146 次
发布时间:2019-06-29

本文共 1254 字,大约阅读时间需要 4 分钟。

最近在和日本外包合作开发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,)

  

转载地址:http://mfzgl.baihongyu.com/

你可能感兴趣的文章
Xcode9 自动上传Fir
查看>>
JavaScript异步流程控制的前世今生
查看>>
通过static关键词来实现late static binding(静态调用绑定)
查看>>
Android小知识-OkHttp的两种请求方式
查看>>
阿里巴巴前端工程师一面二面三面终面面经总结
查看>>
Python正则表达式初识(七)
查看>>
Cocos Creator踩坑日记(一)
查看>>
webpack之代码拆分
查看>>
.NET Core容器化@Docker
查看>>
(1)Linux性能调优之Linux进程管理
查看>>
每周一个 Python 模块 | operator
查看>>
Synchronized原理
查看>>
服务化改造实践(三) | Dubbo + Zipkin
查看>>
Mysql 隔离级别
查看>>
Java虚拟机规范(目录)
查看>>
4.java数组
查看>>
阿里开发者们的第19个感悟:Simple is better.
查看>>
区块链技术进阶
查看>>
超简单七步,解决windows下安装PaddlePaddle的权限错误!
查看>>
Appium框架
查看>>