• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python util.write_log函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中util.write_log函数的典型用法代码示例。如果您正苦于以下问题:Python write_log函数的具体用法?Python write_log怎么用?Python write_log使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了write_log函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:32,代码来源:server.py


示例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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:29,代码来源:user.py


示例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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:31,代码来源:user.py


示例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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:26,代码来源:cobbler.py


示例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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:26,代码来源:server.py


示例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()))
开发者ID:devops-life,项目名称:My-Script,代码行数:7,代码来源:db.py


示例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':'项目申请失败'})
开发者ID:devops-life,项目名称:My-Script,代码行数:27,代码来源:online.py


示例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"})
开发者ID:devops-life,项目名称:My-Script,代码行数:25,代码来源:project.py


示例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'})
开发者ID:devops-life,项目名称:My-Script,代码行数:31,代码来源:project.py


示例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'})
开发者ID:gitsucce,项目名称:roncoo-cmdb,代码行数:25,代码来源:switch.py


示例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':'任务列表获取失败!'})
开发者ID:devops-life,项目名称:My-Script,代码行数:25,代码来源:online.py


示例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()))
开发者ID:devops-life,项目名称:My-Script,代码行数:7,代码来源:db.py


示例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
开发者ID:devops-life,项目名称:My-Script,代码行数:7,代码来源:db.py


示例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
开发者ID:brianr,项目名称:lol-logwatcher,代码行数:29,代码来源:differ.py


示例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
开发者ID:brianr,项目名称:lol-logwatcher,代码行数:30,代码来源:differ.py


示例16: _insert_sql

 def _insert_sql(self, table_name, data):
     fields, values = [], []
     for k, v in data.items():
         fields.append(k)
         values.append("'%s'" % v)
     sql = "INSERT INTO %s (%s) VALUES (%s)" % (table_name, ','.join(fields), ','.join(values))
     util.write_log('api').info("Insert sql: %s" % sql)
     return sql
开发者ID:devops-life,项目名称:My-Script,代码行数:8,代码来源:db.py


示例17: execute_insert_sql

 def execute_insert_sql(self, table_name, data):
     try:
         sql = self._insert_sql(table_name, data)
         if not sql: 
             return None
         return self._execute(sql)
     except:
         util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
开发者ID:devops-life,项目名称:My-Script,代码行数:8,代码来源:db.py


示例18: get_results

 def get_results(self, table_name, fields, where=None, order=None, asc_order=True, limit=None):
     try:
         sql = self._select_sql(table_name, fields, where, order, asc_order, limit)
         self._execute(sql)
         result_sets = self._fetchall()
         return [dict([(k, '' if row[i] is None else row[i]) for i,k in enumerate(fields)]) for row in result_sets]
     except:
         util.write_log('api').error("Execute '%s' error: %s" % (sql, traceback.format_exc()))
         return []
开发者ID:devops-life,项目名称:My-Script,代码行数:9,代码来源:db.py


示例19: userprojects

def userprojects(auth_info,**kwargs):
    if auth_info['code'] == 1:
        return json.dumps(auth_info)             
    username = auth_info['username']
    try:
        res = util.user_projects(username) #{'1':'devops','2':'test'}
        return json.dumps({'code': 0, 'result': res})
    except:
        util.write_log('api').error("调用userproject函数失败: %s" % traceback.format_exc())
        return json.dumps({'code': 1, 'errmsg': '查询项目列表错误'})
开发者ID:devops-life,项目名称:My-Script,代码行数:10,代码来源:project.py


示例20: apply_pub

def apply_pub(username,data,where):
    #更新project_apply表
    app.config['cursor'].execute_update_sql('project_apply',data,where)
    util.write_log('api').info(username,"success and update project_apply status %s" % data['status'])

    #同时将本次操作插入到project_deploy中
    fields = ['project_id','info','applicant','status','apply_date','version','commit','detail']  
    result=app.config['cursor'].get_one_result('project_apply',fields,where)
    app.config['cursor'].execute_insert_sql('project_deploy',result)
    util.write_log('api').info(username,"success and insert project_deploy status  %s"  % data['status'])
开发者ID:devops-life,项目名称:My-Script,代码行数:10,代码来源:online.py



注:本文中的util.write_log函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.ComponentRegistry类代码示例发布时间:2022-05-26
下一篇:
Python util.write_file函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap