2016-09-10 38 views
0

我有一個字典如下Python的編碼空格被正確編碼

params = { 
     'response_type': 'token', 
     'client_id': o_auth_client_id, 
     'redirect_url': call_back_url, 
     'scope': 'activity heartrate location' 

} 
print urllib.urlencode(params) 

和UM編碼它

但是在結果中

REDIRECT_URL = HTTP%3A%2F%2F127.0.0 .1%3A8084%2Fagile_healtg%2Faccess_token%2F & response_type = token & client_id = xxxxxx & scope = activity + heartrate + location

嗯越來越像上述 不幸的是空間被編碼爲+號

,但結果應該是

範圍=活性%20nutrition%20heartrate

我可如何實現Python中的空格的正確編碼?

+0

這是在查詢空間正確的編碼。試試'「http://www.google.com/?」 + urllib.urlencode({「q」:「http query string」})'。 – zvone

+0

@zvone我需要空格作爲%20編碼空格,因爲+不正確 – Kalanamith

+1

但它並不正確。 '+'是查詢字符串參數中空格的正確編碼。 '%20'是路徑元素中空間的編碼。 –

回答

1

這個程序可以做你要求什麼。

import urllib 

def my_special_urlencode(params): 
    return '&'.join('{}={}'.format(urllib.quote(k, ''), urllib.quote(v, '')) for k,v in params.items()) 

params = { 
     'response_type': 'token', 
     'client_id': 'xxxxxx', 
     'redirect_url': 'http://example.com/callback', 
     'scope': 'activity heartrate location' 

} 

print my_special_urlencode(params) 

結果:

redirect_url=http%3A%2F%2Fexample.com%2Fcallback&response_type=token&client_id=xxxxxx&scope=activity%20heartrate%20location 
+0

是的,這是解決方案 – Kalanamith

1

檢查urlencode的文檔。

quote_plus方法用於在傳遞鍵值時將空格更改爲加號。您可以使用unquote_plus方法刪除加號,然後使用quote以您想要的格式進行編碼。

你基本上需要使用quote方法爲您的參數

+0

這是我得到的redirect_url = http%3A%2F%2F127.0.0.1%3A8084%2Fagile_healtg%2Faccess_token%2F&response_type = token&client_id = xxxx&scope = activity%2Bheartrate%2Blocation我沒有得到%20 @George D – Kalanamith

+1

url必須使用'urlencode'方法編碼,其他參數使用'quote'編碼。 –