2012-06-04 89 views
15

此問題基於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輸出到不同編碼,沒有成功...什麼是克服這個問題

回答

35

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şüğçö} 
+0

謝謝很多,就像一個魅力(: – FallenAngel

+2

如果像我一樣,試圖用'pformat'(而不是pprint)來使用它並將結果字符串發送給一個模板引擎,例如'jinja2',它會給你一個'UnicodeDecodeError',你可以通過調用(在這個答案中)unicode(MyPrettyPrinter()。pformat(d),'utf-8')來解決這個問題。 – fiatjaf

+1

你可以使用format set選項來包裝你的pprint PyPI,它會有幫助。 –

1

,您應該使用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,那麼你真的應該使用unicode文字!

無論如何,thg435 has given you a solution如何改變這種行爲的pformat。

+0

是正常的稱爲二進制字符串(非Unicode)的字符串?我認爲他們是ASCII字符串 – jdi

+0

我也試過,我也試過了django的'smart_str','smart_unicode'和soe其他方法......當我使用unicode字符串像'u'müşteri'時,我得到的是'u'm \ xfc \ u015fteri'' – FallenAngel

+0

@FallenAngel - 這是由pformat生成的unicode字符串的表示形式,我發現您的問題有點不同,然後我認爲...我會再次檢查它... – mata

相關問題