django - Tastypie:使用 UTF-8 的 JSON header

标签 django tastypie

我正在使用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/

相关文章:

django - 从 AbstractUser 继承的模型不会散列密码字段

django - 如何限制 django admin 内联表单集

python - 按 json 中的计数排序

django - 在tastypie-swagger中,设置文件中 'TASTYPIE_SWAGGER_API_MODULE'的值应该是多少?

django - MacVim 中的错误命令输出

python - 向 Django 模型添加代码和方法会破坏它

javascript - 为什么 Django 允许用户以 CharField 形式输入 <script>alert ("hello")</script> 而不会抛出错误?

Django & TastyPie : request. POST 为空

python - page() 接受 1 个位置参数,但给出了 2 个

tastypie - 验证/授权访问 tastypie 顶级 API 模式