httplib urllib urllib2 pycurl 比较
最近网上面试看到了有关这方面的问题,由于近两个月这些库或多或少都用过,现在根据自己的经验和网上介绍来总结一下。
httplib
实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。所以效率要比这两个库高一点。http://www.cnblogs.com/beiyeren/p/4046139.html
#-*- coding:utf-8 –*- from urlparse import urlparse import httplib from hds.utils import get_logger import json from exception import HTTPException class HttpClienttMonitor(object): def __init__(self, logger=None): self.logger = logger or get_logger("HttpClienttMonitor") def send_request_with_body(self, url, content, method, token): self.logger.info("url: "+url) self.logger.info(method+ ": "+ str(content)) assert len(url) != 0,"url is empty" assert len(token) !=0,"token is empty" o = urlparse(url) content = json.dumps(content).encode('utf-8') headers = {"Content-Type":"application/json"} headers["Authorization"] = token httpClient = httplib.HTTPConnection(o.hostname, o.port) try: httpClient.set_debuglevel(0) httpClient.request(method, o.path+"?"+o.query, content, headers) response = httpClient.getresponse() if not response: return "No response from httpClient" self.logger.info("status: "+str(response.status)) self.logger.info("reason: " + response.reason) return response.status except Exception as e: raise HTTPException(e) finally: if httpClient: httpClient.close() class HTTP_REQUEST_METHOD(): get = "GET" post = "POST" delete = "DELETE" put = "PUT" patch = "PATCH"
urllib2
can accept aRequest
object to set the headers for a URL request,urllib
accepts only a URL. That means, you cannot masquerade your User Agent string etc.
urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以伪装你的User Agent字符串等。
urllib
provides theurlencode
method which is used for the generation of GET query strings,urllib2
doesn't have such a function. This is one of the reasons whyurllib
is often used along withurllib2
.
urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。
pycurl
关于python网络编程,使用urllib与服务器通信时,客户端的数据是添加到Head里面通过URL,发送到服务器端,urllib包实现客户端上传文件时,会出现死掉的状态(实际上是超时设置问题)。
Pycurl包是一个libcurl的Python接口,它是由C语言编写的。与urllib相比,它的速度要快很多。
Libcurl 是一个支持FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 和 LDAP的客户端URL传输库.libcurl也支持HTTPS认证,HTTP POST,HTTP PUT,FTP上传,代理,Cookies,基本身份验证,FTP文件断点继传,HTTP代理通道等等。
class CurlTest(object): def post(self): provisionContent["metadata"] = metadata b = StringIO.StringIO() c = pycurl.Curl() c.setopt(pycurl.VERBOSE, 1) c.setopt(pycurl.URL, remoteServiceURL) c.setopt(pycurl.HTTPHEADER, ["Accept: application/json", "Content-Type: application/json" ])
c.setopt(pycurl.WRITEFUNCTION, b.write) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) c.setopt(c.POSTFIELDS, json.dumps(provisionContent)) c.perform() print c.getinfo(c.HTTP_CODE), c.getinfo(c.EFFECTIVE_URL), c.POSTFIELDS print b.getvalue() self.response = eval(b.getvalue()) b.close() c.close()
其中c.setopt(pycurl.WRITEFUNCTION, b.write) #把StringIO的写函数注册到pycurl的WRITEFUNCTION中,即pycurl所有获取的内容都写入到StringIO中,如果没有这一句,pycurl就会把所有的内容在默认的输出器中输出
pycurl常用操作如下:
pycurl.Curl() #创建一个pycurl对象的方法
pycurl.Curl(pycurl.URL, http://www.google.com.hk) #设置要访问的URL
pycurl.Curl().setopt(pycurl.MAXREDIRS, 5) #设置最大重定向次数
pycurl.Curl().setopt(pycurl.CONNECTTIMEOUT, 60)
pycurl.Curl().setopt(pycurl.TIMEOUT, 300) #连接超时设置
pycurl.Curl().setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)") #模拟浏览器
pycurl.Curl().perform() #服务器端返回的信息
pycurl.Curl().getinfo(pycurl.HTTP_CODE) #查看HTTP的状态 类似urllib中status属性
pycurl.NAMELOOKUP_TIME 域名解析时间
pycurl.CONNECT_TIME 远程服务器连接时间
pycurl.PRETRANSFER_TIME 连接上后到开始传输时的时间
pycurl.STARTTRANSFER_TIME 接收到第一个字节的时间
pycurl.TOTAL_TIME 上一请求总的时间
pycurl.REDIRECT_TIME 如果存在转向的话,花费的时间
pycurl.EFFECTIVE_URL
pycurl.HTTP_CODE HTTP 响应代码
pycurl.REDIRECT_COUNT 重定向的次数
pycurl.SIZE_UPLOAD 上传的数据大小
pycurl.SIZE_DOWNLOAD 下载的数据大小
pycurl.SPEED_UPLOAD 上传速度
pycurl.HEADER_SIZE 头部大小
pycurl.REQUEST_SIZE 请求大小
pycurl.CONTENT_LENGTH_DOWNLOAD 下载内容长度
pycurl.CONTENT_LENGTH_UPLOAD 上传内容长度
pycurl.CONTENT_TYPE 内容的类型
pycurl.RESPONSE_CODE 响应代码
pycurl.SPEED_DOWNLOAD 下载速度
pycurl.SSL_VERIFYRESULT
pycurl.INFO_FILETIME 文件的时间信息
pycurl.HTTP_CONNECTCODE HTTP 连接代码
pycurl.HTTPAUTH_AVAIL
pycurl.PROXYAUTH_AVAIL
pycurl.OS_ERRNO
pycurl.NUM_CONNECTS
pycurl.SSL_ENGINES
pycurl.INFO_COOKIELIST
pycurl.LASTSOCKET
pycurl.FTP_ENTRY_PATH