在 Reddit API 中请求 json 时出现 404 错误 [英] 404 error when requesting json in Reddit API

查看:34
本文介绍了在 Reddit API 中请求 json 时出现 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试登录 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'{"error": 404}'

The response I get is: b'{"error": 404}'

如果我在没有 .json 部分的情况下执行相同的请求.我得到一堆 HTML 代码,上面写着reddit.com: page not found".所以我假设我的 URL 有问题.但我使用的 URL 是 Reddit API 中指定的方式.

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 route 只接受 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆