问题
I'm trying to log into Reddit and get my own account data.
This my Python code:
from pprint import pprint
import requests
import json
username = 'dirk_b'
password = 'willnottell'
user_pass_dict = {'user': username,
'passwd': password,
'api_type': 'json',
'rem': True, }
headers = {'dirkie': '/u/dirk_b API python test', }
client = requests.session()
client.headers = headers
r = client.post(r'http://www.reddit.com/api/login', data=user_pass_dict)
j = json.loads(r.content.decode());
client.modhash = j['json']['data']['modhash']
s = client.post(r'http://www.reddit.com/api/me.json', data=user_pass_dict)
pprint(s.content)
The response I get is: b'{"error": 404}'
If I do the same request without the .json part. I get a bunch of HTML code with the being 'reddit.com: page not found'. So I assume I'm doing something wrong with the URL. But the URL as I use it is how it is specified in the Reddit API.
The reason I'm not using PRAW is because I eventually want to be able to do this in c++, but I wanted to make sure it works in Python first.
回答1:
The /api/me.json route only accepts GET requests:
s = client.get('http://www.reddit.com/api/me.json')
There is no POST route for that endpoint, so you'll get a 404 for that.
Also, if you need to pass modhash
to the server, do so in the data passed in the POST request; setting client.modhash
does not then pass that parameter to the server. You retrieve the modhash from your me.json
GET response:
r = client.get('http://www.reddit.com/api/me.json')
modhash = r.json()['modhash']
Note how the response from requests
has a .json()
method, there is no need to use the json
module yourself.
You then use the modhash
in POST request data:
client.post('http://www.reddit.com/api/updateapp', {'modhash': modhash, 'about_url': '...', ...})
来源:https://stackoverflow.com/questions/17254248/404-error-when-requesting-json-in-reddit-api