在Reddit API中请求JSON时出现404错误 [英] 404 error when requesting json in Reddit API
问题描述
我正在尝试登录Reddit并获取我自己的帐户数据.
I'm trying to log into Reddit and get my own account data.
这是我的Python代码:
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)
我得到的答复是:b'{错误":404}'
The response I get is: b'{"error": 404}'
如果我执行相同的请求,但没有.json部分.我得到了一堆HTML代码,显示为"reddit.com:未找到页面".所以我想我在URL上做错了.但是我使用的URL是Reddit API中指定的URL.
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.
我不使用PRAW的原因是因为我最终希望能够在c ++中执行此操作,但是我想确保它首先在Python中起作用.
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.
推荐答案
/api/me.json
路线仅接受GET请求:
The /api/me.json
route only accepts GET requests:
s = client.get('http://www.reddit.com/api/me.json')
该端点没有POST路由,因此您将获得404.
There is no POST route for that endpoint, so you'll get a 404 for that.
此外,如果需要将modhash
传递给服务器,请在POST请求中传递的数据中进行;设置client.modhash
不会不是,然后将该参数传递给服务器.您从me.json
GET响应中检索 modhash:
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']
请注意,来自requests
的响应如何具有.json()
方法,无需自己使用json
模块.
Note how the response from requests
has a .json()
method, there is no need to use the json
module yourself.
然后在POST请求数据中使用modhash
:
You then use the modhash
in POST request data:
client.post('http://www.reddit.com/api/updateapp', {'modhash': modhash, 'about_url': '...', ...})
这篇关于在Reddit API中请求JSON时出现404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!