Reputation: 2576
I'm trying to get the voting API working, but I get the error .error.USER_REQUIRED. Can't figure out why, but I assume I must either be sending the modhash or the session cookie the wrong way, as the login goes trough fine
My code looks something like this:
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))
Error:
{"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", []]]}
Upvotes: 2
Views: 2068
Reputation: 4422
To login you should post to ssl.reddit.com
so that you are not posting your credentials in plain-text. Also, you should set a User-Agent.
The below is a working example to vote on your /r/redditdev submission.
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 {}
Also, unless you are really interested in how reddit's API works under the covers, I suggest you use PRAW.
Upvotes: 3
Reputation: 346
You can use session object with with
statement.
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...>
Upvotes: 0