2012-04-26 93 views
0

以下Python腳本正常工作:如何重新使用python Http連接?

#!/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連接來提高性能,我該如何解決這個問題?

在此先感謝!

+0

丹是有可能的Apache或Web服務器在下一個循環之前刷新連接?我知道這是非常previlant防止DDoS的網絡服務器..可能會有趣的看看,如果你在那裏得到一個重置數據包,並在那裏需要每次打開.. – dc5553 2012-04-26 08:53:00

+0

哈哈,我知道如何解決它。只需刪除字符串中的新行字符('\ n')即可。它工作正常! – Dan 2012-04-26 09:00:45

回答

0

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