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

2016-10-12 09:52:13 +08:00
 zong400

代码

...
>>> 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 的,怎么搞?

7577 次点击
所在节点    程序员
18 条回复
upczww
2016-10-12 09:58:21 +08:00
你应该试试 requests.
HTTP for Humans.
shadowmydx
2016-10-12 10:30:45 +08:00
这个很简单,这个 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")
zong400
2016-10-12 10:38:38 +08:00
@shadowmydx 可以了,但是为什么要额外加 req.headers = h
zong400
2016-10-12 10:52:04 +08:00
@upczww 很好 requests 更简洁
ThinkCat
2016-10-12 10:55:19 +08:00
你应该用下 requests , 这个真心好用
ryd994
2016-10-12 11:03:42 +08:00
因为 HTTP 协议本来就规定 header 不分大小写: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
ubear1991
2016-10-12 13:16:26 +08:00
用 requests
tumbzzc
2016-10-12 13:43:51 +08:00
看到那么多人推荐 requests ,我就放心了。
还是用 requests 吧,妥妥的
zong400
2016-10-12 14:09:31 +08:00
已用 requests ,妥妥的
jixiangqd
2016-10-12 15:10:41 +08:00
试过 requests 并发性能不是很好。。。不知道为什么
qweweretrt515
2016-10-12 19:37:15 +08:00
requests 啊
sherwinkoo
2016-10-12 19:53:46 +08:00
@jixiangqd 你怎么测试的?
jixiangqd
2016-10-12 19:59:59 +08:00
@sherwinkoo 试过自带进程池、线程池模块、 gevent 协程:都是 urllib2 性能最好,差的还不是一点半点。不知道是不是有什么配置可以改进并发性能,没有深入研究
purrgil
2016-10-13 03:25:43 +08:00
life is short,you neet requests
purrgil
2016-10-13 03:29:56 +08:00
Life is short,you need requests.
ibigbug
2016-10-13 03:54:59 +08:00
rfc 是规定 http header 不区分大小写的,你可能无语错地方了
shadowmydx
2016-10-13 12:19:16 +08:00
@zong400 因为 urlib2 在构建 Request 对象时对你传入的参数进行了统一的处理,其中,处理 header 后,将其赋予一个成员变量 headers 。因此,你只需要重新替换掉这个成员就可以了。
chy373180
2016-10-13 13:02:08 +08:00
requests 何来的并发性能不是很好。。。

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

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

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

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

© 2021 V2EX