首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Tastypie:使用UTF-8的JSON报头

问Tastypie:使用UTF-8的JSON报头
EN

Stack Overflow用户
提问于 2013-06-25 00:35:27
回答 1查看 1.9K关注 0票数 3

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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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,你会注意到下面的几行:

代码语言:javascript
复制
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)

您可以删除这两行

代码语言:javascript
复制
if format in ('application/json', 'text/javascript'):
    return format

或者,如果您不想修改Tastypie源代码,请执行我所做的操作。

我注意到build_content_type用在ModelResource的create_response方法中,所以我创建了一个新的ModelResource作为ModelResource的子类,并覆盖了该方法。

代码语言:javascript
复制
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)

然后,我更改了我的资源,改为从这个类继承。

代码语言:javascript
复制
class MyResource(MyModelResource):
    class Meta:
        queryset = MyObject.objects.all()
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17280513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档