test for python urllib

 1 #!/usr/bin/python
 2 
 3 import urllib2
 4 import time
 5 import logging
 6 import threading
 7 
 8 succCount = 0
 9 failCount = 0
10 IP = '127.0.0.1'
11 port = '9997'
12 postUrl = "http://%s:%s/" % (IP, port)
13 HTTP_POST_HEADERS = {'Content-Type': 'text/xml'}
14 
15 content = ' '
16 
17 logging.basicConfig(level=logging.INFO,
18                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
19                     filename='myapp.log',
20                     filemode='w')
21 
22 def  doPost1(postUrl,postHeaders,postData = None):
23     global  succCount,failCount
24     postReq = urllib2.Request(url=postUrl, headers=postHeaders, data=postData)
25     try:
26         response = urllib2.urlopen(postReq, timeout=3)
27     except urllib2.HTTPError,e:
28         failCount += 1
29         logging.debug("catch HTTPError")
30         logging.error("The server couldn\'t fulfill the request")
31         logging.error("Error code: %d",e.code)
32         logging.error("Error reason: %s",e.reason)
33     except urllib2.URLError,e:
34         failCount += 1
35         logging.debug("catch URLError")
36         logging.error("We failed to reach a server")
37         logging.error("Reason: %s", e.reason)
38     else:
39         succCount += 1
40         logging.debug("success to recv response")
41         logging.info("response content =%s", response.read())
42         logging.info("response code =%s", response.getcode())
43         logging.info("contentType =%s" , response.info().getheader("Content-Type"))
44         logging.info("response url =%s", response.geturl())
45         logging.info("response info =\n%s", response.info())
46 
47 def doPost2(postUrl,postHeaders,postData):
48     for j in range(0, 1):
49         doPost1(postUrl,postHeaders,postData)
50         time.sleep(0.001)
51 
52 if __name__ == "__main__":
53 
54     logging.info('begin test')
55 
56     threadinggroup = []
57     for i in range(0, 1):
58         tt = threading.Thread(target = doPost2,args = (postUrl, HTTP_POST_HEADERS,content))
59         tt.start()
60         threadinggroup.append(tt)
61 
62     for tt in threadinggroup:
63         tt.join()
64 
65     logging.info('succCount = %d ,failCount = %d',succCount,failCount)

 


posted @ 2017-08-14 09:50  cicero  阅读(169)  评论(0编辑  收藏  举报