refresh_nginx_cache.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding: utf-8
  2. import urllib2
  3. from refresh_config import host_list, url_list
  4. import threading
  5. threadLock = threading.Lock()
  6. class Urltool(threading.Thread):
  7. def __init__(self, threadID, http_type, url, headers):
  8. threading.Thread.__init__(self)
  9. self.hostlist = host_list
  10. self.http_type = http_type
  11. self.url = url
  12. self.headers = headers
  13. self.threadID = threadID
  14. def generaterl(self):
  15. self.urls = []
  16. for host in self.hostlist:
  17. myurl = '%s://%s%s' % (self.http_type, host, self.url)
  18. request = urllib2.Request(myurl, headers={"Host": self.headers,
  19. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'})
  20. self.urls.append(request)
  21. return self.urls
  22. # @property
  23. def run(self):
  24. print 'number of %s task starting.' % self.threadID
  25. self.generaterl()
  26. self.results = []
  27. for url in self.urls:
  28. try:
  29. response = urllib2.urlopen(url, timeout=3)
  30. # print response.url, response.code
  31. self.results.append([url.get_header('Host'), url.get_host(), response.url, response.code])
  32. # 状态码异常
  33. except urllib2.HTTPError, e:
  34. self.results.append([url.get_header('Host'), url.get_host(), e.geturl(), e.code])
  35. # 连接异常
  36. except urllib2.URLError, e:
  37. self.results.append([url.get_header('Host'), url.get_host(), e, 999])
  38. # 数据错误
  39. except urllib2.httplib.BadStatusLine, e:
  40. self.results.append([url.get_header('Host'), url.get_host(), e, 998])
  41. # 超时或其他
  42. except Exception, e:
  43. self.results.append([url.get_header('Host'), url.get_host(), e, 997])
  44. # return self.results
  45. threadLock.acquire()
  46. print self.results
  47. threadLock.release()
  48. if __name__ == '__main__':
  49. for intid, url in enumerate(url_list):
  50. if url == 'www.test.com':
  51. task = Urltool(intid, 'http', '/func.php?uid=12026277&size=big&time=1452578235', url)
  52. task.start()
  53. else:
  54. task = Urltool(intid, 'http', '', url)
  55. task.start()