2017-04-11 25 views
2

我正在運行一個代碼,它從API url中獲取json數據,場景是我正在嘗試自定義異常,而URL響應沒有被提取響應顯示200仍然不提取數據)在這種情況下,代碼應該從頭開始重新執行。如果api調用失敗,重新運行執行 - [Python2.7]

代碼:

import json 
import urllib 
url = 'www.google.com' 
status = url.getcode() 
if(status != 200): 
    # re-execute the code 
data = json.load(urllib.urlopen(url)) 
if (data == null): 
    #re-execute the code 

找不到相同,同時通過互聯網

任何人可以在此幫助尋找一個合適的解決方案?

+0

有關使用一個循環是什麼?另外'null'在Python中不存在,你可以使用'data is None'或'如果不是數據'來驗證。 – lmiguelvargasf

+0

什麼是'null'? – lmiguelvargasf

回答

2

我認爲這可以幫助你,你有這麼遠的邏輯如下:

import json 
import urllib 

url = 'www.google.com' 

while True: 
    status = url.getcode() 
    if status != 200: 
     continue 
    data = json.load(urllib.urlopen(url)) 
    if not data: 
     continue 
    break 

您也可以改善它通過一點點:

import json 
import urllib 

url = 'www.google.com' 
status = url.getcode() 
data = json.load(urllib.urlopen(url)) 

while status != 200 or not data: 
    status = url.getcode() 
    data = json.load(urllib.urlopen(url)) 
0
import json 
import urllib 

URL = 'www.google.com' 

def get_data_status(url): 
    return (json.load(urllib.urlopen(url)), url.getcode()) 

while 1: 
    data, status = get_data_status(URL) 
    if data and (status==200): 
     break 

無,False,空字符串,空字典,空數組和0是假值。我不認爲你正確使用null。當Python解碼JSON時,它會將null變爲空對象,即None。

ETA:有關評論:

API是否已沒有任何數據返回的響應,因此給定的零

我有幾行後,「如果(數據執行空== null)的

確定,所以,如果你真正得到STR(空)從JSON請求回來,你要在這種情況下,以‘執行代碼幾行’:

while 1: 
    data, status = get_data_status(URL) 
    if (data!='null') and (status==200): 
     break 
    elif (data='null'): 
     print 'execute a few more lines of "null" data code' 
    elif (status!=200): 
     print 'execute a few more lines of wrong status code' 

print 'exiting while loop with good data and status 200' 
+0

這會產生兩個錯誤錯誤:1.「狀態」和「數據」未定義。 2.'null'在Python中不存在 – lmiguelvargasf

+0

是的,我抓到了前兩個,正在編輯,因爲你評論。不確定空操作的意思是什麼? – litepresence

+0

我同意你的意見。可能'null'是一個變量,但是由於我看到了通常位於文件開頭的導入內容,因此我假定有人問過使用Java的經驗。 – lmiguelvargasf

相關問題