Tastypie:使用UTF-8的JSON标头

时间:2013-06-24 16:35:27

标签: django tastypie

我正在使用tastypie返回一个资源,其中一个字段是阿拉伯语,因此需要使用UTF-8和Unicode,这就是我假设运行其模式的情况:

“word”:{...,“help_text”:“Unicode字符串数据。例如:\”Hello World \“”,...}

这里是json返回的示例,注意字的乱码字段: {“approved”:false,“id”:12,“resource_uri”:“/ api / v1 / resource / 12 /”,“word”:“اه”}

1 个答案:

答案 0 :(得分:11)

这是因为当内容类型为application / json或text / javascript per https://github.com/toastdriven/django-tastypie/issues/717时,他们修补Tastypie不再发送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()