Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python刷新请求和json_Python_Python Requests - Fatal编程技术网

Python刷新请求和json

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)

我有一个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)
     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()
    方法来解析它(就像您在代码中使用的那样)。