17

この質問は、その副作用に基づいています。

私の.pyファイルはすべて# -*- coding: utf-8 -*-、私のように最初の行にエンコーディング定義者がありますapi.py

関連する質問で述べたように、私HttpResponseは API ドキュメントを返すために使用します。エンコーディングを次のように定義したので:

HttpResponse(cy_content, content_type='text/plain; charset=utf-8')

すべて問題ありません。API サービスを呼び出すと、 pprint によって辞書から形成された文字列を除いて、エンコードの問題はありません。

辞書の一部の値でトルコ文字を使用しているため、pprint はそれらをunichr次のような同等のものに変換します。

API_STATUS = {
    1: 'müşteri',
    2: 'some other status message'
}

my_str = 'Here is the documentation part that contains Turkish chars like işüğçö'
my_str += pprint.pformat(API_STATUS, indent=4, width=1)
return HttpRespopnse(my_str, content_type='text/plain; charset=utf-8')

そして、私のプレーンテキスト出力は次のようになります:

Here is the documentation part that contains Turkish chars like işüğçö

{
    1: 'm\xc3\xbc\xc5\x9fteri',
    2: 'some other status message'
}

pprint 出力をさまざまなエンコーディングにデコードまたはエンコードしようとしましたが、成功しませんでした... この問題を克服するためのベストプラクティスは何ですか?

4

2 に答える 2

39

pprintデフォルトで使用reprしているように見えますが、オーバーライドすることでこれを回避できますPrettyPrinter.format

# coding=utf8

import pprint

class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, unicode):
            return (object.encode('utf8'), True, False)
        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)


d = {'foo': u'işüğçö'}

pprint.pprint(d)              # {'foo': u'i\u015f\xfc\u011f\xe7\xf6'}
MyPrettyPrinter().pprint(d)   # {'foo': işüğçö}
于 2012-06-04T15:28:41.173 に答える
1

8 ビット文字列の代わりに Unicode 文字列を使用する必要があります。

API_STATUS = {
    1: u'müşteri',
    2: u'some other status message'
}

my_str = u'Here is the documentation part that contains Turkish chars like işüğçö'
my_str += pprint.pformat(API_STATUS, indent=4, width=1)

このpprintモジュールは、可能なすべての種類のネストされた構造を読みやすい方法で出力するように設計されています。これを行うには、オブジェクト表現を文字列に変換するのではなく出力するため、Unicode 文字列を使用するかどうかに関係なく、エスケープ構文になります。しかし、ドキュメントで Unicode を使用している場合は、本当に Unicode リテラルを使用する必要があります!

とにかく、thg435 は、pformatのこの動作を変更する方法を提供してくれました。

于 2012-06-04T15:17:58.660 に答える