尝试使用 reddit api 和 python 进行身份验证时出现 401 错误 3

401 error when trying to authenticate with reddit api and python 3

我正在尝试使用 python 3 脚本 不使用 PRAW 或任何其他包装器进行身份验证。 reddit 的官方文档和我搜索到的内容都参考了 python 2 的 urllib utils。 This 是我用来编写代码的指南。

我在我的 reddit 个人资料中设置了脚本应用程序的应用程序配置。从中提取 app_passwordapp_id。我还使用我的 reddit 帐户凭据 user_iduser_psw,以便按照之前链接的指南中显示的进行身份验证。

这是我的代码:

import urllib.request as request
import urllib.parse as parse

pman = request.HTTPPasswordMgrWithDefaultRealm()
pman.add_password(None, "https://reddit.com",
                                  app_id,
                                  app_password)
handler = request.HTTPBasicAuthHandler(pman)
opener = request.build_opener(handler)
request.install_opener(opener)

        # headers
        d = {"grant_type": "password",
             "username": user_id,
             "password": user_pass}
        post_data = parse.urlencode(d).encode("utf-8")

        headers = {"User-Agent": "QuickParsingScript/0.1 by user_id"}

response = request.Request("https://reddit.com/api/v1/access_token",
                                   data=post_data, headers=headers)

request.urlopen(response) # urllib.error.HTTPError: HTTP Error 401: Unauthorized

我注意到在 python 2 urllib 中你可以 POST 使用字典,但是在 p3 的 Request 中你有以下限制:

The supported object types include bytes, file-like objects, and iterables.

我正在使用 urllib.parse.urlencode(),因为我发现一个 SO 正在谈论将 http auth 调用和一般 urllib 操作从 p2 代码库移动到 p3 代码库。所以这可能是一个编码问题?我还考虑过使用 "https://reddit.com" 作为 uri 的密码管理器使我的请求无效,但我不知道如何检查根本原因是否来自那里。

Try "https://www.reddit.com" and "https://www.reddit.com/api/v1/access_token", respectively. I believe reddit returns 301 redirect for your request.

已在 r/redditdev 上回答。