我使用tastypie返回一个资源,它的一个字段是阿拉伯语的,因此需要使用UTF-8与Unicode,这就是我在运行其模式时假设的情况:
"word":{...,"help_text":"Unicode字符串数据,例如:\"Hello World\“,...}
这里是返回的示例json,注意word:{"approved":false,"id":12,"resource_uri":"/api/v1/resource/12/","word":“Ö§‡”}乱码字段
发布于 2013-07-12 17:09:45
这是因为他们给Tastypie打了补丁,当content-type是application/json或text/javascript per https://github.com/toastdriven/django-tastypie/issues/717时,不再发送charset=utf-8。
如果你看一看tastypie/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源代码,请执行我所做的操作。
我注意到build_content_type用在ModelResource的create_response方法中,所以我创建了一个新的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()https://stackoverflow.com/questions/17280513
复制相似问题