python urllib2的301/302重定向处理

用惯了[url='http://pypi.python.org/pypi/requests/1.0.2']requests[/url],python的标准库倒是很久不碰。以致这次用urllib2稍微折腾了下。

记得301/302是自动跳转的,结果我这直接异常,参考[url='http://woodpecker.org.cn/diveintopython/http_web_services/redirects.html']这里[/url],简单重新实现了下重定向,结果仍然杯具。只能追源码:

def redirect_request(self, req, fp, code, msg, headers, newurl):
m = req.get_method()
if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
or code in (301, 302, 303) and m == "POST"):
# Strictly (according to RFC 2616), 301 or 302 in response
# to a POST MUST NOT cause a redirection without confirmation
# from the user (of urllib2, in this case). In practice,
# essentially all clients do redirect in this case, so we
# do the same.
# be conciliant with URIs containing a space
newurl = newurl.replace(' ', '%20')
newheaders = dict((k,v) for k,v in req.headers.items()
if k.lower() not in ("content-length", "content-type")
)
return Request(newurl,
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise HTTPError(req.get_full_url(), code, msg, headers, fp)


感情是只支持post/get/head 方法,咱这用了put,额...(怎么用put,[url='http://zhuoqiang.me/a/python-urllib2-usage']参看这里[/url])
只能把redirect_request一起覆盖了,什么put/delete统统加上,齐活~

另,才发现python2.6+的版本,urlopen竟然已支持timeout传参,幸而一直用的requests,才没有傻兮兮的一路setdefault :D
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值