3

私は Tastypie を使用して Resource を返していますが、そのフィールドの 1 つがアラビア語であるため、UTF-8 と Unicode である必要があります。これは、スキーマを実行する場合に当てはまると想定しています。

"word": {..., "help_text": "Unicode 文字列データ。例: \"Hello World\"", ...}

返されたサンプル json は次のとおりです。単語の文字化けしたフィールドに注意してください: {"approved": false, "id": 12, "resource_uri": "/api/v1/resource/12/", "word": "اه "}

4

1 に答える 1

11

これは、 https ://github.com/toastdriven/django-tastypie/issues/717 に従って content-type が application/json または text/javascript の場合に charset=utf-8 を送信しないように Tastypie にパッチを適用したためです。

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)

2行を削除することができます

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()
于 2013-07-12T09:09:45.253 に答える