2012-11-20 94 views
1

我正在使用Robot框架來自動化一些HTTP POST相關測試。我編寫了一個自定義Python庫,它具有執行HTTP POST的功能。它看起來像這樣:用我的Python函數解碼錯誤

# This function will do a http post and return the json response 
def Http_Post_using_python(json_dict,url): 
    post_data = json_dict.encode('utf-8') 
    headers = {} 
    headers['Content-Type'] = 'application/json' 
    h = httplib2.Http() 
    resp, content = h.request(url,'POST',post_data,headers) 
    return resp, content 

這工作正常,只要我沒有使用任何Unicode字符。當我在json_dict變量Unicode字符(例如,메시지)時,出現此錯誤:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xeb in position 164: ordinal not in range(128)

我正在運行的Python 2.7.3在Windows 7上我看到了幾個相關的問題,但我還沒有能夠解決這個問題。我是Python和編程新手,所以任何幫助表示讚賞。

謝謝。

+1

請包括* full *回溯。 –

+0

你試過post_data = unicode(json_dict,encoding =「utf-8」)嗎?我真的不清楚編碼/解碼/解析如何工作(這就是爲什麼這是一個評論,而不是答案),但也許它會幫助... – BorrajaX

+1

@BorrajaX'unicode(json_dict,encoding =「utf- 8「)'與OP想要的完全相反 - 他們想要一個'str',*而不是'unicode'。 –

回答

2

你會得到這個錯誤,因爲json_dictstr,而不是unicode。不知道什麼對應用程序,一個簡單的解決辦法是:

if isinstance(json_dict, unicode): 
    json_dict = json_dict.encode("utf-8") 
post_data = json_dict 

但是,如果你使用json.dumps(…)創建json_dict,那麼你就需要對它進行編碼 - 將由json.dumps(…)完成。

+0

非常感謝回覆。 json.dumps做到了。 – user1840125

1

使用requests

requests.post(url, data=data, headers=headers) 

它將處理的編碼爲您服務。


你變得因爲Python 2的自動編碼/解碼,這基本上是一個錯誤,並固定在Python 3簡而言之,Python中的錯誤2的str對象是真正的「字節」,右處理字符串數據的方法是在unicode對象中。由於後面介紹了unicode,所以當你感到困惑時,Python 2會自動嘗試在它們和字符串之間進行轉換。要做到這一點,它需要知道一個編碼;因爲你沒有指定一個,所以它默認爲ascii,它沒有所需的字符。

爲什麼Python會自動爲您解碼?因爲您在str對象上調用.encode()。它已經被編碼,因此Python首先嚐試爲您解碼,並猜測ascii編碼。


您應該閱讀The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

+0

感謝您的回覆。 – user1840125

-3

試試這個:

#coding=utf-8 
test = "메시지" 
test.decode('utf8') 

在我剛纔設置的文件編碼爲UTF-8行#coding=utf-8(要能寫 「메시지」)。

您需要將字符串解碼爲utf-8。 decode method documentation

+0

設置源代碼編碼僅適用於*閱讀*源代碼,特別是文字。它不會*神奇地解決任何其他的unicode字節轉換。 –