我正在使用tastypie来返回一个资源,它的一个字段是阿拉伯语,因此需要使用UTF-8 vs Unicode,这就是我假设运行其架构的情况:
"word": {..., "help_text": "Unicode 字符串数据。例如:\"Hello World\"", ...}
下面是返回的示例json,注意word的乱码字段:
{"approved": false, "id": 12, "resource_uri": "/api/v1/resource/12/", "word": "اه"}
最佳答案
这是因为当内容类型为 application/json 或 text/javascript 时,他们修补了 Tastypie 不再发送 charset=utf-8 https://github.com/toastdriven/django-tastypie/issues/717 .
如果您查看tyspypie/utils/mime.py,您会注意到以下几行:
def build_content_type(format, encoding='utf-8'):
"""
Appends character encoding to the provided format if not already present.
"""
if 'charset' in format:
return format
if format in ('application/json', 'text/javascript'):
return format
return "%s; charset=%s" % (format, encoding)
您可以删除这两行
if format in ('application/json', 'text/javascript'):
return format
或者如果您不想修改 Tastypie 源代码,请执行我所做的操作。
我注意到在 ModelResource 的 create_response 方法中使用了 build_content_type,所以我创建了一个新的 ModelResource 作为 ModelResource 的子类并覆盖了该方法。
from django.http import HttpResponse
from tastypie import resources
def build_content_type(format, encoding='utf-8'):
"""
Appends character encoding to the provided format if not already present.
"""
if 'charset' in format:
return format
return "%s; charset=%s" % (format, encoding)
class MyModelResource(resources.ModelResource):
def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
"""
Extracts the common "which-format/serialize/return-response" cycle.
Mostly a useful shortcut/hook.
"""
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)
然后,我将我的资源改为从这个类继承。
class MyResource(MyModelResource):
class Meta:
queryset = MyObject.objects.all()
关于django - Tastypie:使用 UTF-8 的 JSON header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17280513/