如何关闭urllib2连接?
我使用 urllib2 编写了一个程序,可以在网络上建立大量连接。我注意到,最终这可能是值得 DDoS 攻击的;我想知道如何在完成业务后关闭每个连接以防止此类攻击。
我用来打开连接的代码是:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
I have made a program using urllib2 that makes a lot of connections across the web. I noticed that eventually that this can be DDoS worthy; I would like to know how to close down each connection after I have done my business to prevent such an attack.
The code I am using to open a connection is:
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://www.python.org)
html = r.read()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我假设您使用 urlopen() 函数打开它们。 其文档指出:
作为类文件对象,它将有一个可以调用的
close
方法:Update:使用代码您在问题中添加了:
因此
close()
方法存在并且实际上做了一些事情:I assume you are opening them with the
urlopen()
function. Its documentation states:As a file-like object, it will have a
close
method which you can call:Update: Using the code you added to your question:
So the
close()
method exists and actually does something:你的问题非常模糊。
但这里是使用后关闭连接的示例:
your question is extremely vague.
but here is an example of closing a connection after use:
一旦获得响应,套接字连接就会自动关闭。因此,您无需显式关闭 urlopen 对象,它会在套接字级别自动发生。
The socket connection closes automatically, once the response is obtained. So you don't explicitly close the urllopen object, it happens automatically at the socket level.