def init_db(self): '''初始化数据库 ''' if not web.cache.db.has_key(self.conn_str): if os.name == "nt": db_engine = create_engine(self.conn_str, connect_args={ 'charset': 'utf8', }, echo=False, pool_recycle=5, pool_size=10, max_overflow=5) else: db_engine = create_engine(self.conn_str, connect_args={ 'charset': 'utf8', }, echo=False, convert_unicode=True, pool_recycle=10, pool_size=50, max_overflow=20) db_metadata = MetaData(db_engine) #缓存当前连接的基本信息 web.cache.db[self.conn_str] = web.storage() web.cache.db[self.conn_str].engine = db_engine web.cache.db[self.conn_str].metadata = db_metadata web.cache.db[self.conn_str].tables = {} web.cache.db[self.conn_str].tables_class = {}
def get_cur_except(): ''' 获取当前异常信息 ''' try: exception_type, exception_value, tback = sys.exc_info() frames = [] while tback is not None: filename = tback.tb_frame.f_code.co_filename function = tback.tb_frame.f_code.co_name lineno = tback.tb_lineno - 1 lineno += tback.tb_frame.f_locals.get("__lineoffset__", 0) pre_context_lineno, pre_context, context_line, post_context = \ _get_lines_from_file(filename, lineno, 7) if '__hidetraceback__' not in tback.tb_frame.f_locals: frames.append( web.storage({ 'tback': tback, 'filename': filename, 'function': function, 'lineno': lineno, 'vars': tback.tb_frame.f_locals, 'id': id(tback), 'pre_context': pre_context, 'context_line': context_line, 'post_context': post_context, 'pre_context_lineno': pre_context_lineno, })) tback = tback.tb_next frames.reverse() dict_Data = {} dict_Data['filename'] = frames[0].filename dict_Data['function'] = frames[0].function dict_Data['lineno'] = frames[0].lineno + 1 dict_Data['exception_type'] = prettify(exception_type) dict_Data['exception_value'] = prettify(exception_value) json_result = json.dumps(dict_Data) print json_result return (json_result, dict_Data) except: return None
def search_log_list(self, dictPageInfo, nUserID, sWorkCode, sUserCode, sUserName, nOperaType, sPost, dtDateStart, dtDateEnd): strSql = OperatingLog().query2(OperatingLog, User.UserCode).join( User, OperatingLog.UserID == User.UserID) if nUserID != "": strSql = strSql.filter(OperatingLog.UserID == nUserID) if sWorkCode != "": strSql = strSql.filter(OperatingLog.WorkCode == sWorkCode) if sUserCode != "": strSql = strSql.filter(User.UserCode == sUserCode) if sUserName != "": strSql = strSql.filter(OperatingLog.UserName == sUserName) if nOperaType != "": strSql = strSql.filter(OperatingLog.OperaType == nOperaType) if dtDateStart != "": strSql = strSql.filter(OperatingLog.CreateTime >= dtDateStart) if dtDateEnd != "": strSql = strSql.filter(OperatingLog.CreateTime <= dtDateEnd) # if sPost != "": # strSql = strSql.filter(User.Post == sPost) sSqlOrderBy = self.order_by(strSql, dictPageInfo['nSort']) lsQueryData = sSqlOrderBy.limit(dictPageInfo['nPageSize']).offset( (dictPageInfo['nPageNo'] - 1) * dictPageInfo['nPageSize']).all() if strSql.all(): RowCount = len(strSql.all()) else: RowCount = 0 lsDataSet = [] for objQueryData in lsQueryData: distData = web.storage(**obj_to_dict(objQueryData[0].copy( bind=False))) distData['UserCode'] = objQueryData[1] distData['KeyWord'] = objQueryData[0].KeyWord if objQueryData[0].OperaType: num = objQueryData[0].OperaType num = int(filter(str.isdigit, num.encode('utf-8'))) distData['OperaTypeName'] = dict_to_name(num, 'opera_type') else: distData['OperaTypeName'] = '' lsDataSet.append(distData) Data = result_data(dictPageInfo['nPageNo'], dictPageInfo['nPageSize'], RowCount, lsDataSet) return FuncResult(success=True, msg='操作成功!', data=Data)
def get_request_page_params(): '''获取请求参数 ''' web.header('Content-Type', 'text/plain') try: params = web.storage() params.userid = web.input().get('userid') query_columns = web.input().get('query_columns') query_params = web.input().get('query_params') query_params_value = web.input().get('query_params_value') if query_columns:query_columns = json_to_obj(query_columns) if query_params:query_params = json_to_obj(query_params) if query_params_value:query_params_value = json_to_obj(query_params_value) params.query_columns = query_columns params.query_params = query_params or [] params.query_params_value = query_params_value or {} ispage = web.input().get('ispage') if ispage: ispage = ispage.lower().strip() == 'true' params.ispage = ispage or False page_num = web.input().get('page_num') if page_num: page_num = int(page_num) params.page_num = page_num or 0 page_size = web.input().get('page_size') if page_size: page_size = int(page_size) params.page_size = page_size or 0 params.order = web.input().get('order', '') params.order_desc = web.input().get('order_desc', '') return FuncResult(success=True, value=params) except Exception, ce: print ce.message return FuncResult(fail='传入参数json格式有误!')
def __init__(self, success=False, fail=None, data=None, msg=None, fail_type=None): '''对象初始化 Params: @success:调用返回状态, if True 则data=调用成功结果 else fail,msg=调用失败结果 @fail:调用失败结果(开发) @data:调用成功结果 @msg:调用失败结果(用户) @fail_type:失败类型 ''' self.success = success self.fail = fail self.data = data self.msg = msg self.fail_type = fail_type #code:错误编码, desc:错误的友好显示, #level:错误的级别 , error:真正的异常信息 #static Level DEBUG # DEBUG Level指出细粒度信息事件对调试应用程序是非常有帮助的。 # static Level INFO # INFO level表明 消息在粗粒度级别上突出强调应用程序的运行过程。 # static Level WARN # WARN level表明会出现潜在错误的情形。 # static Level ERROR # ERROR level指出虽然发生错误事件,但仍然不影响系统的继续运行。 # static Level FATAL # FATAL level指出每个严重的错误事件将会导致应用程序的退出。 # static Level ALL # ALL Level是最低等级的,用于打开所有日志记录。 # static Level OFF # OFF Level是最高等级的,用于关闭所有日志记录。 #系统的错误(未知) self.fail_system = web.storage(code=500, desc='系统处理:内部访问错误, 服务器不能处理该请求!', level='error', error=None) #内部逻辑的错误(已知) self.fail_logic = web.storage(code=550, desc='业务处理:逻辑调用出错, 服务器不能处理该请求!', level='info', error=self.fail) #外部接口的错误(未知) self.fail_interface = web.storage(code=551, desc='业务处理:调用服务:{%s}出错, 服务器不能处理该请求!', level='error', error=None) #数据库的错误(已知) self.fail_db = web.storage(code=552, desc='业务处理:数据调用出错, 服务器不能处理该请求!', level='error', error=None) #数据库的错误(已知) self.fail_access = web.storage(code=553, desc='您没有权限进行{%s}的操作!', level='info', error=None) if not self.fail_type: #默认当前错误是内部逻辑错误 self.fail_type = self.fail_logic
def table_query(table_class, query_params, query_params_value, obj_page=None, query_columns=None, order='', order_desc='asc', query_all=False): '''单个表的数据查询 Params: @table_name:要查询的表名 @query_params:查询条件参数 例如 FolioCode=:FolioCode @query_params_value:查询条件参数值 @query_columns:查询指定的字段,为空的则查询所有 @page_size:一页的数据大小, 默认是50 @page_num:页编码, 默认是1 @order:排序字段 @order_desc:排序字段方法, 默认是asc ''' if query_params and not query_params_value: return if not query_all: if len(query_params) >= 0 and len(query_params_value) <= 0: return columns = [] if query_columns: columns = [ getattr(table_class, c) for c in query_columns if hasattr(table_class, c) ] if len(columns) > 0: q = web.ctx.cur_dbsession.query(*columns) else: q = web.ctx.cur_dbsession.query(table_class) if query_params: match_params = False for x in query_params: kargs = {} for y in query_params_value.keys(): if x.find(':' + y) >= 0 and query_params_value[y] is not None: kargs[y] = query_params_value[y] if len(kargs.keys()) > 0: match_params = True q = q.filter(x).params(**kargs) # 如果参数化的查询没有匹配上对应的值则不可查询 if not match_params: return if order != '': if order_desc == 'desc': q = q.order_by(desc(order)) else: q = q.order_by(order) list_data = [] total_count = 0 page_count = 0 if q: # q.options(undefer()) # 分页需要特殊处理 if obj_page: if obj_page['nPageSize']: q = q.limit(obj_page['nPageSize']) if obj_page['nPageNo']: q = q.offset((obj_page['nPageNo'] - 1) * obj_page['nPageSize']) # 分页的时候需要获取记录行数 sql = q.statement.prefix_with('SQL_CALC_FOUND_ROWS') # 查询 if len(columns) > 0: data = web.ctx.cur_dbsession.query( *columns).from_statement(sql).all() else: data = web.ctx.cur_dbsession.query(table_class).from_statement( sql).all() else: data = q.all() if data: for d in data: list_data.append( web.storage(**obj_to_dict(d.copy(bind=False)))) # 分页的时候才需要获取总记录数 if obj_page: rows_count = web.ctx.cur_dbconn.execute( text('SELECT FOUND_ROWS()')).fetchone() if rows_count and len(rows_count) > 0: total_count = rows_count[0] page_count = int( math.ceil(total_count / obj_page['nPageSize'])) return FuncResult(success=True, data={ 'rowCount': total_count, 'pageCount': page_count, 'data': list_data }) return FuncResult(success=True, data={ 'rowCount': total_count, 'pageCount': page_count, 'data': list_data })
import sys if sys.getdefaultencoding() != 'utf-8': reload(sys) sys.setdefaultencoding('utf-8') projPath = config.rootPath # i18nToolsPath = "C:/Python27/Tools/i18n/" i18nToolsPath = os.path.join(config.rootPath, "i18n/") localedir = config.rootPath + '/i18n' from libs import web import gettext import copy import json # Object used to store all translations. allTranslations = web.storage() def get_translations(lang='zh_CN'): # Init translation. if allTranslations.has_key(lang): translation = allTranslations[lang] elif lang is None: translation = gettext.NullTranslations() else: try: translation = gettext.translation( 'messages', localedir, languages=[lang], ) except IOError: