作为一个 python 新手,我很无语, urllib2 的 add_header 搞了一天,求助解决方法

2016 年 10 月 12 日
 ethsol

代码

...
>>> h = {"Content-Type": "application/json"}
>>> req = urllib2.Request(url,js,h)
>>> req.has_header("Content-Type")
False
>>> req.get_header("Content-type")
'application/json'

key 被 capitalize 了,我这个 header 就要 Content-Type 的,怎么搞?

8372 次点击
所在节点    程序员
18 条回复
upczww
2016 年 10 月 12 日
你应该试试 requests.
HTTP for Humans.
shadowmydx
2016 年 10 月 12 日
这个很简单,这个 header 是 Request 对象中一个叫 headers 的成员,如果一定要大写,你直接这么写就可以:
h = {"Content-Type": "application/json"}
req = urllib2.Request(url, js, headers=h)
req.headers = h
print req.has_header("Content-Type")
print req.get_header("Content-Type")
ethsol
2016 年 10 月 12 日
@shadowmydx 可以了,但是为什么要额外加 req.headers = h
ethsol
2016 年 10 月 12 日
@upczww 很好 requests 更简洁
ThinkCat
2016 年 10 月 12 日
你应该用下 requests , 这个真心好用
ryd994
2016 年 10 月 12 日
因为 HTTP 协议本来就规定 header 不分大小写: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
ubear1991
2016 年 10 月 12 日
用 requests
TKKONE
2016 年 10 月 12 日
看到那么多人推荐 requests ,我就放心了。
还是用 requests 吧,妥妥的
ethsol
2016 年 10 月 12 日
已用 requests ,妥妥的
jixiangqd
2016 年 10 月 12 日
试过 requests 并发性能不是很好。。。不知道为什么
qweweretrt515
2016 年 10 月 12 日
requests 啊
sherwinkoo
2016 年 10 月 12 日
@jixiangqd 你怎么测试的?
jixiangqd
2016 年 10 月 12 日
@sherwinkoo 试过自带进程池、线程池模块、 gevent 协程:都是 urllib2 性能最好,差的还不是一点半点。不知道是不是有什么配置可以改进并发性能,没有深入研究
purrgil
2016 年 10 月 13 日
life is short,you neet requests
purrgil
2016 年 10 月 13 日
Life is short,you need requests.
ibigbug
2016 年 10 月 13 日
rfc 是规定 http header 不区分大小写的,你可能无语错地方了
shadowmydx
2016 年 10 月 13 日
@zong400 因为 urlib2 在构建 Request 对象时对你传入的参数进行了统一的处理,其中,处理 header 后,将其赋予一个成员变量 headers 。因此,你只需要重新替换掉这个成员就可以了。
chy373180
2016 年 10 月 13 日
requests 何来的并发性能不是很好。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/312107

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX