我该怎么关门urllib.urlopenpython中的连接

2024-09-28 22:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从URL读取的python代码。在

 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"]

我使用上下文库docshttps://docs.python.org/2/library/contextlib.html关闭python连接。但是我在执行时得到了以下错误。在

^{pr2}$

我做错了什么。我需要一种方法来关闭连接,如果有什么不好的事情发生或如果我结束了它。在


Tags: 代码selfnonejsonurlifisresponse
1条回答
网友
1楼 · 发布于 2024-09-28 22:19:17

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

发生错误的原因是:引用@Nonnib:

json.load returns the object you need. You are probably looking for: response_dict = json.load(response) and then return response_dict["data"]["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" 

这样,with块将始终正常执行,并在完成后关闭连接

相关问题 更多 >