我正在尝试制作一个小功能,通过 Brython(浏览器 Python)从 Spotify 的 API 获得响应,以实现更大的项目。
问题是,当我尝试获取时localStorage['apiResponse']
它似乎不起作用,因为似乎 Python 不会等待on_complete
完成并继续执行 main 函数,而不用担心 localStorage 现在是空的(这导致我得到一个空字符串而不是 API 响应。
我尝试了很多东西,比如set_timeout()
or aio.sleep
(在异步函数中),但它们都没有等待执行结束并继续执行程序的其余部分。
也while
循环冻结浏览器......(如this question所述)
from browser import ajax #to make requests
from browser.local_storage import storage as localStorage #to access HTML5 Local Storage
import json #to convert a json-like string into a Python Dict
#Request to the API
def on_complete(req):
if req.status==200 or req.status==0:
localStorage['apiResponse'] = req.text
else:
print("An error occured while asking Spotify for data")
def apiRequest(requestUrl, requestMethod):
req = ajax.ajax()
req.bind('complete', on_complete)
req.open(requestMethod, requestUrl, True)
req.set_header('Authorization', localStorage['header'])
req.send()
localStorage['header']
对于那些想知道的人,我有一个带有我的令牌的标题。
问题不是来自对 API 的请求,因为我可以在 Chrome DevTools 的“网络”选项卡中看到该请求正在运行。
Python 3 和 Brython 3.8.7