Python刷新请求和json
我有一个python程序,可以从API获取数据。此数据每隔几分钟更改一次。程序当前运行时没有任何问题,除了在多个位置调用的“我的刷新”函数 示例代码:Python刷新请求和json,python,python-requests,Python,Python Requests,我有一个python程序,可以从API获取数据。此数据每隔几分钟更改一次。程序当前运行时没有任何问题,除了在多个位置调用的“我的刷新”函数 示例代码: 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)
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文件调用它 在
refresh()
函数中使用的data
变量不是您创建的全局变量,而是在函数外部无法访问的局部变量
要在函数外部使用该变量,您可以在此处执行两项操作:
refresh()
函数以返回新数据:
def refresh_data():
resp = requests.get(url)
data = resp.json()
return data
while True:
print(data)
data = refresh_data()
数据全局:
def refresh_data():
global data
resp = requests.get(url)
data = resp.json()
while True:
print(data)
refresh_data()
我建议您使用第一种解决方案,因为。您的
数据
对象是在全局范围内定义的,但当您从函数中为其赋值时,会创建一个新的局部变量,使全局范围的变量黯然失色。您需要指定要分配给全局变量的事实,如下所示:
def refresh_data():
global data
resp = requests.get(url)
data = resp.json()
您可能需要在
refresh\u data
内部定义global data
,作为旁注,您不需要导入json
模块来解析json响应requests
具有内置的.json()
方法来解析它(就像您在代码中使用的那样)。