使用 Python 从重定向目标获取 URL

Fetching URL from a redirected target using Python

我正在构建一个 Twitch 聊天机器人,使用 Spotipy 库集成一些 Spotify 功能。

实施背后的目标是实现机器人的全自动 Spotipfy API 身份验证。

Spotify APISpotipy 库 是如何工作的,首先需要授权令牌才能执行任何操作在 Spotify 端。所以这就是为什么,每当机器人最初 运行 在我的 VPS 上时,它会提示我从控制台复制一个 URL,在浏览器上找到它以等待它的重定向并粘贴在控制台上,重定向的 URL 包括所需的令牌。这就是身份验证对象检索令牌数据的方式。

为了自动化这个过程,我已经看到了几个通过 Flask 或 Django 的解决方案。

Django 实现对我很有用,因为我在同一个 VPS 上也有 Django 环境处于活动状态,除了我的 Twitch 聊天时 Python 2.7 上的 Django 环境 运行s -bot 运行s 在单独的 Python 3.6 环境中。因此,我想将它们分开,除非没有办法在不通过 Django、Flask 或任何其他网络框架监听重定向的情况下实现这种自动化。不幸的是,我的机器人只能 运行 Python 3.6 或更高。

我特别好奇是否有任何内置函数或轻量级库来处理此类操作。

我用来获取 Spotify 授权令牌的函数是:

def fetchSpotiToken():
global spotiToken, spoti
spotiToken = spotifyAuth.get_cached_token()
if not spotiToken:
    spAuthURL = spotifyAuth.get_authorize_url()
    print(spAuthURL)
    # Prints the URL that Spotify API will redirect to
    authResp = input("Enter URL")
    # Console user is expected to visit the URL and submit the new redirected URL on console
    respCode = spotifyAuth.parse_response_code(authResp)
    spotiToken = spotifyAuth.get_access_token(respCode)
elif spotifyAuth.is_token_expired(spotifyAuth.get_cached_token()):
    spotiToken = spotifyAuth.refresh_access_token(spotiToken["refresh_token"])
spoti = spotipy.Spotify(auth=spotiToken["access_token"])
return [spotiToken, spoti]

PS: 我只开发了 Python 几个星期,即使在完成之后一些研究,我无法以我需要的方式找到解决这个问题的方法。我不确定是否有可能以这种方式实现。所以,如果那是不可能的,请原谅我缺乏知识。

我自己找到了解决方案。

看来 requests 很适合这个例子。

以下代码片段现在可以完美运行。

def tryFetchSpotiToken():
    global spotiToken, spoti
    try:
        spotiToken = spotifyAuth.get_cached_token()
    except:
        if not spotiToken:
            spAuthURL = spotifyAuth.get_authorize_url()
            htReq = requests.get(spAuthURL)
            htRed = htReq.url
            respCode = spotifyAuth.parse_response_code(htRed)
            spotiToken = spotifyAuth.get_access_token(respCode)
        elif spotifyAuth.is_token_expired(spotifyAuth.get_cached_token()):
            spotiToken = spotifyAuth.refresh_access_token(spotiToken["refresh_token"])
    spoti = spotipy.Spotify(auth=spotiToken["access_token"])