2012-04-08 58 views
0

我怎麼會tranfoms這個curl命令:的urllib2引發403錯誤而捲曲同一請求工作正常

curl -v -d [email protected] -d password=mypassword -X POST https://www.toggl.com/api/v6/sessions.json 

到urlib2?

這是爲什麼不工作:

url=  'https://www.toggl.com/api/v6/sessions.json' 
username = '[email protected]' 
password = 'mypassword' 

passman = urllib2.HTTPPasswordMgrWithDefaultRealm() 
passman.add_password(None, url, username, password) 

authhandler = urllib2.HTTPBasicAuthHandler(passman) 

opener = urllib2.build_opener(authhandler) 

urllib2.install_opener(opener) 
pagehandle = urllib2.urlopen(url) 

它給了我這個錯誤:

Traceback (most recent call last): 
    File "/Users/jorrit/virtualenvs/tiddle/tiddle/troggle/tests.py", line 16, in test_get_troggle_connection 
    get_projects() 
    File "/Users/jorrit/virtualenvs/tiddle/tiddle/troggle/views.py", line 29, in get_projects 
    pagehandle = urllib2.urlopen(url) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open 
    response = meth(req, response) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error 
    return self._call_chain(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain 
    result = func(*args) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
HTTPError: HTTP Error 403: Forbidden 

回答

0

與請求包,代碼如下:

import requests 

url = 'https://www.toggl.com/api/v6/sessions.json' 
payload = {'email': '[email protected]', 
      'password': 'mypassword'} 

r = requests.post(url, data=payload) 
+0

以及如何使用API​​密鑰而不是密碼和用戶名? – jorrebor 2012-04-08 14:27:15

+0

更改爲有效載荷= {'api_token':令牌},這可能會根據他們的文檔工作... – 2012-04-09 10:50:02

0

,因爲你的urllib代碼做的東西比你的curl命令別人。試試這個:

import urllib 
import urllib2 

url = 'https://www.toggl.com/api/v6/sessions.json' 
values = {'email': '[email protected]', 
      'password': 'mypassword'} 

data = urllib.urlencode(values) 
req = urllib2.Request(url, data) 
response = urllib2.urlopen(req) 
the_page = response.read() 
+0

這個工程確實是,但我去請求包。 – jorrebor 2012-04-08 12:49:52