2011-02-10 60 views
0

在Python驗證我試圖創建的Python相當於捲曲使用標準庫

curl -u username:password http://policeapi2.rkh.co.uk/api/forces

這裏說http://www.police.uk/api/docs/authentication/

我手工通過瀏覽器登錄,並得到了認證工作

我第一次嘗試從這裏基本認證:

voi dspace.org.uk/python/articles/authentication.shtml

這種失敗

This page isn't protected by authentication. 
But we failed for another reason. 

我再從這個適應嘗試stackoverflow.com/questions/1990976/convert-a-curl-post-request -to-蟒蛇只-使用標準-libary

import urllib2 

def basic_authorization(user, password): 
    s = user + ":" + password 
    return "Basic " + s.encode("base64").rstrip() 

req = urllib2.Request("http://policeapi2.rkh.co.uk/api/forces", 
       headers = { 
    "Authorization": basic_authorization("username", "password"), 
    }) 

f = urllib2.urlopen(req) 

print f.read() 

,並得到:

URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it> 

,我讀了在stackove rflow.com/questions/2407126/python-urllib2-basic-auth-problem:

'問題可能在於,根據HTTP標準,Python庫首先發送一個未經身份驗證的請求,然後只有在應答401重試,是發送的正確憑證。如果Foursquare服務器不執行「完全標準認證」,那麼這些庫將無法工作。

鏈接回「此頁面不受身份驗證保護」。基本認證錯誤。

我用自己的代碼:

import urllib2, base64 

request = urllib2.Request("http://api.foursquare.com/v1/user") 
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') 
request.add_header("Authorization", "Basic %s" % base64string) 
result = urllib2.urlopen(request)' 

但仍然得到錯誤:

URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it> 

我不知道下一個嘗試的東西。我對Python編程和使用Curl很陌生,對於我剛剛獲得的基礎知識是否錯誤或者出現了一些更復雜的錯誤,我感到茫然。

感謝您提供的任何幫助。

+0

您可以嘗試運行Fiddler或(無論您的環境中最好使用http調試工具)並查看從瀏覽器訪問api時發生的http會話嗎? – marr75 2011-02-10 14:32:09

回答

0

I've manually logged in through a browser and got the authentication to work

你是怎麼做到的?

您是否使用FireBug或其他工具來觀察實際發生的事情?

您應該在閱讀太多StackOverflow答案之前研究其工作原理。

+0

我如上所述使用了Fiddler,結果證明我已經獲得了一個正在推薦的病毒。我刪除了這個,授權現在可以使用。感謝您的建議。 – user611478 2011-02-11 10:17:39