如何重用python Http连接?

时间:2012-04-26 08:45:02

标签: python http

以下python脚本可以正常工作:

#!/usr/bin/env python
import httplib, urllib
params = urllib.urlencode({'url':'xxx/xxx/0AAAUw7n6qPQ922.jpg', 'key': 'xxxx'})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/html"}
conn = httplib.HTTPConnection("xxx.test.com")
conn.request("POST", "/xx/delete", params, headers);
response = conn.getresponse()
print response.status, response.reason
data = response.read()
print data
conn.close()

但是,如果我想重复使用打开的http连接来运行更多次,则它不起作用:

#!/usr/bin/env python
import httplib, urllib
import sys

if len(sys.argv)<2:
  print "invalid input"
  sys.exit(0)

path = sys.argv[1]
f = open(path)
lines = f.readlines()
f.close()

conn = httplib.HTTPConnection("xxx.test.com")
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/html"}
for line in lines:
  if len(line) < 6:
    continue
  params = urllib.urlencode({'url': line, 'key': 'xxxx'})
  conn.request("POST", "/xx/delete", params, headers);
  response = conn.getresponse()
  print response.status, response.reason
  data = response.read()
  print data
conn.close()

返回状态为:500服务器错误

我只是想重用http连接来提高性能,我该如何解决这个问题呢?

提前致谢!

1 个答案:

答案 0 :(得分:0)

删除字符串中的换行符('\ n')。它工作正常!