如何关闭python中的urllib.urlopen连接

问题描述:

我有一个从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

我在做什么错在这里?
发生了未捕获的错误。

的出错原因:引自@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