Skip to content

python_retry

遇见王斌 edited this page Jul 27, 2017 · 1 revision

获取api数据时出错时进行3次重试

#!/usr/bin/python
#coding=utf8

import json
import urllib2
from urllib2 import URLError 
import ConfigParser
zabbix_config = '/etc/zabbix_tool/zabbix_config.ini'
def zabbix_apiinfo(num_retries=3): 
    config = ConfigParser.ConfigParser()
    config.read(zabbix_config)
    server = config.get("zabbixserver", "server")
    port = config.get("zabbixserver", "port")
    zabbix_server="http://%s:%s"%(server,port)

    #写了个错误的
    url = zabbix_server + '/api_jsonrpc.php_xx'
    
    #url = zabbix_server + '/api_jsonrpc.php'
    data=json.dumps({"jsonrpc":"2.0","method":"apiinfo.version","id":1,"params":{}})
    request = urllib2.Request(url, data) 
    header = {"Content-Type":"application/json"}
    for key in header: 
        request.add_header(key, header[key]) 
    try: 
        result = urllib2.urlopen(request) 
    except URLError as e: 
        if num_retries>0:  
            print "正在重试,倒数次数 %d"%num_retries
            return zabbix_apiinfo(num_retries-1)  
        print("ERROR", e)
        exit(1)
    else: 
        response = json.loads(result.read()) 
        result.close() 
        print("zabbix version:[%s]"%response['result']  )

zabbix_apiinfo()

:此方法在[ZabbixTool/lib_zabbix/w_lib/zabbix_api_lib.py]中使用

Clone this wiki locally