我有一个从API获取数据的python程序。此数据每隔几分钟更改一次。该程序当前运行,除了在多个地方调用的刷新功能外,没有任何问题。
样例代码:
import requests
import json
import time
url = 'https://api.url.com/...'
resp = requests.get(url)
data = resp.json()
def refresh_data():
resp = requests.get(url)
data = resp.json()
while True:
print(data)
#This will not refresh the response
refresh_data()
#This will refresh (But I need it in function)
#resp = requests.get(url)
#data = resp.json()
sleep(60)
我想要有关如何使刷新功能正常工作的任何建议。我将从其他函数以及其他python文件中调用它。
最佳答案
在data
函数中使用的refresh()
变量不是您创建的全局变量,而是在该函数外部无法访问的局部变量。
要在函数外使用该变量,您可以在此处做两件事:
更改refresh()
函数以返回新数据:
def refresh_data():
resp = requests.get(url)
data = resp.json()
return data
while True:
print(data)
data = refresh_data()
使变量
data
全局:def refresh_data():
global data
resp = requests.get(url)
data = resp.json()
while True:
print(data)
refresh_data()
我建议您使用第一个解决方案,如using
global
variables is not at all a good practice。