2012-10-17 28 views
2

我試圖讓投票API能夠正常工作,但是我得到錯誤.error.USER_REQUIRED。想不通爲什麼,但我認爲我必須被髮送modhash或會話cookie錯誤的方式,如登錄進入低谷精細Reddit API和投票。不接受modhash/cookie。 .error.USER_REQUIRED

我的代碼看起來是這樣的:

UP = {'user': username, 'passwd': password, 'api_type': 'json',} 

client = requests.session() 

r = client.post('http://www.reddit.com/api/login', data=UP) 

j = json.loads(r.text) 

mymodhash = j['json']['data']['modhash'] 

url = 'http://www.reddit.com/api/vote/.json' 
postdata = {'id': thing, 'dir': newdir, 'uh': mymodhash} 
vote = client.post(url, data=json.dumps(newdata)) 

錯誤:

{"jquery": [[0, 1, "refresh", []], [0, 2, "attr", "find"], [2, 3, "call", [".error.USER_REQUIRED"]], [3, 4, "attr", "show"], [4, 5, "call", []], [5, 6, "attr", "text"], [6, 7, "call", ["please login to do that"]], [7, 8, "attr", "end"], [8, 9, "call", []]]} 

回答

3

登陸您應該帖子ssl.reddit.com這樣,你是不是在純文本發佈您的憑據。另外,你應該設置一個User-Agent。

以下是對您的/ r/redditdev提交進行投票的工作示例。

import requests 
# Login                         
client = requests.session(headers={'User-Agent': 'Requests test'}) 
data = {'user': 'USERNAME', 'passwd': 'PASSWORD', 'api_type': 'json'} 
r = client.post('https://ssl.reddit.com/api/login', data=data) 
modhash = r.json['json']['data']['modhash'] 

# Vote                         
data = {'id': 't3_11mr32', 'dir': '1', 'uh': modhash, 'api_type': 'json'} 
r = client.post('http://www.reddit.com/api/vote', data=data) 
print r.status_code # Should be 200                 
print r.json # Should be {} 

此外,除非你是在reddit的的API在幕後的工作原理很感興趣,我建議你使用PRAW

+0

什麼是'用戶代理':'請求測試'? –

+0

這表明你是一個標識爲'Requests test'的客戶。根據Reddit的API,這個用戶代理應該更具描述性:https://github.com/reddit/reddit/wiki/API#rules。另外值得注意的是,Reddit的API不再正式支持第三方客戶端的cookie-auth,所以你真的應該看看OAuth。 – bboe

0

您可以使用會話對象和with語句。

import requests 

UP = {'user': username, 'passwd': password, 'api_type': 'json'} 
url_prefix = "http://www.reddit.com" 
with requests.session() as client: 
    client.post(url_prefix + '/login', data=UP) 

    <...something else what you want...> 
+0

我已經試過,現在仍然不接受登錄。我也嘗試從http://www.reddit.com/api/me.json獲取modhash,但仍拒絕。我想我必須誤解modhash的工作方式,也許它會因爲我請求URL的方式而改變。我猜也可能是cookie。 –