如何使用RedditAPI交换访问令牌的代码

2024-04-23 13:36:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我相信这是一个更广泛的问题,不仅仅适用于Reddit,但目前我正试图用代码交换用户访问令牌,但我不了解如何实现以下步骤:

https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token

If you didn't get an error and the state value checks out, you may then make a POST request with code to the following URL to retrieve your access token:

https://www.reddit.com/api/v1/access_token

Include the following information in your POST data (NOT as part of the URL)

grant_type=authorization_code&code=CODE&redirect_uri=URI

好吧,我做的是:

headers = {
     CLIENT_ID: CLIENT_SECRET,
    }
r = requests.post(
    url="https://www.reddit.com/api/v1/access_token",
    data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:5000/callback"
      },
    headers=headers
  )

我认为我的标题失败了,我收到了一个429错误,我认为我不知道如何正确排列标题,因为上面的链接中没有明确解释

The "user" is the client_id. The "password" for confidential clients is the client_secret. The "password" for non-confidential clients (installed apps) is an empty string.

CLIENT_IDCLIENT_SECRET显然是变量,它们是我的Reddit应用程序开发凭据

编辑:

我想出了这个,虽然很恶心,但似乎有效

headers = {
        "User-Agent": "MyApp v1.0",
        "Authorization": "Basic " + str(base64.b64encode(str.encode(f"{CLIENT_ID}:{CLIENT_SECRET}")))[2:-1],
    }

有没有更干净的方法来写


Tags: thehttpscomclienttokenyouidsecret
1条回答
网友
1楼 · 发布于 2024-04-23 13:36:40

最终答案,在Python的请求中使用内置方法:

client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)

r = requests.post(
    url="https://www.example.com/api/v1/access_token",
    auth=client_auth,
    data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:5000/callback"
    },
    headers={
        "User-Agent": "MyApp v1.0",
    }
)

相关问题 更多 >