使用aiohttp的异步Python接口访问Spotify API
项目描述
使用aiohttp的异步Python接口访问Spotify API。
注意:这是alpha软件。使用风险自负。
安装
要安装,请使用pip
python -m pip install aiohttp_spotify
最好同时安装并使用aiohttp-session。
使用方法
要将OAuth流程添加到您的应用程序中
from aiohttp import web
import aiohttp_spotify
async def handle_auth(request: web.Request, auth: aiohttp_spotify.SpotifyAuth):
# Store the `auth` object for use later
app = web.Application()
app["spotify_app"] = aiohttp_spotify.spotify_app(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
handle_auth=handle_auth,
)
app.add_subapp("/spotify", app["spotify_app"])
然后您可以按照以下方式调用API
from aiohttp import ClientSession
async def call_api(request: web.Request) -> web.Response:
async with ClientSession() as session:
response = app["spotify_app"]["spotify_client"].request(
session, auth, "/me"
)
# The auth object will be updated as tokens expire so you should
# update this however you have it stored:
if response.auth_changed:
await handle_auth(request, response.auth)
return web.json_request(response.json())
其中 auth
是上面的 SpotifyAuth
对象。
请参阅示例目录以获取更完整的示例。