此問題基於that one的副作用。無法編碼/解碼pprint輸出
我.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輸出到不同編碼,沒有成功...什麼是克服這個問題
謝謝很多,就像一個魅力(: – FallenAngel
如果像我一樣,試圖用'pformat'(而不是pprint)來使用它並將結果字符串發送給一個模板引擎,例如'jinja2',它會給你一個'UnicodeDecodeError',你可以通過調用(在這個答案中)unicode(MyPrettyPrinter()。pformat(d),'utf-8')來解決這個問題。 – fiatjaf
你可以使用format set選項來包裝你的pprint PyPI,它會有幫助。 –