Reddit API和投票。不接受modhash / cookie。 .error.USER_REQUIRED

时间:2012-10-17 14:10:07

标签: python api reddit

我正在尝试让投票API工作,但我收到错误.error.USER_REQUIRED。无法弄清楚为什么,但我认为我必须以错误的方式发送modhash或会话cookie,因为登录很顺利

我的代码看起来像这样:

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", []]]}

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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...>
相关问题