本文整理汇总了Python中util.write_log函数的典型用法代码示例。如果您正苦于以下问题:Python write_log函数的具体用法?Python write_log怎么用?Python write_log使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write_log函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: server_select
def server_select(auth_info,**kwargs):
data_result = []
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
if '1' not in auth_info['r_id']:
return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' })
try:
fields = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','server_purpose','server_run','expire','server_up_time','idc_id','cabinet_id','supplier','supplier_phone']
#将角色对应的p_id都转为name,最终返回的结果p_id的值都是name
res = app.config['cursor'].get_results('server', fields)
print res
for i in res:
i['check_update_time'] = str(i['check_update_time'])
i['manufacture_date'] = str(i['manufacture_date'])
i['expire'] = str(i['expire'])
i['server_up_time'] = str(i['server_up_time'])
if i["idc_id"]:
idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc_id"])})
cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet_id"])})
i['idc_name'] = str(idc['name'])
i['cabinet_name'] = str(cabinet['name'])
i['expire'] = i['expire'].split()[0]
i['server_up_time'] = i['server_up_time'].split()[0]
data_result.append(i)
else:
data_result.append(i)
util.write_log('api').info(username, 'select server list success')
return json.dumps({'code':0,'result':data_result})
except:
util.write_log('api').error("select server list error: %s" % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'get serverlist failed'})
示例2: passwd
def passwd(auth_info):
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
uid = int(auth_info['uid'])
r_id = auth_info['r_id']
try:
data = request.get_json()
if '1' in r_id and data.has_key('user_id'): #管理员修改用户密码,需要传入user_id,不需要输入老密码
user_id = data['user_id']
if not app.config['cursor'].if_id_exist('user',user_id):
return json.dumps({'code':1,'errmsg':'User not exist'})
password = hashlib.md5(data['password']).hexdigest()
app.config['cursor'].execute_update_sql('user', {'password': password}, {'id': user_id})
else: #用户自己修改密码,需要输入老密码
if not data.has_key("oldpassword") :
return json.dumps({'code':1,'errmsg':'need oldpassword'})
oldpassword = hashlib.md5(data['oldpassword']).hexdigest()
res = app.config['cursor'].get_one_result('user', ['password'], {'username': username})
if res['password'] != oldpassword:
return json.dumps({'code':1,'errmsg':'oldpassword wrong'})
password = hashlib.md5(data['password']).hexdigest()
app.config['cursor'].execute_update_sql('user', {'password': password}, {'username': username})
util.write_log('api').info(username,'update user password success')
return json.dumps({'code':0,'result':'update user passwd success'})
except:
util.write_log('api').error('update user password error : %s' % traceback.format_exc())
return json.dumps({' code':1,'errmsg':'update user password failed'})
示例3: createuser
def createuser(auth_info,*arg,**kwargs):
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
r_id = auth_info['r_id'] #string, eg: '1,2,3'
if '1' not in r_id: #角色id = 1 为sa组,超级管理员
return json.dumps({'code': 1,'errmsg':'you not admin,no power' })
try:
data = request.get_json()['params']
#api端对传入端参数验证
if 'r_id' not in data:
return json.dumps({'code': 1, 'errmsg': "must need a role!"})
if not app.config['cursor'].if_id_exist('role',data['r_id'].split(',')):
return json.dumps({'code': 1, 'errmsg': "Role not exist!"})
if not util.check_name(data['username']):
return json.dumps({'code': 1, 'errmsg': "username must be string or num!"})
if data['password'] != data['repwd']:
return json.dumps({'code': 1, 'errmsg': "password equal repwd!"})
elif len(data['password']) < 6:
return json.dumps({'code': 1, 'errmsg': 'passwd must over 6 string !'})
else:
data.pop('repwd') #传入的第二次密码字段不存在,需要删除
data['password'] = hashlib.md5(data['password']).hexdigest()
data['join_date'] = time.strftime('%Y-%m-%d %H:%M:%S')
app.config['cursor'].execute_insert_sql('user', data)
util.write_log('api').info(username, "create_user %s" % data['username'])
return json.dumps({'code': 0, 'result': 'create user %s success' % data['username']})
except:
util.write_log('api').error("Create user error: %s" % traceback.format_exc())
return json.dumps({'code': 1, 'errmsg': 'Create user failed'})
示例4: getapi
def getapi(auth_info,**kwargs):
if auth_info['code']==1:
return json.dumps(auth_info)
username = auth_info['username']
if '1' not in auth_info['r_id']:
return json.dumps({'code': 1,'errmsg':'you not admin,no power' })
try:
output = ['id','ip','hostname','MAC','os','status','gateway','subnet']
data = request.get_json()['params']
fields = data.get('output', output)
where = data.get('where',None)
if not where:
return json.dumps({'code':1,'errmsg':'must need a condition'})
result = app.config['cursor'].get_one_result('cobbler', fields, where)
ret_system = system(app.config['cobbler_url'],app.config['cobbler_user'],app.config['cobbler_password'],result['hostname'],result['ip'],result['MAC'],result['os'],result['gateway'],result['subnet'])
if str(ret_system['result']) != "True":
return json.dumps({'code':1,'errmsg':'please check your system name'})
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
data_insert = {'ip':result['ip'],'os':result['os'],'install_time':now}
ret = app.config['cursor'].execute_insert_sql('install', data_insert)
up_date = app.config['cursor'].execute_update_sql('cobbler', {"status":1}, where)
util.write_log('api').info(username, 'select permission list success')
return json.dumps({'code':0,'result':up_date})
except:
util.write_log('api').error("get list permission error: %s" % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'get cobbler failed'})
示例5: server_get
def server_get(auth_info, **kwargs):
res = []
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
try:
output = ['id','hostname','ip','vm_status','st','uuid','manufacturers','server_type','server_cpu','os','server_disk','server_mem','mac_address','manufacture_date','check_update_time','supplier','supplier_phone','idc_id','cabinet_id','cabinet_pos','expire','server_up_time','server_purpose','server_run','host']
data = request.get_json()['params']
fields = data.get('output', output)
where = data.get('where',None)
if not where:
return json.dumps({'code':1, 'errmsg':'must need a condition'})
result = app.config['cursor'].get_one_result('server', fields, where)
result['check_update_time'] = str(result['check_update_time'])
result['manufacture_date'] = str(result['manufacture_date'])
result['expire'] = str(result['expire'])
result['server_up_time'] = str(result['server_up_time'])
# print result
if not result :
return json.dumps({'code':1, 'errmsg':'result is null'})
else:
util.write_log('api').info(username, "select server by id success")
return json.dumps({'code':0,'result':result})
except:
util.write_log('api').error('select server by id error: %s' % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'get server failed'})
示例6: execute_update_sql
def execute_update_sql(self, table_name, data, where, fields=None):
try:
sql = self._update_sql(table_name, data, where, fields)
if sql:
return self._execute(sql)
except:
util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
示例7: apply_create
def apply_create(auth_info, **kwargs):
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
if '1' not in auth_info['r_id']:
return json.dumps({'code': 1,'errmsg':'you not admin,no power' })
r_id = auth_info['r_id']
field = ['project_id','info','applicant','commit','apply_date','status','detail']
try:
data = request.get_json()['params'] #project_id,project_name,applicant,info,detail
data['commit']='11111' #脚本获取
data['apply_date'] = time.strftime('%Y-%m-%d %H:%M')
data['status'] = 1
data['applicant'] = username
where = {"project_id":int(data['project_id'])}
data.pop('project_username')
res = app.config['cursor'].get_one_result('project_apply',field,where)
if not res:
app.config['cursor'].execute_insert_sql('project_apply', data)
else:
app.config['cursor'].execute_update_sql('project_apply',data,where)
app.config['cursor'].execute_insert_sql('project_deploy',data)
util.write_log('api').info(username,{'code':0,'result':'项目申请成功'})
return json.dumps({'code':0,'result':'项目申请成功'})
except:
util.write_log('api').error('project apply error: %s' % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'项目申请失败'})
示例8: gitolite
def gitolite():
git_confile = app.config['git_confile']
api_dir = os.path.dirname(os.path.realpath(__file__))
script_dir = os.path.join(api_dir.rstrip('api'),'script')
projects,pro_pri = util.project_members()
try :
# 将项目和用户信息写入配置文件中
with open(git_confile,'w') as f:
str1= ""
for k,v in projects.items():
v = list(set(v)-set(pro_pri[k])) # 由于projests中存放了项目所有的成员,包括负责人。需要吧负责人剔除
str1 += "repo %s \n" % k
str1 += " RW+ = %s \n" % ' '.join(pro_pri[k]) # 负责人的权限最大
if v: # 如果项目除了负责人外,有其他成员,则设置成员的权限
str1 += " - master = %s \n" %(' '.join(v)) # 项目成员无权操作master分支,其他分支可任意操作
str1 += " RW = %s \n" %(' '.join(v))
f.write(str1)
# git add/commit/push生效.路径暂时写死,定版前修改
#stdout=util.run_script_with_timeout("sh %s/git.sh" % script_dir)
#print stdout
return json.dumps({'code':0,'result':"git操作成功"})
except:
util.write_log('api').error("get config error: %s" % traceback.format_exc())
return json.dumps({'code':1,'errmsg':"get config error"})
示例9: project_select
def project_select(auth_info,**kwargs):
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
try:
output = ['id','name','path','principal','p_user','p_group','is_lock','comment']
data = request.get_json()['params']
fields = data.get('output', output)
#查询用户表,生成id2name的字典
users=util.getinfo('user',['id', 'name'])
#查询角色表,生成id2name的字典
roles=util.getinfo('role',['id', 'name'])
#查询项目表,把项目表中p_uesr,p_group,principal的ID 转为name
projects = app.config['cursor'].get_results('project', fields)
for p in projects: #循环项目列表,判断项目表中的p_user的id是否存在,如果存在则id2name
p['principal'] = ','.join([users[x] for x in p['principal'].split(',') if x in users])
p['p_user'] = ','.join([users[u] for u in p['p_user'].split(',') if u in users])
p['p_group'] = ','.join([roles[r] for r in p['p_group'].split(',') if r in roles])
#普通用户只能查看其有权限的项目
if '1' not in auth_info['r_id']:
p=util.user_projects(username) #调用公共函数,查出用户的项目id2name{'1':'devops','2':'test'}
projects = [pro for pro in projects for pid in p.keys() if pid==pro['id']] #获取对应项目的详情
util.write_log('api').info(username, 'select project list success')
return json.dumps({'code':0,'result':projects,'count':len(projects)})
except:
util.write_log('api').error("select project list error: %s" % traceback.format_exc())
return json.dumps({ 'code':1,'errmsg':'get projectlist failed'})
示例10: switch_select
def switch_select(auth_info,**kwargs):
data_result = []
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
if '1' not in auth_info['r_id']:
return json.dumps({'code': 1,'errmsg':'you not admin,no cmdb' })
try:
fields = ['id','ip','device','port','port','cabinet','idc']
#将角色对应的p_id都转为name,最终返回的结果p_id的值都是name
res = app.config['cursor'].get_results('switch', fields)
for i in res:
if i['idc']:
idc = app.config['cursor'].get_one_result('idc', ['name'],{"id":int(i["idc"])})
cabinet = app.config['cursor'].get_one_result('cabinet', ['name'],{"id":int(i["cabinet"])})
i['idc_name'] = str(idc['name'])
i['cabinet_name'] = str(cabinet['name'])
data_result.append(i)
else:
data_result.append(i)
util.write_log('api').info(username, 'select switch list success')
return json.dumps({'code':0,'result':data_result})
except:
util.write_log('api').error("select switch list error: %s" % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'get switch failed'})
示例11: apply_list
def apply_list(auth_info,**kwargs):
if auth_info['code'] == 1:
return json.dumps(auth_info)
username = auth_info['username']
try:
output = ['id','project_id','info','applicant','version','apply_date','commit','status','detail']
data = request.get_json()['params']
fields = data.get('output', output)
applyer = app.config['cursor'].get_results('project_apply',fields) #申请人看到的项目列表
for res in applyer:
res['apply_date']=str(res['apply_date'])
where = {'status':['1','2']}
result = app.config['cursor'].get_results('project_apply',fields,where) #只列出申请中和审核中的项目给发布者
#id转换成名字
id2name_project=util.getinfo('project',['id','name'])
for res in result:
res['project_name'] = id2name_project[str(res['project_id'])]
res['apply_date']=str(res['apply_date'])
util.write_log('api').info(username, 'get apply list success!')
return json.dumps({'code':0,'data': applyer, 'result':result,'count':len(result)})
except:
util.write_log('api').error("select apply list error:%s" % traceback.format_exc())
return json.dumps({'code':1,'errmsg':'任务列表获取失败!'})
示例12: execute_delete_sql
def execute_delete_sql(self, table_name, where):
try:
sql = self._delete_sql(table_name, where)
if sql:
return self._execute(sql)
except:
util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
示例13: _delete_sql
def _delete_sql(self, table_name, where):
if not (where and isinstance(where, dict)):
return ""
where_cond = ["%s='%s'" % (k, v) for k,v in where.items()]
sql = "DELETE FROM %s WHERE %s" % (table_name, ' AND '.join(where_cond))
util.write_log('api').info("Delete sql: %s" % sql)
return sql
示例14: update_logdict
def update_logdict(loglist, oldlogdict):
# Each time we run, we want to re-build our log dictionary. This
# helps to ensure we don't carry over stale data.
newlogdict = {}
for log in loglist:
stats = os.stat(log)
inode = stats[stat.ST_INO]
file_mtime = stats[stat.ST_MTIME]
min_mtime = int(time.time() - MAX_MTIME)
if file_mtime < min_mtime:
# we've got an older file, so update the values in the newlogdict
# to the file size
file_size = stats[stat.ST_SIZE]
newlogdict[log] = {'log_pos': file_size, 'inode': inode}
elif oldlogdict.has_key(log):
# Check to see if a file we saw before has a new inode
# which indicates a new file
if inode != oldlogdict[log]['inode']:
newlogdict[log] = {'log_pos': 0, 'inode': inode}
util.write_log('inode on %s has changed, will scan' % log)
else:
newlogdict[log] = oldlogdict[log]
else:
# normal new file
newlogdict[log] = {'log_pos': 0, 'inode': inode}
return newlogdict
示例15: submit_errors
def submit_errors(error_msg):
""" submit_errors is used for sending out notifications
of errors.
We can put in a variety of things here. For now, we have
email submission and a quick syslog sent over to verify that
we made it into here.
"""
# If there's no error messages, just get out of here
if not error_msg:
util.write_log('nothing to submit')
return True
myhost = util.get_differ_hostname()
# email out the message
if DIFFER_EMAIL_ERRORS:
subject = 'Differ ERRORS: %s' % myhost
util.mail_it(RCPT_TO, MAIL_FROM, subject, error_msg, '[email protected]')
# send to the syslog on DIFFERLOGHOST the fact that we sent out an error
# helpful for perhaps getting a quick look at how many servers
# were sending out errors
human_time = time.strftime('%Y%m%d %H:%M', time.localtime())
try:
syslog_msg = '%s errors submitted at %s' % (myhost, human_time)
c = syslog_client.syslog_client((DIFFERLOGHOST, 514))
c.log(syslog_msg, facility='local4', priority='info')
except:
pass