def get_request_body_to_json(self): params = self.request.body if isinstance(params, bytes): params = params.decode('utf8') try: params = munchify(json.loads(params)) except Exception as e: log.error(e) params = None return params
def __save_file(self, file_path, filename, data): try: if not os.path.isdir(file_path): os.makedirs(file_path) file_path = os.path.join(file_path, filename) with open(file_path, 'wb') as fp: fp.write(data) return file_path except Exception as e: log.error(e) return None
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)
def add_logs(self, tool_id='1', ip='127.0.0.1', op_type='pv'): try: data = munchify(dict(toolId=tool_id, type=op_type, ip=ip)) tool = yield self.project.get_project(pid=data.toolId) if tool and data.type in ['pv', 'active']: data['name'] = tool.name self.statistics.add_statistics(s_type=data.type, project_id=data.toolId, name=data.ip, value=data) if data.type == 'active': self.statistics.add_statistics(s_type='pv', project_id=data.toolId, name=data.ip, value=data) except Exception as e: log.error(e)
def get_current_user_async(self): user = self.get_secure_cookie('OSTSESSION', None) try: token = self.request.headers.get('Token') if token and not user: user = base64.b64decode( base64.b16decode( token.strip().encode('utf8'))).decode('utf8') except Exception as e: log.error(e) if user is not None: if isinstance(user, bytes): user = user.decode('utf8', errors='ignore') user = yield self.user.get_user_info(email_or_username=user) if not user: self.clear_cookie('OSTSESSION') else: self.set_secure_cookie('OSTSESSION', user.email, expires=time.time() + 1800) return user
def _handle_request_exception(self, e): #from tornado.web import Finish, app_log, gen_log, HTTPError, httputil from tornado.web import app_log, gen_log, HTTPError, httputil #if isinstance(e, Finish): # # Not an error; just finish the request without logging. # if not self._finished: # self.finish(*e.args) # return ## add if isinstance(e, params.InvalidParams): self.set_status(400) self.finish({'error': str(e)}) return ## end try: self.log_exception(*sys.exc_info()) except Exception: # An error here should still get a best-effort send_error() # to avoid leaking the connection. app_log.error("Error in exception logger", exc_info=True) if self._finished: # Extra errors after the request has been finished should # be logged, but there is no reason to continue to try and # send a response. return if isinstance(e, HTTPError): if e.status_code not in httputil.responses and not e.reason: gen_log.error("Bad HTTP status code: %d", e.status_code) self.send_error(500, exc_info=sys.exc_info()) else: self.send_error(e.status_code, exc_info=sys.exc_info()) else: self.send_error(500, exc_info=sys.exc_info())
def send_error(self, status=ServerError.INTERNAL_SERVER_ERROR, **kwargs): if not isinstance(status, ServerResponseStatus): status = ServerError.UNKNOWN if self._headers_written: gen_log.error("Cannot send error response after headers written") if not self._finished: self.finish() return self.clear() reason = None if 'exc_info' in kwargs: exception = kwargs['exc_info'][1] if isinstance(exception, HTTPError) and exception.reason: reason = exception.reason self.set_status(status_code=status.http_code, reason=reason) try: self.write_error(status, **kwargs) except Exception: app_log.error("Uncaught exception in write_error", exc_info=True) if not self._finished: self.finish()
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)
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=''))