Python | 多进程
一、简介
Python标准库中有很多实用的工具类,但是在具体使用时,标准库文档上对使用细节描述的并不清楚,比如urllib2这个HTTP客户端库。这里总结了一些urllib2的使用细节。
- Proxy设置
- Timeout设置
- 在HTTP Request中加入特定的Header
- Redirect
- Cookie
- 使用HTTP的PUT和DELETE方法
- 得到HTTP的返回码
- Debug Log
二、Proxy设置
urllib2默认会使用环境变量http_proxy来设置HTTP Proxy。如果想在程序中明确控制Proxy而不受环境变量的影响,可以使用下面的方式
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2enable_proxy = Trueproxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})null_proxy_handler = urllib2.ProxyHandler({})if enable_proxy: opener = urllib2.build_opener(proxy_handler)else: opener = urllib2.build_opener(null_proxy_handler)urllib2.install_opener(opener)
这里要注意的一个细节,使用urllib2.install_opener()会设置urllib2的全局opener。这样后面的使用会很方便,但不能做更细粒度的控制,比如想在程序中使用两个不同的Proxy设置等。比较好的做法是不使用install_opener去更改全局的设置,而只是直接调用opener的open方法代替全局的urlopen方法。
三、Timeout设置
在老版Python中,urllib2的API并没有暴露Timeout的设置,要设置Timeout值,只能更改Socket的全局 Timeout 值。
#!/usr/bin/python# _*_ coding=utf-8 _*_import socketimport urllib2socket.setdefaulttimeout(10) # 10 秒钟后超时urllib2.socket.setdefaulttimeout(10) # 另一种方式
在Python 2.6以后,超时可以通过urllib2.urlopen()的timeout 参数直接设置。
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2response = urllib2.urlopen('http://www.google.com', timeout=10)
四、在HTTP Request中加入特定的Header
要加入header,需要使用Request对象:
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2request = urllib2.Request(uri)request.add_header('User-Agent', 'fake-client')response = urllib2.urlopen(request)
对有些header要特别留意,服务器会针对这些header做检查,在使用服务器提供的RESTful或SOAP服务时,Content-Type设置错误会导致服务器拒绝服务
- User-Agent: 有些服务器或Proxy会通过该值来判断是否是浏览器发出的请求
- Content-Type: 在使用REST接口时,服务器会检查该值,用来确定HTTP Body中的内容该怎样解析。常见的取值有:
application/xml:在XML RPC,如RESTful/SOAP调用时使用application/json:在JSON RPC调用时使用application/x-www-form-urlencoded:浏览器提交Web表单时使用
五、Redirect
urllib2默认情况下会针对HTTP 3XX返回码自动进行redirect动作,无需人工配置。要检测是否发生了redirect动作,只要检查一下Response的URL和Request的URL是否一致就可以了。
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2response = urllib2.urlopen('http://www.google.cn')redirected = response.geturl() == 'http://www.google.cn'
如果不想自动redirect,除了使用更低层次的httplib库之外,还可以自定义HTTPRedirectHandler类。
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2class RedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): pass def http_error_302(self, req, fp, code, msg, headers): passopener = urllib2.build_opener(RedirectHandler)opener.open('http://www.google.cn')
六、Cookie
urllib2对Cookie的处理也是自动的。如果需要得到某个Cookie项的值,可以这么做:
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2import cookielibcookie = cookielib.CookieJar()opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))response = opener.open('http://www.google.com')for item in cookie: if item.name == 'some_cookie_item_name': print item.value
七、使用HTTP的PUT和DELETE方法
urllib2只支持HTTP的GET和POST方法,如果要使用HTTP PUT和DELETE,只能使用比较低层的httplib库。虽然如此,我们还是能通过下面的方式,使urllib2能够发出PUT或DELETE的请求:
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2request = urllib2.Request(uri, data=data)request.get_method = lambda: 'PUT' # or 'DELETE'response = urllib2.urlopen(request)
这种做法虽然属于Hack的方式,但实际使用起来也没什么问题。
八、得到HTTP的返回码
对于200 OK来说,只要使用urlopen返回的response对象的getcode()方法就可以得到HTTP的返回码。但对其它返回码来说,urlopen会抛出异常。这时候,就要检查异常对象的code属性了:
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2try: response = urllib2.urlopen('http://restrict.web.com')except urllib2.HTTPError, e: print e.code
九、Debug Log
使用urllib2时,可以通过下面的方法把debug Log打开,这样收发包的内容就会在屏幕上打印出来,方便调试,有时可以省去抓包的工作
#!/usr/bin/python# _*_ coding=utf-8 _*_import urllib2httpHandler = urllib2.HTTPHandler(debuglevel=1)httpsHandler = urllib2.HTTPSHandler(debuglevel=1)opener = urllib2.build_opener(httpHandler, httpsHandler)urllib2.install_opener(opener)response = urllib2.urlopen('http://www.google.com')