標籤:http res this pre pes creat 項目 合作 one
最近在和日本外包合作開發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編碼