コード例 #1
0
 def post(self, op=None):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     if op == 'online':
         data = yield self.get_request_body_to_json()
         content = data.get('content')
         if content:
             html = '''
             <p>Dear All:</p>
             <p>&nbsp;&nbsp;以下是近期的线上问题汇报,请查收~</p>
             <p>&nbsp;&nbsp;本信息由测试部自动化汇集工具自动创建于{}</p>
             <p>{}</p>
             <p>&nbsp;&nbsp;如您需要查看更多信息,请访问综合测试管理平台。</p>
             '''.format(time.strftime('%Y-%m-%d %H:%M:%S'), content)
             res, msg = yield self.common_func.send_email(
                 subject='测试部门线上问题汇报_{}'.format(
                     time.strftime('%Y-%m-%d %H:%M:%S')),
                 content=html,
                 to=online_mail_to)
         else:
             res, msg = False, '邮件内容不能为空!'
         if res:
             msg = dict(status='SUCCESS', message='邮件发送成功!', data='')
         else:
             log.info(msg)
             msg = dict(status='FAIL', message=str(msg), data='')
     else:
         msg = dict(status='FAIL', message='操作类型错误!', data='')
     self.write_json(msg)
コード例 #2
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     user = self.current_user
     data = yield self.get_request_body_to_json()
     save_data = data.data
     flag = False
     if data.type == 'info':
         department = save_data.department_id or []
         if not department:
             msg = '请选择部门!'
         elif not self.common_func.check_string(save_data.username.strip(), 'username'):
             msg = '用户名格式不对, 请检查!'
         elif not self.common_func.check_string(save_data.realname.strip(), 'realname'):
             msg = '请填写正确的中文姓名!'
         elif not self.common_func.check_string(save_data.email.strip(), 'email'):
             msg = '邮箱格式不对, 请检查!'
         else:
             profile = dict(department=save_data.department_id, workerId=save_data.workerId.strip(),
                            avatar=json.loads(user.profile)['avatar'], position=save_data.position.strip())
             flag, msg = yield self.user.edit_user(uid=user.id, username=save_data.username.strip(),
                                                   real_name=save_data.realname.strip(),
                                                   profile=profile, email=save_data.email.strip())
     elif data.type == 'passwd':
         if not self.common_func.check_string(save_data.newPasswd, 'password'):
             msg = '密码格式不对, 请检查!'
         else:
             if self.common_func.encode_password(save_data.password) != user.password:
                 msg = '原密码不正确!'
             elif save_data.newPasswd == save_data.rePasswd:
                 flag, msg = yield self.user.edit_user(uid=user.id, password=save_data.newPasswd)
             else:
                 msg = '新密码与确认密码不一致!'
     else:
         msg = '操作类型错误!'
     self.write_json(dict(status='SUCCESS' if flag else 'FAIL', message='修改成功' if flag else msg, data=dict(type=data.type)))
コード例 #3
0
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     common_info = yield self.option.get_options_list(o_type='common',
                                                      status=1)
     common = dict(company='鸥鹏斯塔克',
                   sysName='斯塔克综合测试管理平台',
                   sysDesc='让测试更高效 使测试更简单',
                   emailExt='')
     auto_login = False
     for row in common_info:
         if row.name == 'company':
             common['company'] = row.value
         if row.name == 'sysName':
             common['sysName'] = row.value
         if row.name == 'sysDesc':
             common['sysDesc'] = row.value
         if row.name == 'emailExt' and row.value:
             common['emailExt'] = '@{}'.format(row.value)
         if row.name == 'autoLogin':
             auto_login = True if row.value == 'yes' else False
     msg = dict(status='SUCCESS',
                message='',
                data=dict(company=common['company'],
                          sysName=common['sysName'],
                          sysDesc=common['sysDesc'],
                          emailExt=common['emailExt'],
                          autoLogin=auto_login))
     self.write_json(msg)
コード例 #4
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     params = yield self.get_request_body_to_json()
     username = params.userName or ''
     password = params.password or ''
     user = yield self.user.get_user_info(username)
     if not user:
         msg = dict(status='FAIL', message='用户不存在!', data='')
         log.warn('{} 用户不存在'.format(username))
     elif user.password == self.common_func.encode_password(password) and user.status != 0:
         self.user.edit_user(username, last_login_time=time.strftime('%Y-%m-%d %H:%M:%S'))
         self.set_secure_cookie('OSTSESSION', user.email, expires=time.time()+1800)
         if user.role == 0:
             authority = 'admin'
         elif user.role == 1 and user.status == 2:
             authority = 'user'
         elif user.role == 1 and user.status == 1:
             authority = 'noActive'
         else:
             authority = 'guest'
         msg = dict(status='SUCCESS', message='', data=dict(authority=authority))
         log.info('{} 登录成功'.format(username))
         content = dict(group=dict(name='', link=''), project=dict(name='', link=''),
                        template='同学, 欢迎回来!')
         self.msg.add_message(user_id=user.id, m_type='active', content=content)
     elif user.status == 0:
         msg = dict(status='FAIL', message='用户被禁用, 请联系管理员!', data='')
         log.warn('{} 用户被禁用, 请联系管理员'.format(username))
     else:
         msg = dict(status='FAIL', message='密码不正确!', data='')
         log.warn('{} 密码不正确'.format(username))
     self.write_json(msg)
コード例 #5
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     user = self.current_user
     params = yield self.get_request_body_to_json()
     m_type = ''
     if params.type == 'notification':
         m_type = 'notice'
     elif params.type == 'message':
         m_type = 'message'
     elif params.type == 'event':
         m_type = 'todo'
     elif params.type == 'read':
         msg = yield self.msg.get_message(mid=params.mid)
         if msg and msg.type == 'todo':
             status = 5 if msg.status == 3 else msg.status + 1
             status = 0 if status > 5 else status
         else:
             status = 0 if msg.status == 2 else 2
         yield self.msg.edit_message(mid=params.mid, status=status)
         if msg.type == 'notice':
             m_type = '通知'
         elif msg.type == 'message':
             m_type = '消息'
         elif msg.type == 'todo':
             m_type = '待办'
         return self.write_json(dict(status='SUCCESS', message='{} 状态已变更!'.format(m_type), data=''))
     if m_type:
         res, msg = yield self.msg.edit_message(m_type=m_type, user_id=user.id, status=0)
         if res:
             msg = dict(status='SUCCESS', message='清除成功', data='')
         else:
             msg = dict(status='FAIL', message='清除失败', data='')
     else:
         msg = dict(status='FAIL', message='清除失败', data='')
     self.write_json(msg)
コード例 #6
0
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     op = self.get_argument('type', '')
     if op == 'projects':
         projects, total = yield self.project.get_projects_list(p_type='project', status=1)
         projects_list = list()
         for p in projects:
             projects_list.append(dict(pid=p.id, name=p.name))
         return self.write_json(dict(status='SUCCESS', message='', data=dict(data=projects_list, type=op)))
     name = self.get_argument('name', '').strip()
     page = int(self.get_argument('page', 1))
     size = int(self.get_argument('size', 10))
     tid = self.get_argument('tid', '').strip()
     projects, total = yield self.project.get_projects_list(p_type='project', page=page, limit=size,
                                                            name=name or None, team_id=tid or None)
     data = []
     no = 0
     for project in projects:
         info = json.loads(project.config) if project.config else dict(description='', params=[])
         no += 1
         data.append(dict(no=no+page*size-size, key=project.id, name=project.name, tid=project.teamId, status=project.status,
                          team=json.loads(project.team)['name'], description=info.get('description'),
                          params=[], pid=project.id, userId=info.get('userId')))
     msg = dict(status='SUCCESS', message='', data=dict(data=data, page=page, size=size, total=total, type=op))
     self.write_json(msg)
コード例 #7
0
ファイル: members.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self, op='edit'):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     data = yield self.get_request_body_to_json()
     if data.type == 'groups':
         if op == 'edit':
             msg = yield self.__save_group(data.data)
         elif op == 'delete':
             msg = yield self.__delete_group(data.data)
         else:
             msg = dict(status='FAIL', message='操作类型错误', data='')
     elif data.type == 'members':
         if op == 'edit':
             msg = yield self.__save_members(data.data)
         elif op == 'delete':
             msg = yield self.__delete_members(data.data)
         else:
             msg = dict(status='FAIL', message='操作类型错误', data='')
     elif data.type == 'reset':
         user = data.data
         email = user.email or ''
         res, msg = yield self.user.edit_user(uid=user.uid,
                                              password=email.split('@')[0] +
                                              '123456')
         if res:
             msg = dict(status='SUCCESS', message='密码重置成功!', data='')
         else:
             msg = dict(status='FAIL', message=msg, data='')
     else:
         msg = dict(status='FAIL', message='操作类型错误', data='')
     self.write_json(msg=msg)
コード例 #8
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     data = self.get_argument('data', None)
     if data:
         email = base64.b64decode(data.encode('utf8')).decode('utf8')
         user = yield self.user.get_user_info(email_or_username=email, status=1)
         if user:
             yield self.user.edit_user(email=email, status=2)
     self.clear_cookie('OSTSESSION')
     self.redirect('/')
コード例 #9
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     params = yield self.get_request_body_to_json()
     email = params.email or ''
     name = params.name or ''
     department = params.department or []
     password = params.password or ''
     confirm = params.confirm or ''
     if not self.common_func.check_string(name.strip(), 'realname'):
         msg = dict(status='FAIL', message='请填写正确的中文姓名!', data='')
     elif not department:
         msg = dict(status='FAIL', message='请选择部门!', data='')
     elif not self.common_func.check_string(email, 'email'):
         msg = dict(status='FAIL', message='邮箱格式不对, 请检查!', data='')
     elif not self.common_func.check_string(password, 'password'):
         msg = dict(status='FAIL', message='密码格式不对, 请检查!', data='')
     elif password != confirm:
         msg = dict(status='FAIL', message='密码跟确认密码不一致, 请检查!', data='')
     else:
         user, msg = yield self.user.register_user(email=email, password=password, real_name=name,
                                                   profile=dict(department=department, avatar='https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png', position=''))
         if user:
             self.set_secure_cookie('OSTSESSION', email, expires=time.time()+1800)
             if user.role == 0:
                 authority = 'admin'
             elif user.role == 1 and user.status == 2:
                 authority = 'user'
             elif user.role == 1 and user.status == 1:
                 authority = 'noActive'
             else:
                 authority = 'guest'
             msg = dict(status='SUCCESS', message=msg, data=dict(authority=authority))
             log.info('{} 注册成功'.format(email))
             if authority == 'noActive':
                 end_time = datetime.datetime.now() + datetime.timedelta(days=3)
                 content = dict(title='激活账户', description='请在 {} 前激活您的账户, 否则将自动注销。'.format(
                     end_time.strftime('%Y-%m-%d')))
                 self.msg.add_message(user_id=user.id, m_type='todo', content=content)
                 config = yield self.option_func.get_option_by_type(o_type='common')
                 data = base64.b64encode(email.encode('utf8', errors='ignore')).decode('utf8', errors='ignore')
                 url = '{}/{}?data={}'.format(self.request.headers.get('Origin'), 'api/py/activeUser', data)
                 html = '''
                 <p>Dear {}:</p>
                 <p>&nbsp;&nbsp;欢迎使用{}, 请点击下面链接激活你的账户, 谢谢!</p>
                 <p><a href="{}">{}</a></p>
                 '''.format(name, config.get('sysName'), url, url)
                 yield self.common_func.send_email(
                     subject='[{}]请尽快激活你的账户'.format(config.get('sysName')), content=html, to=[email])
             content = dict(group=dict(name='', link=''), project=dict(name='', link=''),
                            template='同学, 欢迎加入组织!')
             self.msg.add_message(user_id=user.id, m_type='active', content=content)
         else:
             msg = dict(status='FAIL', message=msg, data='')
             log.warn('{} 注册失败#{}'.format(email, msg))
     self.write_json(msg)
コード例 #10
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     common_info = yield self.option.get_option(o_type='common', name='autoLogin', status=1)
     if auto_login_url and (common_info and common_info.value == 'yes'):
         try:
             api_client = httpclient.AsyncHTTPClient()
             resp = yield api_client.fetch(
                 '{}?ip={}'.format(
                     auto_login_url, self.request.remote_ip), method='GET')
             data = resp.body
             if isinstance(data, bytes):
                 data = data.decode('utf8', errors='ignore')
             data = json.loads(data)
             if data:
                 email = data[0]['email'].strip()
                 name = data[0]['userName'].strip()
                 department = []
                 dep = yield self.option.get_options_list(o_type='teams', status=1)
                 for d in dep:
                     dv = json.loads(d.value)
                     if d.name == 'department' and dv['name'] == data[0]['department'].strip():
                         department.append(dv['up'])
                         department.append(d.id)
                         break
                 user, msg = yield self._login_or_register(email=email, name=name, department=department,
                                                           password=email.split('@')[0]+'123456')
             else:
                 user = None
                 msg = '[自动登录]通过IP {} 获取用户信息失败, 获取到的信息为 {}'.format(self.request.remote_ip, data)
         except Exception as e:
             log.error(e)
             user = None
             msg = str(e)
         if user:
             if user.role == 0:
                 authority = 'admin'
             elif user.role == 1 and user.status == 2:
                 authority = 'user'
             elif user.role == 1 and user.status == 1:
                 authority = 'noActive'
             else:
                 authority = 'guest'
             data = dict(status='SUCCESS', message=msg, data=dict(authority=authority))
         else:
             data = dict(status='FAIL', message=msg, data='')
     else:
         data = dict(status='FAIL', message='', data='')
     self.write_json(data)
コード例 #11
0
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     configs = yield self.option.get_options_list(o_type='common')
     config = dict()
     for c in configs:
         if c.name == 'emailPasswd':
             c.value = base64.b16decode(c.value.encode('utf8', errors='ignore')).decode('utf8', errors='ignore')
         config[c.name] = c.value
     nav_links = yield self.option.get_options_list(o_type='navLink')
     link = []
     no = 0
     for nav in nav_links:
         no += 1
         link.append(dict(key=no, id=nav.id, title=nav.name, href=nav.value))
     config['navLink'] = link
     self.write_json(dict(status="SUCCESS", message="", data=config))
コード例 #12
0
 def post(self, op='edit'):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     data = yield self.get_request_body_to_json()
     if op == 'edit':
         if data.name.strip() == '':
             return self.write_json(msg=dict(status='FAIL', message='项目名称不能为空!', data=''))
         if str(data.key).find('NEW_TEMP_ID') != -1 and data.pid == '':
             pid, msg = yield self.project.add_project(
                 name=data.name.strip(), p_type='project', status=data.status, team_id=data.tid,
                 config=dict(description=data.description, userId=self.current_user.id))
             if pid:
                 content = dict(group=dict(name=data.team), project=dict(name=data.name.strip()),
                                template='在 @{group} 新建了项目 @{project}')
                 self.msg.add_message(user_id=self.current_user.id, m_type='active', content=content)
                 msg = dict(status='SUCCESS', message='新增成功', data=dict(pid=pid))
             else:
                 msg = dict(status='FAIL', message=msg, data='')
         else:
             res, msg = yield self.project.edit_project(
                 pid=data.pid, name=data.name.strip(), status=data.status, team_id=data.tid,
                 config=dict(description=data.description, userId=data.userId))
             if res:
                 msg = dict(status='SUCCESS', message='编辑成功', data=dict(pid=data.pid))
             else:
                 msg = dict(status='FAIL', message=msg, data='')
     elif op == 'delete':
         res, msg = yield self.project.delete_project(pid=data.pid)
         if res:
             if not isinstance(data.pid, list):
                 content = dict(group=dict(name=data.team), project=dict(name=data.name.strip()),
                            template='删除了 @{group} 的项目 @{project}')
             else:
                 content = dict(group=dict(), project=dict(),
                            template='批量删除了项目')
             self.msg.add_message(user_id=self.current_user.id, m_type='active', content=content)
             yield self.statistics.delete_statistics(project_id=data.pid)
             msg = dict(status='SUCCESS', message='删除成功', data='')
         else:
             msg = dict(status='FAIL', message=msg, data='')
     else:
         msg = dict(status='FAIL', message='操作类型错误', data='')
     self.write_json(msg)
コード例 #13
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self, op='edit'):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     params = yield self.get_request_body_to_json()
     params = params.data
     user = self.current_user
     profile = json.loads(user.profile)
     if not self.common_func.check_string(params.href, 'url'):
         return self.write_json(dict(status='FAIL', message='链接格式不对, 请检查!', data=''))
     if op == 'edit':
         nid = 1
         if 'nav' not in profile.keys():
             profile['nav'] = [dict(id=nid, title=params.title, href=params.href)]
         elif 'id' not in params.keys() or params.id == '':
             nid = len(profile['nav']) + 1
             profile['nav'].append(dict(id=nid, title=params.title, href=params.href))
         else:
             for link in profile['nav']:
                 if link['id'] == params.id:
                     link['title'] = params.title
                     link['href'] = params.href
         res, msg = yield self.user.edit_user(uid=user.id, profile=profile)
         if res:
             msg = dict(status='SUCCESS', message='便捷导航保存成功!', data=dict(id=nid))
         else:
             msg = dict(status='FAIL', message=msg, data='')
     elif op == 'delete':
         if 'nav' in profile.keys():
             for link in profile['nav']:
                 if link['id'] == params.id:
                     profile['nav'].remove(link)
             res, msg = yield self.user.edit_user(uid=user.id, profile=profile)
             if res:
                 msg = dict(status='SUCCESS', message='删除便捷导航成功!', data='')
             else:
                 msg = dict(status='FAIL', message=msg, data='')
         else:
             msg = dict(status='FAIL', message='便捷导航列表为空!', data='')
     else:
         msg = dict(status='FAIL', message='操作类型错误!', data='')
     self.write_json(msg)
コード例 #14
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     user = self.current_user
     config = yield self.option_func.get_option_by_type(o_type='common')
     if user.status == 1:
         data = base64.b64encode(user.email.encode('utf8', errors='ignore')).decode('utf8', errors='ignore')
         url = '{}/{}?data={}'.format(self.request.headers.get('Origin'), 'api/py/activeUser', data)
         html = '''
         <p>Dear {}:</p>
         <p>&nbsp;&nbsp;欢迎使用{}, 请点击下面链接激活你的账户, 谢谢!</p>
         <p><a href="{}">{}</a></p>
         '''.format(user.username, config.get('sysName'), url, url)
         res, msg = yield self.common_func.send_email(
             subject='[{}]请尽快激活你的账户'.format(config.get('sysName')), content=html, to=[user.email])
         if res:
             msg = dict(status='SUCCESS', message='激活邮件发送成功!', data=dict(type='active'))
         else:
             log.info(msg)
             msg = dict(status='FAIL', message=str(msg), data=dict(type='active'))
     else:
         msg = dict(status='FAIL', message='用户已是激活状态!', data=dict(type='active'))
     self.write_json(msg)
コード例 #15
0
ファイル: members.py プロジェクト: zhengxiaoming1/OpenStark
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     op = self.get_argument('type', '')
     groups = []
     members = dict(data=[])
     if op == 'groups':
         groups = yield self.__get_group()
     elif op == 'members':
         callback = self.get_argument('callback', None)
         members = yield self.__get_members(status=2 if callback else None)
         if callback:
             return self.write_json('{}({})'.format(callback,
                                                    members['data']))
     elif op == 'teams':
         teams = yield self.option.get_options_list(o_type='teams',
                                                    name='team')
         departments = yield self.option.get_options_list(o_type='teams',
                                                          name='department')
         teams_list = []
         for team in teams:
             department = '火星部门'
             for d in departments:
                 if d.id == json.loads(team.value)['up']:
                     department = json.loads(d.value)['name']
             teams_list.append(
                 dict(tid=team.id,
                      name='{} ({})'.format(
                          json.loads(team.value)['name'], department)))
         return self.write_json(
             dict(status='SUCCESS', message='', data=teams_list))
     else:
         groups = yield self.__get_group()
         members = yield self.__get_members()
     self.write_json(
         dict(status='SUCCESS',
              message='',
              data=dict(groups=groups, members=members)))
コード例 #16
0
 def get(self, op=None, name=None):
     AddLogs().add_logs(ip=self.request.remote_ip)
     if op == 'media' and name == 'files':
         media_path = os.path.join(self.settings.get('static_path'), op,
                                   name, str(self.current_user.id))
         data = list()
         if os.path.isdir(media_path):
             files_list = os.listdir(media_path)
             for file in files_list:
                 file_ext = file.split('.', maxsplit=1)
                 uri = self.static_url('{}/{}/{}/{}'.format(
                     op, name, str(self.current_user.id), file))
                 if file_ext[-1].lower() == 'mp3':
                     data.append(dict(id=file_ext[0], type='AUDIO',
                                      url=uri))
                 elif file_ext[-1].lower() == 'mp4':
                     data.append(dict(id=file_ext[0], type='VIDEO',
                                      url=uri))
                 else:
                     data.append(dict(id=file_ext[0], type='IMAGE',
                                      url=uri))
         self.write_json(dict(status='SUCCESS', message='', data=data))
     else:
         self.write_json(dict(status='FAIL', message='操作类型错误', data=''))
コード例 #17
0
ファイル: user.py プロジェクト: zhengxiaoming1/OpenStark
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     user = self.current_user
     profile = json.loads(user.profile)
     department = ''
     work_id = profile['workerId'] if 'workerId' in profile.keys() else ''
     for oid in profile['department']:
         dep = yield self.option.get_option(oid=oid)
         if dep:
             department = '{} / {}'.format(department, json.loads(dep.value)['name'])
     if user.role == 0:
         authority = 'admin'
     elif user.role == 1 and user.status == 2:
         authority = 'user'
     elif user.role == 1 and user.status == 1:
         authority = 'noActive'
     else:
         authority = 'guest'
     data = dict(name='{}{}'.format(user.realname, '[未激活]' if user.status == 1 else work_id and '[{}]'.format(work_id)),
                 avatar=profile['avatar'], userId=user.id, unreadCount=user.unreadCount, authority=authority,
                 email=user.email, department=department[3:], position=profile['position'], workerId=work_id,
                 department_id=profile['department'], username=user.username, status=user.status,
                 realname=user.realname, token=base64.b16encode(base64.b64encode(user.email.encode('utf8'))).decode('utf8'))
     self.write_json(dict(status='SUCCESS', message='', data=data))
コード例 #18
0
 def get(self):
     AddLogs().add_logs(ip=self.request.remote_ip)
     chart_type = self.get_arguments('type')
     start_time = self.get_argument('startTime', time.strftime('%Y-%m-%d'))
     end_time = self.get_argument('endTime', time.strftime('%Y-%m-%d'))
     pid = self.get_argument('pid', '')
     data_pv = []
     data_active = []
     data_pv_rank = []
     data_active_rank = []
     data_range = []
     tools_list = []
     ret_data = dict()
     if 'pv' in chart_type:
         data = yield self.statistics.statistics(s_type='pv',
                                                 start_time=start_time,
                                                 order_by=['p.id DESC'],
                                                 end_time=end_time,
                                                 group_by=['p.id'],
                                                 status=1)
         for d in data:
             data_pv.append(dict(x=d.projectName, y=d.count))
             data_pv_rank.append(
                 dict(id=str(d.pid), title=d.projectName, total=d.count))
         ret_data['toolsPVRange'] = data_pv
         ret_data['toolsPVRanking'] = sorted(data_pv_rank,
                                             key=lambda k: k['total'],
                                             reverse=True)
     if 'active' in chart_type:
         data = yield self.statistics.statistics(s_type='active',
                                                 start_time=start_time,
                                                 order_by=['p.id DESC'],
                                                 end_time=end_time,
                                                 group_by=['p.id'],
                                                 status=1)
         for d in data:
             data_active.append(dict(x=d.projectName, y=d.count))
             data_active_rank.append(
                 dict(id=str(d.pid), title=d.projectName, total=d.count))
         ret_data['toolsActiveRange'] = data_active
         ret_data['toolsActiveRanking'] = sorted(data_active_rank,
                                                 key=lambda k: k['total'],
                                                 reverse=True)
     if 'data' in chart_type:
         if not pid:
             tools, total = yield self.project.get_projects_list(
                 p_type='tool', status=1)
             for tool in tools:
                 tools_list.append(dict(id=str(tool.id), name=tool.name))
             ret_data['toolsList'] = tools_list
             pid = len(tools_list) and tools_list[0]['id']
         data_p = yield self.statistics.statistics(
             project_id=pid,
             status=1,
             order_by=['s.createTime'],
             s_type='pv',
             group_by=["DATE(s.createTime)"],
             start_time=start_time,
             end_time=end_time)
         if data_p:
             data_a = yield self.statistics.statistics(
                 project_id=pid,
                 status=1,
                 order_by=['s.createTime'],
                 start_time=start_time,
                 s_type='active',
                 group_by=["DATE(s.createTime)"],
                 end_time=end_time)
             for d in data_p:
                 y1 = d.count
                 y2 = 0
                 for a in data_a:
                     if d.createTime.strftime(
                             '%Y-%m-%d') == a.createTime.strftime(
                                 '%Y-%m-%d'):
                         y2 = a.count
                         break
                 data_range.append(
                     dict(x=time.mktime(d.createTime.timetuple()) * 1000,
                          y1=y1,
                          y2=y2))
         else:
             data_range.append(dict(x=time.time() * 1000, y1=0, y2=0))
         ret_data['toolsRangeData'] = sorted(data_range,
                                             key=lambda x: x['y1'],
                                             reverse=True)
     msg = dict(status='SUCCESS', message='', data=ret_data)
     self.write_json(msg)
コード例 #19
0
 def get(self, op=None):
     AddLogs().add_logs(ip=self.request.remote_ip)
     chart_type = self.get_argument('type', 'load')
     start_time = self.get_argument('startTime', time.strftime('%Y-%m-%d'))
     end_time = self.get_argument('endTime', time.strftime('%Y-%m-%d'))
     env = self.get_argument('env', None)
     load_env = list()
     load_names = dict()
     load_data = list()
     ret_data = dict()
     if env is None:
         env_list = yield self.statistics.statistics(s_type=chart_type,
                                                     start_time=start_time,
                                                     join='INNER',
                                                     end_time=end_time,
                                                     group_by=['s.name'])
         for e in env_list:
             test_env = yield self.project.get_project(p_type='env',
                                                       name=e.name)
             test_env = test_env and json.loads(
                 test_env.config).get('title')
             load_env.append(dict(name=test_env or e.name, id=e.name))
         ret_data['loadEvn'] = load_env
         env = len(load_env) and load_env[0]['id']
     if op == 'api':
         page = int(self.get_argument('page', 1))
         size = int(self.get_argument('size', 10))
         kw = self.get_argument('kw', '').strip()
         data = list()
         api_list, total = yield self.statistics.get_statistics_list(
             s_type=chart_type,
             start_time=start_time,
             end_time=end_time,
             group_by=['s.name', 'p.name'],
             order_by=['s.name', 'p.name'],
             limit=size,
             page=page,
             name=env or None,
             search=kw or None)
         no = 0
         for api in api_list:
             no += 1
             desc = api.config and json.loads(api.config)
             test_env = yield self.project.get_project(p_type='env',
                                                       name=env)
             test_env = test_env and json.loads(
                 test_env.config).get('title')
             data.append(
                 dict(key=no + page * size - size,
                      id=api.projectId,
                      env=test_env or api.name,
                      name=api.projectName,
                      showName=desc and desc['showName'],
                      api=desc and desc['url'],
                      description=desc and desc['desc'],
                      userNum=desc and desc['userNum'],
                      threshold=desc and desc['threshold']))
         return self.write_json(
             dict(status='SUCCESS',
                  message='',
                  data=dict(total=total, page=page, size=size, data=data)))
     if env:
         names = yield self.statistics.statistics(
             s_type=chart_type,
             start_time=start_time,
             join='INNER',
             end_time=end_time,
             group_by=['p.name'],
             name=env,
             fields=['p.name', 'p.config'])
         for i in range(len(names)):
             load_names['y{}'.format(i + 1)] = names[i].name
         data = yield self.statistics.statistics(
             s_type=chart_type,
             start_time=start_time,
             end_time=end_time,
             name=env,
             group_by=['DATE(s.createTime)', 'p.name'],
             order_by=['s.createTime'],
             fields=[
                 'p.name', 's.createTime', 'SUM(s.value)/COUNT(s.id) count'
             ])
         temp_time = ''
         for i in range(len(data)):
             x = data[i].createTime.strftime('%Y-%m-%d')
             if x > temp_time:
                 if temp_time:
                     load_data.append(chart)
                 temp_time = x
                 chart = dict(
                     x=time.mktime(data[i].createTime.timetuple()) * 1000)
             if x == temp_time:
                 for key in load_names:
                     if load_names[key] == data[i].name:
                         chart[key] = round(data[i].count, 3)
                         break
             if i + 1 == len(data):
                 load_data.append(chart)
         for n in names:
             for ln in load_names:
                 if load_names[ln] == n.name:
                     if n.config and json.loads(n.config)['showName']:
                         load_names[ln] = json.loads(n.config)['showName']
                         break
     if not load_data:
         load_data.append(dict(x=time.time() * 1000, y1=0, y2=0))
     ret_data['loadData'] = load_data
     ret_data['loadNames'] = load_names
     msg = dict(status='SUCCESS', message='', data=ret_data)
     self.write_json(msg)
コード例 #20
0
 def get(self, op=None, do=None):
     AddLogs().add_logs(ip=self.request.remote_ip)
     if op == 'server':
         if do == 'list':
             page = int(self.get_argument('page', 1))
             size = int(self.get_argument('size', 10))
             key_word = self.get_argument('keyWord', '').strip()
             status = self.get_argument('status', None)
             e_type = self.get_argument('type', '')
             env_list, total = yield self.project.get_projects_list(
                 p_type='env', page=page, limit=size, status=status or None, search=key_word or e_type or None)
             data = list()
             no = 0
             for env in env_list:
                 desc = json.loads(env.config)
                 if e_type and e_type.find(desc.get('type')) == -1:
                     total -= 1
                     continue
                 no += 1
                 data.append(dict(no=no+page*size-size, key=env.id, eid=env.name, title=desc.get('title'),
                                  type=desc.get('type'), description=desc.get('description'),
                                  principal=desc.get('principal').get('name'), status=env.status,
                                  uid=desc.get('principal').get('uid'), dep=desc.get('principal').get('dep'),
                                  username=desc.get('principal').get('username')))
             self.write_json(dict(status='SUCCESS', message='',
                                  data=dict(data=data, total=total, page=page, size=size)))
         elif do == 'all':
             env_list, total = yield self.project.get_projects_list(p_type='env', status=1)
             data = list()
             for env in env_list:
                 desc = json.loads(env.config)
                 data.append(dict(key=env.id, id=env.name, title=desc.get('title'),
                                  description=desc.get('description')))
             self.write_json(dict(status='SUCCESS', message='',
                                  data=dict(data=data, total=total, page=1, size=10)))
         else:
             self.write_json(dict(status='FAIL', message='操作类型错误', data=''))
     elif op == 'detail':
         if do == 'list':
             page = int(self.get_argument('page', 1))
             size = int(self.get_argument('size', 10))
             key_word = self.get_argument('keyWord', '').strip()
             status = self.get_argument('status', None)
             e_type = self.get_argument('type', '')
             network = self.get_argument('network', '')
             eid = self.get_argument('eid', '')
             detail_list, total = yield self.setting.get_settings_list(
                 s_type='env', name=eid, page=page, limit=size, status=status or None, search=key_word or None)
             data = list()
             no = 0
             for detail in detail_list:
                 desc = json.loads(detail.value)
                 if (e_type and e_type.find(desc.get('type')) == -1) or (
                         network and network.find(desc.get('network')) == -1):
                     total -= 1
                     continue
                 no += 1
                 data.append(dict(no=no+page*size-size, key=detail.id, title=desc.get('title'),
                                  type=desc.get('type'), description=desc.get('description'),
                                  host=desc.get('host'), ip=desc.get('ip'), status=detail.status,
                                  port=desc.get('port'), user=desc.get('user'), mac=desc.get('mac'),
                                  password=desc.get('password'), network=desc.get('network')))
             self.write_json(dict(status='SUCCESS', message='',
                                  data=dict(data=data, total=total, page=page, size=size)))
         elif do == 'all':
             eid = self.get_argument('eid', '')
             detail_list, total = yield self.setting.get_settings_list(s_type='env', name=eid, status=1)
             data = list()
             keys = list()
             for detail in detail_list:
                 desc = json.loads(detail.value)
                 if desc.get('type') != self.get_argument('type', 'OS') or desc.get('ip').strip() in keys:
                     continue
                 data.append(dict(key=detail.id, title=desc.get('ip').strip(),
                                  description=desc.get('title').strip(), id=desc.get('ip').strip()))
                 keys.append(desc.get('ip').strip())
             self.write_json(dict(status='SUCCESS', message='',
                                  data=dict(data=data, total=total, page=1, size=10)))
         else:
             self.write_json(dict(status='FAIL', message='操作类型错误', data=''))
     else:
         self.write_json(dict(status='FAIL', message='操作类型错误', data=''))
コード例 #21
0
    def post(self, op=None, do=None):
        AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
        data = yield self.get_request_body_to_json()
        if op == 'server':
            if do == 'edit':
                desc = dict(description=data.get('description'), title=data.get('title'), type=data.get('type'),
                            principal=dict(name=data.get('principal'), username=data.get('username'),
                                           uid=data.get('uid'), dep=data.get('dep')))
                if str(data.key).find('NEW_TEMP_KEY') != -1:
                    eid = str(uuid.uuid1())
                    key, msg = yield self.project.add_project(p_type='env', name=eid, config=desc, status=data.status or 1)
                    if key:
                        ret_msg = dict(status='SUCCESS', message='新增成功!', data=dict(eid=eid, key=key))
                    else:
                        ret_msg = dict(status='FAIL', message=msg, data='')
                else:
                    res, msg = yield self.project.edit_project(pid=data.key, config=desc, status=data.status or None)
                    if res:
                        ret_msg = dict(status='SUCCESS', message='编辑成功!', data=dict(eid=data.eid, key=data.key))
                    else:
                        ret_msg = dict(status='FAIL', message=msg, data='')
            elif do == 'delete':
                res, msg = yield self.project.delete_project(pid=data.key)
                if res:
                    ret_msg = dict(status='SUCCESS', message='删除成功!', data='')
                else:
                    ret_msg = dict(status='FAIL', message=msg, data='')
            elif do == 'host':
                env_list, total = yield self.setting.get_settings_list(
                    s_type='env', name=data.get('eid'), status=1)
                data = list()
                hosts = list()
                for env in env_list:
                    desc = json.loads(env.value)
                    host = (desc.get('ip').strip(), desc.get('host').strip())
                    if desc.get('host').strip() and desc.get('ip').strip() and host not in hosts:
                        data.append('{}\t\t{}\t\t# {}'.format(
                            desc.get('ip').strip(), desc.get('host').strip(), desc.get('title').strip()))
                        hosts.append(host)
                ret_msg = dict(status='SUCCESS', message='获取HOST成功!', data='\n'.join(data))
            else:
                ret_msg = dict(status='FAIL', message='操作类型错误', data='')
        elif op == 'detail':
            if do == 'edit':
                if self.common_func.check_string(data.get('ip').strip(), 'ip'):
                    desc = dict(description=data.get('description'), title=data.get('title'), type=data.get('type'),
                                host=data.get('host'), ip=data.get('ip'), port=data.get('port'),  user=data.get('user'),
                                mac=data.get('mac'), password=data.get('password'), network=data.get('network') or 'no')
                    if str(data.key).find('NEW_TEMP_KEY') != -1:
                        server = yield self.project.get_project(name=data.eid, p_type='env')
                        if server:
                            key, msg = yield self.setting.add_setting(
                                s_type='env', pid=server.id, name=data.eid, value=desc, status=data.status or 1)
                            if key:
                                ret_msg = dict(status='SUCCESS', message='新增成功!', data=dict(key=key))
                            else:
                                ret_msg = dict(status='FAIL', message=msg, data='')
                        else:
                            ret_msg = dict(status='FAIL', message='所要编辑的环境信息不存在!', data='')
                    else:
                        res, msg = yield self.setting.edit_setting(sid=data.key, value=desc, status=data.status or None)
                        if res:
                            ret_msg = dict(status='SUCCESS', message='编辑成功!', data=dict(key=data.key))
                        else:
                            ret_msg = dict(status='FAIL', message=msg, data='')
                else:
                    ret_msg = dict(status='FAIL', message='IP地址格式不对, 请检查!', data='')
            elif do == 'delete':
                res, msg = yield self.setting.delete_setting(sid=data.key)
                if res:
                    ret_msg = dict(status='SUCCESS', message='删除成功!', data='')
                else:
                    ret_msg = dict(status='FAIL', message=msg, data='')
            elif do == 'status':
                ret_data = list()
                server = yield self.setting.get_settings_by_id(sid=data.key)
                for svr in server:
                    desc = json.loads(svr.value)
                    env_type = desc.get('type')
                    env_ip = desc.get('ip') or ''
                    env_port = desc.get('port') or ''
                    env_user = desc.get('user') or ''
                    env_password = desc.get('password') or ''
                    env_title = desc.get('title') or ''
                    if env_type == 'OS':
                        if env_title.strip().split('_', maxsplit=1)[0].lower().startswith('linux'):
                            linux_shell = '''
                            mac1=`ifconfig -a|grep -C 2 %s|awk 'NR==1{print}'|awk '{print $5}'`&&mac2=`ifconfig -a|grep -C 2 %s|awk 'END{print}'|awk '{print $2}'`&&net=`ping -c 2 www.baidu.com|awk 'END{print}'`&&echo "$mac1 mac1"&&echo "$mac2 mac2"&&echo "$net net"
                            ''' % (env_ip.strip(), env_ip.strip())
                            flag, msg = yield self.thread_func.exec_remote_shell(
                                host=env_ip.strip(), port=env_port.strip(), shell=linux_shell,
                                username=env_user.strip(), password=env_password.strip())
                            if flag:
                                msg = msg.split('\n')
                                if len(msg) == 3:
                                    mac = msg[1] if msg[0].strip() == 'mac1' else msg[0]
                                    net = 'no' if msg[2].strip() == 'net' else 'yes'
                                    desc['mac'] = desc.get('mac') or mac.split()[0].upper()
                                    desc['network'] = net
                                status = 1
                            else:
                                res = yield self.thread_func.check_port(env_ip, env_port)
                                if res:
                                    status = 1
                                else:
                                    status = 0
                            yield self.setting.edit_setting(svr.id, value=desc, status=status)
                            ret_data.append(dict(key=svr.id, status=status, network=desc['network'], mac=desc['mac']))
                    elif env_type == 'APPLICATION':
                        res = yield self.thread_func.check_port(env_ip, env_port)
                        if res:
                            status = 1
                        else:
                            status = 0
                        yield self.setting.edit_setting(svr.id, status=status)
                        ret_data.append(dict(key=svr.id, status=status))
                ret_msg = dict(status='SUCCESS', message='刷新状态成功!', data=ret_data)
            elif do == 'network':
                title = yield self.project.get_project(name=data.eid, p_type='env')
                server = yield self.setting.get_settings_by_id(sid=data.key)
                ips = []
                for svr in server:
                    desc = json.loads(svr.value)
                    if desc.get('ip'):
                        ips.append(desc.get('ip').strip())
                title = '测试环境申请开放外网权限_{}'.format(title and json.loads(title.config).get('title'))
                mail_content = '''
<p>Hi 你好!</p>
<p style="padding-left:30px;">测试人员 ({}) 申请开放本测试环境服务器外网权限,以供功能测试验收。请帮忙处理一下,3ks~</p>
<p style="padding-left:30px;">1、服务器</p>
<p style="padding-left:60px;">{}</p>
<p style="padding-left:30px;">2、使用时间</p>
<p style="padding-left:60px;">开始使用时间:{}</p>
<p style="padding-left:60px;">结束使用时间:{}</p>
<p style="padding-left:30px;">3、备注</p>
<p style="padding-left:60px;">凡是开放了外网权限的服务器必须做到以下准备工作,否则会造成线上问题:</p>
<p style="padding-left:60px;">1、6020-common-service服务必须关闭</p>
<p style="padding-left:60px;">2、短信、邮箱相关配置必须设置为测试配置</p>
<p style="padding-left:60px;">3、使用完毕要及时申请关闭外网权限</p>     
                '''.format(self.current_user.realname, '</br>'.join(set(ips)), data.startTime, data.endTime)
                res, msg = yield self.common_func.send_email(
                    subject=title, content=mail_content, to=net_mail_to, cc=net_mail_cc)
                if res:
                    ret_msg = dict(status='SUCCESS', message='申请邮件发送成功!', data='')
                    for svr in server:
                        desc = json.loads(svr.value)
                        desc['network'] = 'yes'
                        yield self.setting.edit_setting(sid=svr.id, value=desc, create_time=data.endTime)
                else:
                    ret_msg = dict(status='FAIL', message=msg, data='')
            else:
                ret_msg = dict(status='FAIL', message='操作类型错误', data='')
        else:
            ret_msg = dict(status='FAIL', message='操作类型错误', data='')
        self.write_json(ret_msg)
コード例 #22
0
 def post(self):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     configs = yield self.get_request_body_to_json()
     op_type = configs.get('type')
     op = configs.get('op')
     if op_type == 'navLink':
         params = configs.data
         if not self.common_func.check_string(params.href, 'url'):
             return self.write_json(dict(status='FAIL', message='链接格式不对, 请检查!', data=dict(type=op_type)))
         if op == 'edit':
             if params.id == '':
                 res, msg = yield self.option.add_option(o_type='navLink', name=params.title, value=params.href)
                 if res:
                     res_msg = dict(status='SUCCESS', message='保存成功!', data=dict(id=res, type=op_type))
                 else:
                     res_msg = dict(status='FAIL', message=msg, data=dict(type=op_type))
             else:
                 res, msg = yield self.option.edit_option(oid=params.id, name=params.title, value=params.href)
                 if res:
                     res_msg = dict(status='SUCCESS', message='保存成功!', data=dict(type=op_type))
                 else:
                     res_msg = dict(status='FAIL', message=msg, data=dict(type=op_type))
         elif op == 'delete':
             res, msg = yield self.option.delete_option(oid=params.id)
             if res:
                 res_msg = dict(status='SUCCESS', message='删除成功!', data=dict(type=op_type))
             else:
                 res_msg = dict(status='FAIL', message=msg, data=dict(type=op_type))
         else:
             res_msg = dict(status='FAIL', message='操作类型错误!', data=dict(type=op_type))
     else:
         if op_type == 'email' and op == 'test':
             current = self.current_user
             res_msg = dict(status='SUCCESS', message='发送成功!', data=dict(type=op_type))
             params = configs.data
             if len(params) >= 5:
                 mail = Mail(smtp_server=params.emailHost, smtp_port=params.emailPort,
                             smtp_user=params.emailUser, smtp_password=params.emailPasswd,
                             use_ssl=params.get('emailSSL') or 'no', mail_from=params.emailFrom,
                             mail_type=params.get('emailType') or 'normal')
                 message = '''
                 <p>Dear {}:</p>
                 <p>&nbsp;&nbsp;你好, 收到此邮件表示系统邮箱配置正确, 现在开始可以愉快地使用邮件报告功能啦。</p>
                 '''.format(current.username)
                 log.info(message)
                 res, msg = yield mail.send_mail(subject='系统邮件配置成功', message=message, to=[current.email])
                 if not res:
                     log.info(msg)
                     res_msg = dict(status='FAIL', message=str(msg), data=dict(type=op_type))
             else:
                 res_msg = dict(status='FAIL', message='系统邮箱配置不正确!', data=dict(type=op_type))
         else:
             res_msg = dict(status='SUCCESS', message='保存成功!', data=dict(type=op_type))
             for key in configs.data:
                 if key == 'emailPasswd':
                     configs.data[key] = base64.b16encode(configs.data[key].encode('utf8', errors='ignore')).decode('utf8', errors='ignore')
                 res, msg = yield self.option.edit_option(o_type='common', name=key, value=configs.data[key])
                 if not res and configs.data[key]:
                     res, msg = yield self.option.add_option(o_type='common', name=key, value=configs.data[key])
                     if not res:
                         res_msg = dict(status='FAIL', message=msg, data=dict(type=op_type))
     self.write_json(res_msg)
コード例 #23
0
 def post(self, op=None, name=None):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     if not op and not name:
         return self.write_json(
             dict(status='FAIL', message='参数不正确', data=''))
     if op == 'media' and name == 'delete':
         data = yield self.get_request_body_to_json()
         media_path = os.path.join(self.settings.get('static_path'), op,
                                   'files', str(self.current_user.id))
         if os.path.isdir(media_path):
             files_list = os.listdir(media_path)
             for file in files_list:
                 if file.split('.', maxsplit=1)[0] in data.get('keys'):
                     log.info('删除媒体文件#{}'.format(
                         os.path.join(media_path, file)))
                     os.remove(os.path.join(media_path, file))
         return self.write_json(dict(status='SUCCESS', message='', data=op))
     files = self.request.files
     if op == 'media' and name == 'local':
         return self.write_json(
             dict(state="SUCCESS",
                  list=[{
                      'source': url,
                      'url': url,
                      'state': "SUCCESS"
                  } for url in self.get_arguments('source[]')]))
     flag = False
     msg = '上传失败!'
     uri = ''
     if files:
         if op == 'images':
             images_path = os.path.join(self.settings.get('static_path'),
                                        op)
             images = files.get(name)
             if name == 'avatar' and images:
                 images = images[0]
                 filename = images.filename
                 ext = filename.split('.')[-1]
                 filename = '{}.{}'.format(int(time.time() * 10000000), ext)
                 file_path = os.path.join(images_path, name)
                 flag = yield self.__save_file(file_path, filename,
                                               images.body)
                 if flag:
                     msg = '上传成功!'
                     log.info('文件上传成功, 保存在 {}'.format(flag))
                     uri = self.static_url('{}/{}/{}'.format(
                         op, name, filename))
                     profile = json.loads(self.current_user.profile)
                     profile['avatar'] = uri
                     self.user.edit_user(uid=self.current_user.id,
                                         profile=profile)
             else:
                 flag = False
         elif op == 'files':
             files_path = os.path.join(self.settings.get('static_path'), op)
             files_list = files.get(name)
             test_type = self.get_argument('test_type', 'caseG')
             if name == 'testCase' and files_list:
                 file = files_list[0]
                 filename = file.filename
                 ext = filename.split('.')[-1]
                 filename = '{}.{}'.format(int(time.time() * 10000000), ext)
                 file_path = os.path.join(files_path, name)
                 flag = file_path = yield self.__save_file(
                     file_path, filename, file.body)
                 if flag:
                     log.info('文件上传成功, 保存在 {}'.format(file_path))
                     if os.path.isfile(file_path):
                         workbook = load_workbook(file_path, read_only=True)
                         try:
                             table = workbook[workbook.sheetnames[0]]
                             if table.max_row > 1 and table.max_column == 11:
                                 count_add = 0
                                 count_edit = 0
                                 for i in range(1, table.max_row):
                                     cid = table['B{}'.format(i + 1)].value
                                     project = table['D{}'.format(i +
                                                                  1)].value
                                     module = table['E{}'.format(i +
                                                                 1)].value
                                     title = table['F{}'.format(i +
                                                                1)].value
                                     description = table['G{}'.format(
                                         i + 1)].value
                                     expected = table['H{}'.format(i +
                                                                   1)].value
                                     status = table['I{}'.format(i +
                                                                 1)].value
                                     author = table['J{}'.format(i +
                                                                 1)].value
                                     executor = table['K{}'.format(i +
                                                                   1)].value
                                     desc = dict(
                                         description=description or '',
                                         expected=expected or '',
                                         function='' or '',
                                         executor=executor or '',
                                         title=title or '',
                                         module=module or '',
                                         userId=self.current_user.id,
                                         author=author
                                         or self.current_user.realname
                                         or '')
                                     if test_type == 'case':
                                         status = 2 if status == '已转自动化' else 1 if status == '手动执行' else 0
                                     else:
                                         status = 2 if status == '已实现' else 1 if status == '开发中' else 0
                                     if not cid:
                                         key, msg = yield self.setting.add_setting(
                                             s_type=test_type,
                                             name=cid or '',
                                             value=desc,
                                             status=status,
                                             project=project
                                             and project.strip())
                                         if key:
                                             count_add += 1
                                     else:
                                         projects, total = yield self.setting.get_settings_list(
                                             name=cid,
                                             project=project,
                                             limit=None,
                                             s_type=test_type)
                                         if projects:
                                             for p in projects:
                                                 desc[
                                                     'function'] = json.loads(
                                                         p.value
                                                     ).get('function') or ''
                                                 desc[
                                                     'userId'] = json.loads(
                                                         p.value).get(
                                                             'userId') or ''
                                                 desc['urls'] = json.loads(
                                                     p.value).get(
                                                         'urls') or list()
                                                 key, msg = yield self.setting.edit_setting(
                                                     sid=p.id,
                                                     value=desc,
                                                     status=status)
                                                 if key:
                                                     count_edit += 1
                                         else:
                                             key, msg = yield self.setting.add_setting(
                                                 s_type=test_type,
                                                 name=cid,
                                                 value=desc,
                                                 project=project,
                                                 status=status)
                                             if key:
                                                 count_add += 1
                                 msg = '测试用例成功导入 {} 条, 编辑 {} 条!'.format(
                                     count_add, count_edit)
                             else:
                                 flag = False
                                 msg = '没有用例数据或用例模板格式不对, 请检查后重新导入!'
                         except Exception as e:
                             log.error(e)
                             flag = False
                             msg = '{}#{}'.format('测试用例导入失败', e)
                         workbook.close()
                         try:
                             os.remove(file_path)
                         except os.error as e:
                             log.info(e)
                     else:
                         flag = False
                         msg = '文件上传成功但保存失败!'
             else:
                 flag = False
         else:
             media_path = os.path.join(self.settings.get('static_path'), op)
             file = files.get(name)
             if name == 'files' or name == 'file' and file:
                 name = 'files'
                 file = file[0]
                 filename = file.filename
                 ext = filename.split('.')[-1]
                 filename = '{}.{}'.format(str(uuid.uuid1()), ext)
                 file_path = os.path.join(media_path, name,
                                          str(self.current_user.id))
                 flag = yield self.__save_file(file_path, filename,
                                               file.body)
                 if flag:
                     msg = '上传成功!'
                     log.info('文件上传成功, 保存在 {}'.format(flag))
                     uri = self.static_url('{}/{}/{}/{}'.format(
                         op, name, str(self.current_user.id), filename))
             else:
                 flag = False
     if flag:
         self.write_json(
             dict(status='SUCCESS',
                  message=msg,
                  data=uri,
                  state='SUCCESS',
                  url=uri,
                  title=self.get_body_argument('name', ''),
                  original=self.get_body_argument('name', '')))
     else:
         self.write_json(
             dict(status='FAIL',
                  message=msg,
                  data='',
                  state=msg,
                  url='',
                  title='',
                  original=''))
コード例 #24
0
 def post(self, op=None):
     AddLogs().add_logs(ip=self.request.remote_ip, op_type='active')
     data = yield self.get_request_body_to_json()
     if op == 'edit':
         config = dict(showName=data.showName,
                       url=data.api,
                       desc=data.description,
                       threshold=data.threshold,
                       userNum=data.userNum)
         res, msg = yield self.project.edit_project(pid=data.id,
                                                    config=config)
         if res:
             msg = dict(status='SUCCESS', message='编辑成功!', data='')
         else:
             msg = dict(status='FAIL', message=msg, data='')
         return self.write_json(msg)
     elif op == 'delete':
         res, msg = yield self.project.delete_project(pid=data.id)
         if res:
             self.statistics.delete_statistics(project_id=data.id)
             msg = dict(status='SUCCESS', message='删除成功!', data='')
         else:
             msg = dict(status='FAIL', message=msg, data='')
         return self.write_json(msg)
     if data is None:
         key = self.get_argument('key', '').strip()
         name = self.get_argument('name', '').strip()
         duration = self.get_argument('time', '').strip()
         ip = self.get_argument('ip', '').strip()
         url = self.get_argument('url', '').strip()
         description = self.get_argument('description', '').strip()
         user_num = self.get_argument('userNum', '150').strip()
         threshold = self.get_argument('threshold', '50').strip()
         token = self.get_argument('token', '').strip()
         data = munchify(
             dict(key=key,
                  name=name,
                  time=duration,
                  ip=ip,
                  url=url,
                  token=token,
                  description=description,
                  userNum=user_num,
                  threshold=threshold))
     msg = dict(status='FAIL',
                message='参数key、time、url、ip, token必填, 并且time字段需大于0!',
                data='')
     if data and data.key and data.time and float(
             data.time) > 0 and data.ip and data.url and data.token:
         user = dict()
         if data.token.strip():
             try:
                 email = base64.b64decode(
                     base64.b16decode(
                         data.token.strip().encode('utf8'))).decode('utf8')
                 user = yield self.user.get_user_info(email, status=2)
             except Exception as e:
                 log.error(e)
         if not user:
             return self.write_json(
                 dict(status='FAIL', message='Token不正确!', data=''))
         tran = yield self.project.get_project(p_type='sLoad',
                                               name=data.key)
         if tran:
             tran_id = tran.id
         else:
             tran_id, msg = yield self.project.add_project(
                 p_type='sLoad',
                 name=data.key,
                 config=dict(userId=user.get('id'),
                             showName=data.name,
                             url=data.url,
                             desc=data.description,
                             author=user.get('realname'),
                             threshold=data.threshold,
                             userNum=data.userNum))
         if tran_id:
             env, total = yield self.setting.get_settings_list(
                 s_type='env', search=data.ip)
             name = data.ip
             for e in env:
                 value = json.loads(e.value)
                 if value.get('ip').strip() == data.ip.strip():
                     name = value.name
                     break
             res, msg = yield self.statistics.add_statistics(
                 project_id=tran_id,
                 name=name,
                 value=float(data.time),
                 s_type='load')
             if res:
                 msg = dict(status='SUCCESS', message=msg, data='')
             else:
                 msg = dict(status='FAIL', message=msg, data='')
         else:
             msg = dict(status='FAIL', message=msg, data='')
     self.write_json(msg)
コード例 #25
0
    def get(self, op='gui', do='case'):
        AddLogs().add_logs(ip=self.request.remote_ip)
        start_time = self.get_argument('startTime', '1970-01-01')
        end_time = self.get_argument('endTime', '1970-01-01')
        key = self.get_argument('key', '')
        status = self.get_argument('status', None)
        if op == 'gui':
            if do == 'case':
                if status is not None:
                    sql = '''
                    SELECT p.teamId, IF(s.`status`=0, '已废弃', IF(s.`status`=1, '开发中', '已实现')) project, COUNT(s.id) num 
                    FROM t_settings s JOIN t_projects p ON p.id = s.projectId 
                    WHERE s.type = 'caseG' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59' GROUP BY p.teamId, s.`status`;
                    '''.format(start_time, end_time)
                else:
                    sql = '''
                    SELECT p.`name` project, p.teamId, COUNT(s.id) num 
                    FROM t_settings s JOIN t_projects p ON p.id = s.projectId 
                    WHERE s.type = 'caseG' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59' GROUP BY s.projectId, p.teamId;
                    '''.format(start_time, end_time)
                data = dict()
                count_list = yield self.statistics.custom_statistics(sql=sql)
                for count in count_list:
                    if count.teamId not in data.keys():
                        data[count.teamId] = [
                            dict(x=count.project, y=count.num)
                        ]
                    else:
                        data[count.teamId].append(
                            dict(x=count.project, y=count.num))
                if status is not None:
                    ret_data = dict(caseStatus=data)
                else:
                    ret_data = dict(guiCaseData=data)
                ret_msg = dict(status='SUCCESS', message='', data=ret_data)
            elif do == 'reports':
                ret_data = dict()
                if not key:
                    jobs, total = yield self.setting.get_settings_list(
                        s_type='jobG')
                    jobs_dict = dict()
                    for job in jobs:
                        desc = json.loads(job.value)
                        jobs_dict[job.name] = desc.get('title')
                    sql = '''
                    SELECT s.`name`, s.`value`, s.`createTime`
                    FROM t_settings s 
                    WHERE s.type = 'reportG' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59';
                    '''.format(start_time, end_time)
                    reports = yield self.statistics.custom_statistics(sql=sql)
                    report_list = list()
                    for report in reports:
                        if report.name in jobs_dict.keys(
                        ) and report.name not in [
                                k['id'] for k in report_list
                        ]:
                            report_list.append(
                                dict(id=report.name,
                                     name=jobs_dict[report.name]))
                            key = key or report_list[0]['id']
                    ret_data['guiJobs'] = report_list
                else:
                    sql = '''
                    SELECT s.`name`, s.`value`, s.`createTime`
                    FROM t_settings s 
                    WHERE s.type = 'reportG' AND s.`name`='{}' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59';
                    '''.format(key, start_time, end_time)
                    reports = yield self.statistics.custom_statistics(sql=sql)
                report_data = list()
                sql = '''
                SELECT s.projectId, p.`name` project, COUNT(s.id) num 
                FROM t_settings s JOIN t_projects p ON p.id = s.projectId 
                WHERE s.projectId = (SELECT t.projectId FROM t_settings t WHERE t.type = 'jobG' AND t.`name` = '{}') 
                AND s.type = 'caseG' AND s.`status` > 1 GROUP BY p.teamId, s.`status`;
                '''.format(key)
                project = yield self.statistics.custom_statistics(sql=sql)
                pid = project[0].get('num') if project else 1
                for report in reports:
                    desc = json.loads(report.value)
                    if report.name == key:
                        run_rate = round(
                            (desc.get('runCases') or 0) / (pid or 1) * 100, 2)
                        y1 = desc.get('runCases', 0)
                        y2 = desc.get('passCases', 0)
                        y3 = round(
                            desc.get('passCases', 0) /
                            desc.get('runCases', 1) * 100, 2)
                        y4 = 100 if run_rate > 100 else run_rate
                        if not y1 and not y2 and not y3 and not y4:
                            continue
                        report_data.append(
                            dict(x=time.mktime(report.createTime.timetuple()) *
                                 1000,
                                 y1=y1,
                                 y2=y2,
                                 y3=y3,
                                 y4=y4))
                if not report_data:
                    report_data.append(
                        dict(x=time.time() * 1000, y1=0, y2=0, y3=0, y4=0))
                ret_data['guiReports'] = report_data
                report_data = list()
                for report in reports:
                    desc = json.loads(report.value)
                    if report.name == key:
                        y1 = round(desc.get('line', 0) * 100, 2)
                        y2 = round(desc.get('branch', 0) * 100, 2)
                        y3 = round(desc.get('method', 0) * 100, 2)
                        y4 = round(desc.get('classes', 0) * 100, 2)
                        if not y1 and not y2 and not y3 and not y4:
                            continue
                        report_data.append(
                            dict(x=time.mktime(report.createTime.timetuple()) *
                                 1000,
                                 y1=y1,
                                 y2=y2,
                                 y3=y3,
                                 y4=y4))
                if not report_data:
                    report_data.append(
                        dict(x=time.time() * 1000, y1=0, y2=0, y3=0, y4=0))
                ret_data['guiJacoco'] = report_data
                ret_msg = dict(status='SUCCESS', message='', data=ret_data)
            else:
                ret_msg = dict(status='FAIL', message='操作类型错误!', data='')
        elif op == 'api':
            if do == 'case':
                if status is not None:
                    sql = '''
                    SELECT p.teamId, IF(s.`status`=0, '已废弃', IF(s.`status`=1, '开发中', '已实现')) project, COUNT(s.id) num 
                    FROM t_settings s JOIN t_projects p ON p.id = s.projectId 
                    WHERE s.type = 'caseA' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59' GROUP BY p.teamId, s.`status`;
                    '''.format(start_time, end_time)
                else:
                    sql = '''
                    SELECT p.`id` pid, p.`name` project, p.teamId tid, count(tmp.url) apinum, ctmp.num casenum 
FROM (SELECT * FROM (SELECT s.projectId pid, SUBSTRING_INDEX(s.`name`, '?', 1) url FROM t_settings s WHERE s.type = 'suiteA' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59') as utmp GROUP BY utmp.pid, utmp.url) as tmp 
RIGHT JOIN t_projects p ON p.id = tmp.pid JOIN (SELECT p.`id` pid, p.`name` project, p.teamId tid, count(s.name) num FROM t_settings s 
JOIN t_projects p ON p.id = s.projectId WHERE s.type = 'caseA' AND s.createTime BETWEEN '{} 00:00:00' AND '{} 23:59:59'
GROUP BY p.teamId, p.id) ctmp ON ctmp.tid = p.teamId AND ctmp.pid = p.id GROUP BY p.teamId, p.id;
                    '''.format(start_time, end_time, start_time, end_time)
                data = dict()
                case_list = yield self.statistics.custom_statistics(sql=sql)
                if status is not None:
                    for count in case_list:
                        if count.teamId not in data.keys():
                            data[count.teamId] = [
                                dict(x=count.project, y=count.num)
                            ]
                        else:
                            data[count.teamId].append(
                                dict(x=count.project, y=count.num))
                    ret_data = dict(caseStatus=data)
                else:
                    data_list = dict()
                    for case in case_list:
                        if case.tid not in data_list.keys():
                            data_list[case.tid] = {
                                case.pid:
                                dict(name=case.project,
                                     y=case.casenum,
                                     z=case.apinum)
                            }
                        else:
                            if case.pid not in data_list[case.tid].keys():
                                data_list[case.tid][case.pid] = dict(
                                    name=case.project,
                                    y=case.casenum,
                                    z=case.apinum)
                            else:
                                project = data_list[case.tid][case.pid]
                                data_list[case.tid][case.pid] = dict(
                                    name=case.project,
                                    y=project['y'] + case.casenum,
                                    z=project['z'] + case.apinum)
コード例 #26
0
ファイル: knowledge.py プロジェクト: zhengxiaoming1/OpenStark
from handlers.common import BaseHandler, authenticated_async