我使用 urllib2 制作了一个程序,它在网络上建立了很多连接。我注意到最终这可能是 DDoS 值得的;我想知道在我完成业务后如何关闭每个连接以防止此类攻击。
我用来打开连接的代码是:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
我使用 urllib2 制作了一个程序,它在网络上建立了很多连接。我注意到最终这可能是 DDoS 值得的;我想知道在我完成业务后如何关闭每个连接以防止此类攻击。
我用来打开连接的代码是:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
我假设您正在使用该urlopen()
功能打开它们。其文档指出:
这个函数返回一个类似文件的对象,它有两个额外的方法:
作为一个类文件对象,它将有一个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
你的问题非常模糊。
但这是使用后关闭连接的示例:
f = urllib2.urlopen(req)
f.read()
f.close()
一旦获得响应,套接字连接就会自动关闭。因此,您无需显式关闭 urlopen 对象,它会在套接字级别自动发生。