Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.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:遇到超时错误时重复API请求_Python_Api_Request - Fatal编程技术网

Python:遇到超时错误时重复API请求

Python:遇到超时错误时重复API请求,python,api,request,Python,Api,Request,我通过循环遍历有限的坐标列表并将它们提供给URL,从API中检索一些数据。每隔一段时间,我的代码就会中断,因为它会遇到错误消息,而不是JSON格式的文件。换句话说,文本文件包含错误消息,而不是代码所需的字典: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <html><head> <title>504 Gateway Time-out</title> </

我通过循环遍历有限的坐标列表并将它们提供给URL,从API中检索一些数据。每隔一段时间,我的代码就会中断,因为它会遇到错误消息,而不是JSON格式的文件。换句话说,文本文件包含错误消息,而不是代码所需的字典:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>504 Gateway Time-out</title>
</head><body>
<h1>Gateway Time-out</h1>
<p>The proxy server did not receive a timely response
from the upstream server.</p>
</body></html>
它在dataparse=json.load(数据)处中断,因为它不读取json格式(JSONDECODEROR)

我正在试图找到一种方法,在发生这种情况时重复循环的这一部分(即再次尝试相同的坐标)。我怀疑我可以从文件中提取错误代码,但我不确定如何继续

非常感谢您的帮助。

应该给您和。
for Y, X in zip(col_Y, col_X):
    try:
        conn = http.client.HTTPSConnection('api.randomurl.com')
        url = URL_PATTERN.format(Y, X)
        conn.request("GET", url % params, "{body}", headers)
        response = conn.getresponse()
        data = response.read()
        f = open("output.txt", "wb")
        f.write(data)
        f.close()
        dataparse = json.loads(data)
        
        print("\n\nNIEUWE BEREKENING\n")
        routes = dataparse["reiswegen"]
        print("\nDuurtijden in ISO-notatie:\n")
        duurtijden_iso = []
        
        for route in routes:
            duurtijden_iso.append(route['duurtijd']['duurtijd'])
        print(duurtijden_iso)
        
        duurtijden_sec = []
        for duurtijd in duurtijden_iso:
            dur=isodate.parse_duration(duurtijd)
            duurtijden_sec.append(dur.total_seconds())
        print("\nDuurtijden in seconden:\n")
        print(duurtijden_sec)
        
        print("\nResultaat voor deze coördinaten:\n")
        print(str(Y) + " " + str(X) + " " + str(min(duurtijden_sec)/60))

        with open('coord_reistijd.csv', 'a', newline='') as file:
            writer = csv.writer(file)
            writer.writerow([str(Y), str(X), str(min(duurtijden_sec)/60)])
            
        conn.close()
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))