2014-01-16 31 views
2

我正在嘗試生成用於python測試用例的摘要授權標頭。由於代碼庫的工作方式,能夠以字符串的形式獲取頭文件非常重要。 這頭看起來像這樣使用urllib2生成授權摘要標頭或請求

Authorization: Digest username="the_user", realm="my_realm", nonce="1389832695:d3c620a9e645420228c5c7da7d228f8c", uri="/some/uri", response="b9770bd8f1cf594dade72fe9abbb2f31" 

我想我最好的賭注是爲使用的urllib2或請求庫。

隨着urllib2的,我有這個迄今爲止得到:

au=urllib2.HTTPDigestAuthHandler() 
au.add_password("my_realm", "http://example.com/", "the_user", "the_password") 

,但我不能讓頭了這一點。

預約,我有這個迄今爲止得到:

requests.HTTPDigestAuth("the_user", "the_password") 

但我當我嘗試使用,在一個請求,我收到有關設置,我想不通的境界錯誤怎麼辦

回答

3

如果你準備自己扭曲圍繞它,你可以得到requests.auth.HTTPDigestAuth類做這樣的事情,給你正確的答案:

from requests.auth import HTTPDigestAuth 

chal = {'realm': 'my_realm', 'nonce': '1389832695:d3c620a9e645420228c5c7da7d228f8c'} 
a = HTTPDigestAuth('the_user', password) 
a.chal = chal 

print a.build_digest_header('GET', '/some/uri') 

如果我使用'the_password'作爲用戶的密碼,這給了我這樣的結果:

Digest username="the_user", realm="my_realm", nonce="1389832695:d3c620a9e645420228c5c7da7d228f8c", uri="/some/uri", response="0b34daf411f3d9739538c7e7ee845e92" 
+0

我遇到了一些麻煩產生的隨機數。我發現這個:'md5(「%d:%s」%(time.time(),'the_realm')).hexdigest()}'但這似乎不起作用。 – scottmrogowski

+0

你在最後得到了無與倫比的大括號。 – Lukasa

+0

它也看起來像你應該只有MD5領域,而不是整個字符串。所以適當的字符串是:'「%d:%d」%(time.time(),md5('the_realm')。hexdigest()) – Lukasa