How to close urllib2 connection?

I created a program using urllib2 that makes many connections over the network. I noticed that in the long run it might be worthy of DDoS; I would like to know how to close each connection after I have done my business to prevent such an attack.

The code I use to open the connection is:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
+5
source share
3 answers

I assume that you open them with a function urlopen(). Its documentation states:

This function returns a file-like object with two additional methods:

- , close, :

connection = urllib2.urlopen(url)
# Do cool stuff in here.
connection.close()

: , :

>>> import urllib2
>>> import cookielib
>>> cj = cookielib.CookieJar()
>>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
>>> r = opener.open("http://www.python.org")
>>> html = r.read()
>>> r.close??
Type:  instancemethod
Base Class: <type 'instancemethod'>
String Form: <bound method addinfourl.close of <addinfourl at 150857644 whose fp = <socket._fileobject object at 0x8fd48ec>>>
Namespace: Interactive
File:  /usr/lib/python2.6/urllib.py
Definition: r.close(self)
Source:
    def close(self):
        self.read = None
        self.readline = None
        self.readlines = None
        self.fileno = None
        if self.fp: self.fp.close()
        self.fp = None

, close() - :

>>> r.close()
>>> r.read()
------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
TypeError: 'NoneType' object is not callable
+6

.

:

f = urllib2.urlopen(req)
f.read()
f.close()
+2

The socket connection automatically closes after receiving a response. This way you are not explicitly closing the urllopen object, this happens automatically at the socket level.

0
source

All Articles