Python刷新请求和json

时间:2018-04-02 16:34:28

标签: python python-requests

我有一个从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文件中调用它。

2 个答案:

答案 0 :(得分:2)

您在data函数中使用的refresh()变量不是您创建的全局变量,而是在函数外部无法访问的局部变量。

要在函数外部使用该变量,您可以在此处执行以下操作:

  1. 更改refresh()功能以返回新数据:

    def refresh_data():
        resp = requests.get(url)
        data = resp.json()
        return data
    
    while True:
        print(data)
        data = refresh_data()
    
  2. 将变量data设为全局:

    def refresh_data():
        global data
        resp = requests.get(url)
        data = resp.json()
    
    while True:
        print(data)
        refresh_data()
    
  3. 我建议您使用第一个解决方案,using global variables is not at all a good practice

答案 1 :(得分:1)

您的data对象是在全局范围内定义的,但是当您从函数中分配它时,会创建一个新的局部变量,该变量会覆盖全局范围。您需要指定您想要分配给全局变量的事实:

def refresh_data():
     global data
     resp = requests.get(url)
     data = resp.json()