使 Spotipy 程序对用户友好

Making Spotipy program user-friendly

我使用 Spotipy 创建了一个简单的 Python 程序,它会根据用户设备中下载的曲目显示一些推荐的曲目。但是我在使程序易于使用方面遇到了一些麻烦。

首先,通过例如上传我的代码到GitHub与用户共享我的Client ID和我的Client Secret有什么问题吗?我可以将重定向 URI 用作 http://localhost/ 还是应该为我的程序创建一个网站以确保安全?在用户名字段中,它应该是要分析的帐户的用户名,也可以是任何内容,例如 "Brian Rogers"?

在身份验证部分,它在 Python 控制台中向用户显示以下消息:

User authentication requires interaction with your
    web browser. Once you enter your credentials and
    give authorization, you will be redirected to
    a url.  Paste that url you were directed to to
    complete the authorization.

Opening https://... in your browser

Enter the URL you were redirected to: 

我的问题是:由于我正在设法使用 Tkinter,如何将输入从 Tkinter 输入框重定向到 Python 控制台?

最后,身份验证令牌需要多长时间才能过期?如果是这样,如何更新它(如果可能,只有用户在第一次 运行 程序时才进入)?

在此先感谢患者!

我会一一解答您的所有问题。

is there any problem by sharing my Client ID and my Client Secret with the user by, for example, uploading my code in GitHub?

人们应该始终避免将个人凭据放入源中。如果有人滥用您的凭据,您将承担责任,因为它们是您的凭据。无论如何,我能想象到的唯一可能造成的破坏是向 Spotify 的 API 发送垃圾请求,我相信 Spotify 的 API 已经有了保护措施,如果它检测到请求垃圾邮件,它将丢弃更多请求。我已经看到一些项目通过创建用于为他们的项目生成 API 凭据的特殊帐户来放置他们的 Spotify 和 YouTube API 凭据,在他们的源代码中并推送到 GitHub 来制作工具更易于设置使用。

Can I use Redirect URI as being http://localhost/ or should I create a website for my program for securing purposes? In Username field, it should be the username of the account to be analyzed or it can be anything, like "Brian Rogers"?

由于您只是在 Spotify 上搜索相关曲目,我相信您可能不需要访问您正在使用其凭据的 Spotify 用户的个人信息。如果是这样,您可以通过使用 oauth2.SpotifyClientCredentials 授权自己来避免同时传递 username 和验证重定向 URI:

import spotipy
import spotipy.oauth2 as oauth2

credentials = oauth2.SpotifyClientCredentials(
        client_id=client_id,
        client_secret=client_secret)

token = credentials.get_access_token()
# This won't prompt for verification of Redirect URI
sp = spotipy.Spotify(auth=token)

My question is: since I'm managing to use Tkinter, how can I redirect the input from the Tkinter input box to the Python console?

如果您如上所述使用 oauth2.SpotifyClientCredentials,则不需要。

Finally, how long does the authentication token take to expire? And if so, how to renew it (if possible, so that only the user enters when they run the program for the first time)?

截至撰写本文时,令牌的有效期正好为一小时。您可以通过检查以秒为单位显示时间的 credentials.token_info["expires_in"] 的值来确认。

此外,当依赖方法已被调用但令牌已过期时,spotipy 会引发 spotipy.client.SpotifyException。因此,您可以捕获此异常并用新实例覆盖之前的 spotipy.client.Spotify 实例。至少你会做类似这样的事情:

import spotipy
import spotipy.oauth2 as oauth2

def authenticate_calls():
    credentials = oauth2.SpotifyClientCredentials(
        client_id=client_id,
        client_secret=client_secret,
    )
    token = credentials.get_access_token()
    sp = spotipy.Spotify(auth=token)
    return sp

sp = authenticate_calls()

try:
    do_something_that_needs_authentication(sp)
except spotipy.client.SpotifyException:
    sp = authenticate_calls()
    do_something_that_needs_authentication(sp)

您还可以创建一个装饰器函数,它会在令牌过期时刷新它并用它来装饰您的函数!