nob*_*ody 5 python connection ddos urllib
我使用urllib2创建了一个程序,它在网络上建立了很多连接.我注意到最终这可能是DDoS值得的; 我想知道在我完成业务以防止这种攻击之后如何关闭每个连接.
我用来打开连接的代码是:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
Run Code Online (Sandbox Code Playgroud)
我假设您正在使用该urlopen()功能打开它们.其文件说明:
此函数返回一个类似文件的对象,其中包含两个方法:
作为一个类文件对象,它将有一个close你可以调用的方法:
connection = urllib2.urlopen(url)
# Do cool stuff in here.
connection.close()
Run Code Online (Sandbox Code Playgroud)
更新:使用您添加到问题中的代码:
>>> 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
Run Code Online (Sandbox Code Playgroud)
所以该close()方法存在并实际做了一些事情:
>>> r.close()
>>> r.read()
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
你的问题非常模糊。
但这里是使用后关闭连接的示例:
f = urllib2.urlopen(req)
f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)