【问题标题】:401 error when trying to authenticate with reddit api and python 3尝试使用 reddit api 和 python 3 进行身份验证时出现 401 错误
【发布时间】:2017-10-23 11:07:25
【问题描述】:

我正在尝试使用 python 3 脚本没有 PRAW 或任何其他包装器进行身份验证。 reddit 的官方文档和我搜索到的内容都参考了 python 2 的 urllib 实用程序。 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 中,您有以下限制:

支持的对象类型包括字节、类文件对象和可迭代对象。

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

【问题讨论】:

    标签: python-3.x oauth reddit


    【解决方案1】:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 2018-10-09
      • 1970-01-01
      • 2019-12-21
      • 2017-07-22
      • 2021-05-24
      • 2016-03-22
      相关资源
      最近更新 更多