【问题标题】:django rest-framework api and unicode charactersdjango rest-framework api 和 unicode 字符
【发布时间】:2014-12-05 14:35:34
【问题描述】:

我正在使用 django-rest-framework 为我的应用程序创建一个 api。我的应用程序使用希腊字母作为其模型的值。我已经创建了我的视图集并使用 UnicodeJSONRenderer 来返回 json 结果。

class ChapterViewSet(viewsets.ModelViewSet):
    queryset = Chapter.objects.all()
    serializer_class = ChapterSerializer
    renderer_classes = (UnicodeJSONRenderer, )

返回Json,但浏览器无法识别希腊字母(“Ξ ΟΟΟΞΈΞ΅ΟΞ·)。在chrome的开发控制台上,虽然在网络选项卡上,响应的预览正常显示希腊字母。我怎样才能让我的浏览器识别希腊字母?

【问题讨论】:

  • 您是否在页面的 head 标签中使用了将属性 charset 设置为 utf-8 的元标签?
  • 你能举个例子吗?
  • 他大概想到了html标签<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  • 但我没有返回 html,我正在返回 application/json 内容。
  • @Apostolos 你能把浏览器的编码方案改成 unicode 吗?您可以在 Chrome 的右侧找到扳手工具。试试看,让我们知道。

标签: json django rest unicode


【解决方案1】:

为我解决了什么问题(因为 pt-BR 我需要口音)

转到您的 settings.py 并包含

REST_FRAMEWORK = {
    #this bit makes the magic.
    'DEFAULT_RENDERER_CLASSES': (
         #UnicodeJSONRenderer has an ensure_ascii = False attribute,
         #thus it will not escape characters.
        'rest_framework.renderers.UnicodeJSONRenderer',
         #You only need to keep this one if you're using the browsable API
        'rest_framework.renderers.BrowsableAPIRenderer',
    )
}

通过这样做,您不需要在您拥有的每个视图中都包含序列化程序 renderer_classes。

希望它也能为您解决问题!

【讨论】:

【解决方案2】:

这是一个我也遇到过的非常奇怪的问题;我的第一印象是 Django REST Framework 应该在 Content-Type 标头中将字符集设置为 UTF-8,但这已经被归档为 issue #2891 并且显然有很多争论。

我最终使用的修复方法是将UNICODE_JSON 设置为False。这会导致更大的响应,特别是如果您的响应中有很多 unicode 字符,例如水平省略号在字符串中变为\u2026,而不是其等效的 3 字节 UTF-8 表示,但它不太可能被客户端误解。

【讨论】:

    【解决方案3】:

    这是一个浏览器问题。

    UTF-8 is the default encoding 用于 JSON 内容; Django Rest Framework 正在将您的 JSON 正确编码为 UTF-8,但您的浏览器未正确显示它。

    如果在 Content-Type HTTP 标头中提供charset=utf-8,浏览器将正确显示它。但是,规范定义了another way of determining the encoding,因此不应使用它。 Django Rest Framework 通过不包含它来尊重这一点。

    Chrome 上有一个open ticket,但不幸的是,似乎没有人在意。其他浏览器似乎也有同样的问题。另见this SO question

    【讨论】:

      猜你喜欢
      • 2014-06-05
      • 2014-09-14
      • 1970-01-01
      • 2017-08-18
      • 2016-07-08
      • 2020-06-24
      • 1970-01-01
      • 2016-08-01
      • 2019-04-26
      相关资源
      最近更新 更多