[英]Unable to encode/decode pprint output
這個問題是基於那個問題的副作用。
我的.py
文件都具有# -*- coding: utf-8 -*-
第一行是# -*- 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輸出解碼或編碼為不同的編碼,但沒有成功...解決此問題的最佳實踐是什么
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şüğçö}
您應該使用unicode字符串而不是8位字符串:
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的這種行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.