django rest_framework中將json輸出字元強製為utf-8編碼

來源:互聯網
上載者:User

標籤: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編碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.