2014-11-04 242 views
0

我有一個從URL讀取的python代碼。如何關閉python中的urllib.urlopen連接

def submitTest(self,url): 
    response = None 
    if url is not None: 
     wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL" 
     with closing(urllib.urlopen(wptUrl)) as response: 
      json.load(response) 
      return response["data"]["testId"] 

我使用上下文庫docs https://docs.python.org/2/library/contextlib.html來關閉python連接。但是,然後在執行時出現以下錯誤。

Traceback (most recent call last): 
File "webPageTestUtils.py", line 59, in <module> 
main() 
File "webPageTestUtils.py", line 56, in main 
print webPageTestProcessor.submitTest("www.amazon.com") 
File "webPageTestUtils.py", line 27, in submitTest 
return response["data"]["testId"] 
AttributeError: addinfourl instance has no attribute '__getitem__' 

我在做什麼錯在這裏。我需要一種方式來關閉連接,如果發生了不好的事情或者我已經完成了。

+0

可能重複關閉連接(HTTP [我要調用close()後了urllib.urlopen()?]://計算器。 COM /問題/ 1522 636/should-i-call-close-after-urllib-urlopen) – 2014-11-04 11:41:47

回答

0

我在做什麼錯在這裏?
發生了未捕獲的錯誤。

的出錯原因:引自@Nonnib:

json.load返回你所需要的對象。您可能正在尋找: response_dict = json.load(響應),然後返回 response_dict [ 「數據」] [ 「testId」]

可能的解決辦法:
捕捉可能出現的錯誤,並返回相應的結果

def submitTest(self,url): 
    response = None 
    if url is not None: 
     wptUrl = WebPageTestConfigUtils.getConfigValue('runTestURL')+"?f=json&url="+url+"&runs=3&video=1&web10=0&fvonly=1&mv=1&private=1&location=us_east_wptdriver:Chrome.DSL" 
     with closing(urllib.urlopen(wptUrl)) as response: 
      json.load(response) 
      try: 
       return response["data"]["testId"] 
      except AttributeError: 
       return "an AttributeError occured" # or return something else, up to you 
      except: 
       return "an error occured" 

這樣,用塊將保持正常運行,當它完成的

+0

不,但爲什麼錯誤發生在第一位 – station 2014-11-04 11:47:01

+0

因爲'response'不是字典 – 2014-11-04 11:47:56

+0

但是如果我使用json.load (urllib.urlopen(wptUrl)) – station 2014-11-04 11:49:07