开发环境:操作系统:Ubuntu 16.04 LTS
python版本:python3.6.3
以下是代码分析:
# _*_coding:utf-8_*_ import sys, os import datetime,time import http.cookiejar as cookielib import urllib.request import urllib.error import urllib.parse import logging from oms.settings import ZABBIX_HOST,ZABBIX_USER,ZABBIX_PASS,ZABBIX_GRAPH_DIR #导入配置信息 logger=logging.getLogger(__name__) if "http" in ZABBIX_HOST: graphurl = "{0}/chart2.php".format(ZABBIX_HOST) loginurl = "{0}/index.php".format(ZABBIX_HOST) else: graphurl = "http://{0}/chart2.php".format(ZABBIX_HOST) loginurl = "http://{0}/index.php".format(ZABBIX_HOST) class ZabbixGraph(object): def __init__(self): self.graphurl = graphurl self.loginurl = loginurl self.name = ZABBIX_USER self.password = ZABBIX_PASS self.baseDir = ZABBIX_GRAPH_DIR #self.baseDir = "media/reports/graphs/" # 初始化时生成cookies cookiejar = cookielib.CookieJar() urlOpener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookiejar)) values = {"name":self.name, ‘password‘:self.password, ‘autologin‘:1, "enter":‘Sign in‘} data = urllib.parse.urlencode(values).encode(encoding=‘UTF8‘) request = urllib.request.Request(self.loginurl, data) try: urlOpener.open(request,timeout=10) self.urlOpener = urlOpener except urllib.error.HTTPError as e: print(e) def get(self, graphid, begin_date, end_date, imgsDir, width=800, height=200): if graphid == 0: print("graphid error") sys.exit(1) stime=end_date.strftime(‘%Y%m%d000000‘) period=int(time.mktime(end_date.timetuple())-time.mktime(begin_date.timetuple())) logger.debug("period %s" %period) logger.debug("stime %s" %stime) values = { "graphid":graphid, "period":period, "stime":stime, "width":width, "height":height} data = urllib.parse.urlencode(values).encode(encoding=‘UTF8‘) request = urllib.request.Request(self.graphurl, data) url = self.urlOpener.open(request) image = url.read() if not os.path.exists(self.baseDir + imgsDir): os.makedirs(self.baseDir + imgsDir) imgName = "%s%s%s.png" % (self.baseDir, imgsDir, str(graphid)) if os.path.exists(imgName): pass else: f = open(imgName, ‘wb‘) f.write(image) f.flush() f.close return imgName