Created
February 23, 2012 10:13
-
-
Save onlytiancai/1892097 to your computer and use it in GitHub Desktop.
求重构:获取一个服务器HTTP状态
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_http_status(ip, port, host, path='/',ssl=False): | |
''' | |
根据指定IP,端口等信息返回该服务器的http状态,应答码,错误原因,响应时间 | |
代码写的很难看,求重构 | |
''' | |
newstatus, status_code, status_desc = config.Unknow, -99, '未知状态' | |
starttime = datetime.now() | |
try: | |
status_code = int(http((ip, port),host, path, ssl)) | |
perfmon.ok_sum.increase() | |
perfmon.ok_rate.increase() | |
if status_code / 100 in (2,3): | |
newstatus = config.Ok | |
status_desc = '正常' | |
elif status_code >= 500: | |
newstatus = config.Down | |
status_desc = '服务器端错误' | |
else: | |
newstatus = config.Warn | |
status_desc = '服务器返回%s错误' % (status_code,) | |
except Exception, ex: | |
if isinstance(ex, socket.error): | |
if isinstance(ex, socket.timeout): | |
status_code = -3 | |
status_desc = ex.message | |
else: | |
status_code = -1 | |
status_desc = ex.strerror | |
elif isinstance(ex, ValueError): | |
status_code = -8 | |
status_desc = '服务器返回无效HTTP应答' | |
else: | |
status_code = -2 | |
status_desc = '未知错误' | |
newstatus = config.Down | |
perfmon.error_sum.increase() | |
perfmon.error_rate.increase() | |
logging.debug("http error:%s-%s", ip ,ex) | |
responsetime = (datetime.now()-starttime).microseconds/1000 | |
return responsetime, newstatus, status_code, status_desc |
这一次的重构还有什么不满意的地方?
我不知道最后10行再怎么写的简洁易懂一些。
newstatus, status_code, status_desc = config.Unknow, -99, '未知状态'
这个写法可读性不高啊,而且后期维护起来,比如加个新变量什么的也不方便
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
第一次重构