0

I have a python code that reads from a URL.

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

I used the context lib docs https://docs.python.org/2/library/contextlib.html to close the python connection. But then I get the following error on executing.

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__'

What I am doing wrong here . I need a way to close the connection if something bad happens or if I am done with it.

station
  • 6,715
  • 14
  • 55
  • 89
  • possible duplicate of [should I call close() after urllib.urlopen()?](http://stackoverflow.com/questions/1522636/should-i-call-close-after-urllib-urlopen) –  Nov 04 '14 at 11:41

1 Answers1

0

What I am doing wrong here?
An error occurred that was not caught.

The error occured because: quote from @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"]

Possible solution:
Catch possible errors and return the appropriate result

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" 

This way the with block will always execute normally and close the connection when it's done

Tim
  • 41,901
  • 18
  • 127
  • 145