如何“保活”? python 中的 cookielib 和 httplib ?
在 python 中,我使用 httplib 因为它“保持”http 连接(与 urllib(2) 相反)。 现在,我想将 cookielib 与 httplib 一起使用,但它们似乎互相讨厌! (无法将它们连接在一起)。
有谁知道这个问题的解决方案?
In python, I'm using httplib because it "keep-alive" the http connection (as oppose to urllib(2)). Now, I want to use cookielib with httplib but they seem to hate each other!! (no way to interface them together).
Does anyone know of a solution to that problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
支持 keep-alive 的 urllib2 HTTP 处理程序
HTTP handler for urllib2 that supports keep-alive
您应该考虑使用
Requests
库,而不是在您必须重构代码的最早机会。 同时;黑客警报! :)
我会采用其他建议的方式,但我已经做了一个 hack(尽管出于不同的原因),它确实在 httplib 和 cookielib。
我所做的是使用最少的所需方法集创建一个假的
HTTPRequest
,以便CookieJar
会识别它并根据需要处理 cookie。 我使用了那个假请求对象,设置了 cookielib 所需的所有数据。以下是该类的代码:
请注意,该类仅支持 HTTPS 协议(我目前需要的全部)。
使用此类的代码是(请注意另一个使响应与 cookielib 兼容的技巧):
You should consider using the
Requests
library instead at the earliest chance you have to refactor your code. In the mean time;HACK ALERT! :)
I'd go other suggested way, but I've done a hack (done for different reasons though), which does create an interface between httplib and cookielib.
What I did was creating a fake
HTTPRequest
with minimal required set of methods, so thatCookieJar
would recognize it and process cookies as needed. I've used that fake request object, setting all the data needed for cookielib.Here is the code of the class:
Please note, the class has support for HTTPS protocol only (all I needed at the moment).
The code, which used this class was (please note another hack to make response compatible with cookielib):