def initialize(self, **kwargs): super(Handler, self).initialize(**kwargs) self.svc = DataBaseService() self.svc.__enter__() self.db = self.svc.db logger.warning("<" + "=" * 25 + " [initialize] " + "=" * 25 + ">") self.handler_return_url()
def post_role_group_ops(role_id, group_ops): result = get_role_group_ops(role_id) role_group_obj = result["data"]["role_group_obj"] role_group_op_list = role_group_obj.keys() logger.info("============================") logger.info(set(role_group_op_list)) logger.info(set(group_ops)) logger.info("============================") need_deletes = set(role_group_op_list) - set(group_ops) group_op_list = [(g, op) for g, op in [_str.split(".") for _str in group_ops]] need_delete_list = [ (g, op) for g, op in [_str.split(".") for _str in need_deletes] ] for g, op in group_op_list: instance, created = PT_Role_Group_Ops.get_or_create( role_id=int(role_id), group_keycode=g, op_keycode=op) with DataBaseService({}) as svc: for g, op in need_delete_list: svc.db.query(PT_Role_Group_Ops).filter( PT_Role_Group_Ops.role_id == int(role_id), PT_Role_Group_Ops.group_keycode == g, PT_Role_Group_Ops.op_keycode == op).delete() data = { "return_code": 0, "return_message": u"", "data": { "sys_groups": sys_groups } } return data
def get_role_group_ops(role_id): conditions = and_() conditions.append(PT_Role_Group_Ops.role_id == role_id) with DataBaseService({}) as svc: pt_role = svc.db.query(PT_Role).filter(PT_Role.id == role_id).one() role_group_ops = svc.db.query(PT_Role_Group_Ops).filter( conditions).order_by( PT_Role_Group_Ops.role_id.asc(), PT_Role_Group_Ops.group_keycode.asc(), PT_Role_Group_Ops.op_keycode.asc(), ) role_group_ops = [ r_g_o.as_dict(["group_keycode", "op_keycode"]) for r_g_o in role_group_ops ] role_group_obj = { "%s.%s" % (str(int(d["group_keycode"])), str(int(d["op_keycode"]))): "%s.%s" % (GROUP.get(int(d["group_keycode"])).keyword if GROUP.get( int(d["group_keycode"])) else "", OP[int( d["op_keycode"])].keyword) for d in role_group_ops } data = { "return_code": 0, "return_message": u"", "data": { "pt_role": pt_role.as_dict(), "sys_groups": sys_groups, "role_group_obj": role_group_obj } } print data return data
def post_user_roles(user_id, role_ids): result = get_user_roles(user_id) user_role_obj = result["data"]["role_obj"] user_role_list = [str(i) for i in user_role_obj.keys()] # logger.info("============================") # logger.info(set(role_group_op_list)) # logger.info(set(group_ops)) # logger.info("============================") need_deletes = set(user_role_list) - set(role_ids) logger.info(need_deletes) # role_list = [(g, op) for g, op in [_str.split(".") for _str in role_ids]] # need_delete_list = [(g, op) for g, op in [_str.split(".") for _str in need_deletes]] for role_id in role_ids: instance, created = PT_User_Role.get_or_create( user_id=int(user_id), role_id=int(role_id), ) with DataBaseService({}) as svc: for role_id in need_deletes: svc.db.query(PT_User_Role).filter( PT_User_Role.user_id == int(user_id), PT_User_Role.role_id == int(role_id)).delete() data = { "return_code": 0, "return_message": u"", "data": { "roles": result["data"]["roles"] } } return data
def get_project_list(kwargs={}): logger.info("------[celery task get_project_list]------") with DataBaseService(kwargs) as svc: projects = svc.db.query(Pro_Info).all() project_list = [i.as_dict() for i in projects] logger.info("project_list") res = {"return_code": 0, "return_message": "", "data": project_list} return res
def on_message(self, message): logger.error("====[status onmessage]====") self.svc = DataBaseService() self.svc.__enter__() logger.error("\t WebSocket message: %s" % message) json_message = simplejson.loads(message) if json_message["action"] == "init_status": # svc = ProResourceApplyService(self, {"res_id": json_message["res_id"]}) # resource_res = svc.get_resource() # user_id = resource_res.data.user_id user_id = json_message["user_id"] svc = PtUserService(self, {"user_id": user_id}) pt_user_res = svc.get_info() if pt_user_res.return_code == 0: current_perms = pt_user_res.data.get_current_perms() if "pro_resource_apply.view" in current_perms: imchecker = False else: imchecker = True svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() data = { "tasks_res": tasks_res, "imchecker": imchecker, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "task_html": self.render_to_string("admin/notice/tasks.html", **data) } chat.update(json_message) logger.error(chat) self.write_message(chat) # self.on_finish() # chat.update(json_message) # EchoWebSocket.send_message(chat) # self.write_message(u"You said: " + message) elif json_message["action"] == "offline": EchoWebSocket.users.pop(str(json_message["user_id"])) else: self.write_message(u"You said: " + message) self.svc.db.commit() self.svc.db.close() logger.error("====[status finish]====")
def task_act_post(act_type=1, table_name="", table_doc=""): logger.info("------[celery task post act]------") logger.info("------[ act type %s ]------" % act_type) with DataBaseService({}) as svc: act = Act_History() act.act_type = act_type act.desc = act_actions[act_type].value % table_doc svc.db.add(act) svc.db.flush()
def get_list(search=""): with DataBaseService({}) as svc: or_conditions = or_() or_conditions.append(PT_User.username.like("%" + search + "%")) pt_users = svc.db.query(PT_User).filter(or_conditions).order_by( PT_User.id.desc()).all() pt_users = [i.as_dict() for i in pt_users] data = {"return_code": 0, "return_message": u"", "data": pt_users} return data
def get_info(perm_id): with DataBaseService({}) as svc: pt_perm = svc.db.query(PT_Perm).filter(PT_Perm.id == perm_id).one() data = { "return_code": 0, "return_message": u"", "data": pt_perm.as_dict() } return data
def on_message(self, message): logger.error("====[index onmessage]====") self.svc = DataBaseService() self.svc.__enter__() logger.error("\t WebSocket message: %s" % message) json_message = simplejson.loads(message) if json_message["action"] == "pro_resource_apply": self.do_notice_user(json_message) elif json_message["action"] == "notice_checker": self.do_notice_checker(json_message) elif json_message["action"] == "join": self.do_online(json_message) elif json_message["action"] == "offline": EchoWebSocket.users.pop(str(json_message["user_id"])) else: self.write_message(u"You said: " + message) self.svc.db.commit() self.svc.db.close() logger.error("====[index finish]====")
def task_post_action(act_type=1, content=u"", user_id=0): logger.info("------[celery task post action]------") logger.info("------[ act type %s ]------" % act_type) with DataBaseService({}) as svc: act = Act_History() act.act_type = act_type act.desc = content act.user_id = user_id svc.db.add(act) svc.db.flush()
def get_info(user_id): with DataBaseService({}) as svc: pt_user = svc.db.query(PT_User).filter(PT_User.id == user_id).one() data = { "return_code": 0, "return_message": u"", "data": { "pt_user": pt_user.as_dict() } } return data
def delete_info(user_id): with DataBaseService({}) as svc: is_success = svc.db.query(PT_User).filter( PT_User.id == user_id, ).delete() data = { "return_code": 0, "return_message": u"", "data": { "success": is_success } } return data
def get_info(role_id): with DataBaseService({}) as svc: pt_role = svc.db.query(PT_Role).filter(PT_Role.id == role_id).one() data = { "return_code": 0, "return_message": u"", "data": { "pt_role": pt_role.as_dict(), "sys_groups": sys_groups } } return data
def publish_notice_user(user_id=0): logger.info("#"*30+" [user %s notice_user tasks] "%user_id+"#"*30) action = "on_notice_user" with DataBaseService({}) as DBSvc: svc = PtUserService(DBSvc) pt_users_res = svc.get_list() user_ids = [u.id for u in pt_users_res.data if "pro_resource_apply.check" in u.get_current_perms()] pub_svc = TaskPublish(DBSvc) pub_svc.publish_tasks(user_id, action=action) for this_id in user_ids: # 通知所有审核员 pub_svc.publish_tasks(this_id) logger.info("#"*30+" [user %s notice_user tasks finish] "%user_id+"#"*30) return True
def update_info(role_id, name=u"", desc=u"", remark=u""): with DataBaseService({}) as svc: role = svc.db.query(PT_Role).filter(PT_Role.id == role_id, ).one() role.name = name role.desc = desc role.remark = remark svc.db.add(role) data = { "return_code": 0, "return_message": u"", "data": { "pt_role": role.as_dict(), "sys_groups": sys_groups } } return data
def get_user_roles(user_id): conditions = and_() conditions.append(PT_User_Role.user_id == user_id) with DataBaseService({}) as svc: role_list = svc.db.query(PT_Role).filter( PT_Role.is_enable == 1).order_by(PT_Role.id.asc(), ) roles = [r.as_dict() for r in role_list] role_obj = {} user_roles = svc.db.query(PT_User_Role).filter( PT_User_Role.user_id == user_id).all() role_group_obj = {} for user_role in user_roles: role_group_ops = user_role.role.group_ops # role_group_ops = svc.db.query( # PT_Role_Group_Ops # ).outerjoin( # PT_User_Role, PT_Role_Group_Ops.role_id == PT_User_Role.role_id # ).filter( # conditions # ).order_by( # PT_Role_Group_Ops.role_id.asc(), # PT_Role_Group_Ops.group_keycode.asc(), # PT_Role_Group_Ops.op_keycode.asc(), # ) role_group_ops = [ r_g_o.as_dict(["role_id", "group_keycode", "op_keycode"]) for r_g_o in role_group_ops ] # pprint(role_group_ops) role_group_obj.update({ "%s.%s" % (str(int(d["group_keycode"])), str(int(d["op_keycode"]))): "%s.%s" % (GROUP[int(d["group_keycode"])].keyword, OP[int( d["op_keycode"])].keyword) for d in role_group_ops }) role_obj.update({user_role.role.id: role_group_obj}) data = { "return_code": 0, "return_message": u"", "data": { "roles": roles, "role_obj": role_obj, "role_group_obj": role_group_obj } } return data
def task_post_pro_res_apply_history(status=0, content=u"", pro_id=0, res_apply_id=0, user_id=0, checker_id=0): logger.info("------[celery task post action]------") with DataBaseService({}) as svc: act = Act_Pro_History() act.pro_id = pro_id act.res_apply_id = res_apply_id act.status = status act.desc = content act.user_id = user_id act.checker_id = checker_id svc.db.add(act) svc.db.flush()
def get_or_create(name, desc=u"", remark=u""): role_info, created = PT_Role.get_or_create(name=name, ) role_info.desc = desc role_info.remark = remark with DataBaseService({}) as svc: svc.db.add(role_info) # role_res = svc.db.query( # PT_Role # ).filter( # PT_Role.id == role_info.id # ).first() data = { "return_code": 0, "return_message": u"", # "data": role_res.as_dict() } return data
def get_or_create(username, password): """ 添加管理用户 """ user_instance, created = PT_User.get_or_create(username=username) user_instance.password = password with DataBaseService({}) as svc: svc.db.add(user_instance) user_info = svc.db.query(PT_User).filter( PT_User.username == username).first() data = { "return_code": 0, "return_message": u"", "data": { "pt_user": user_info.as_dict() } } return data
def update_info(user_id, username=u"", password=u""): # import time # time.sleep(60) with DataBaseService({}) as svc: user_filter = svc.db.query(PT_User).filter(PT_User.id == user_id, ) pprint(str(user_filter)) user = user_filter.one() user.username = username user.password = password svc.db.add(user) data = { "return_code": 0, "return_message": u"", "data": { "pt_user": user.as_dict() } } return data
def update_info(perm_id, name, keyword): with DataBaseService({}) as svc: perm = svc.db.query(PT_Perm).filter(PT_Perm.id == perm_id, ).one() perm.name = name perm.keyword = keyword svc.db.add(perm) # .update( # { # PT_Perm.name: name, # PT_Perm.keyword: keyword, # } # ) data = { "return_code": 0, "return_message": u"", "data": { "is_success": True } } return data
# -*- coding: utf-8 -*- import uuid from os.path import abspath, dirname, join current_path = abspath(dirname(__file__)) import sys sys.path.insert(0, join(current_path, '..', "scloud")) # sys.path.insert(0, join(current_path, '..')) from scloud.config import logger # from scloud.async_services.listener import init_listener from scloud.models.base import DataBaseService from scloud.models.project import Pro_Info from scloud.services.svc_project import ProjectService #init_listener() if __name__ == '__main__': logger.info("-----[0 post_act_history]------") # try: dbsvc = DataBaseService({}) dbsvc._db_init() svc = ProjectService(dbsvc, {"env": 2, "status": ""}) svc.filter_list()
def publish_tasks(user_id, action="on_task", template="admin/notice/tasks.html"): with DataBaseService({"user_id": user_id}) as DBSvc: pub_svc = TaskPublish(DBSvc) pub_svc.publish_tasks(user_id) return True
class EchoWebSocket(MySocketHandler): users = dict() def check_origin(self, origin): return True def open(self): logger.info("WebSocket opened") # current_user = self.current_user # from code import interact # interact(local=locals()) # EchoWebSocket.users.update({current_user.id: self}) @classmethod def send_message(cls, chat): waiter = cls.users.get(str(chat["user_id"])) if waiter: waiter.write_message(simplejson.dumps(chat)) @classmethod def send_all(cls, chat): for waiter in cls.users.values(): waiter.write_message(simplejson.dumps(chat)) def on_message(self, message): logger.error("====[index onmessage]====") self.svc = DataBaseService() self.svc.__enter__() logger.error("\t WebSocket message: %s" % message) json_message = simplejson.loads(message) if json_message["action"] == "pro_resource_apply": self.do_notice_user(json_message) elif json_message["action"] == "notice_checker": self.do_notice_checker(json_message) elif json_message["action"] == "join": self.do_online(json_message) elif json_message["action"] == "offline": EchoWebSocket.users.pop(str(json_message["user_id"])) else: self.write_message(u"You said: " + message) self.svc.db.commit() self.svc.db.close() logger.error("====[index finish]====") def on_close(self): logger.info("WebSocket closed") def do_online(self, json_message): user_id = json_message["user_id"] svc = PtUserService(self, {"user_id": user_id}) pt_user_res = svc.get_info() pt_user = pt_user_res.data logger.info("pt_user: %s"% pt_user) data = { "level": "info", "content": u"%s已经上线!" % (pt_user.username or pt_user.email or pt_user.mobile), } try: html = self.render_to_string("admin/notice/online.html", **data) except Exception as e: logThrown() html = "" chat = { "user_id": pt_user.id, "html": html } chat.update(json_message) EchoWebSocket.users.update({user_id: self}) EchoWebSocket.send_all(chat) logger.info("**users: %s" % EchoWebSocket.users) # self.on_finish() def do_notice_user(self, json_message): svc = ProResourceApplyService(self, {"res_id": json_message["res_id"]}) resource_res = svc.get_resource() user_id = resource_res.data.user_id svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() logger.info(resource_res.data.user_id) logger.info(resource_res.data.checker_id) data = { "tasks_res": tasks_res, "imchecker": False, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "data": resource_res.data.as_dict(), "html": self.render_to_string("admin/notice/tasks.html", **data) } logger.error(chat) chat.update(json_message) EchoWebSocket.send_message(chat) # self.on_finish() # self.write_message(u"You said: " + message) def do_notice_checker(self, json_message): logger.info("-----------------------------NOTICE CHECKER-----------------------------") svc = PtUserService(self) pt_users_res = svc.get_list() user_ids = [u.id for u in pt_users_res.data if "pro_resource_apply.check" in u.get_current_perms()] for user_id in user_ids: svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() data = { "tasks_res": tasks_res, "imchecker": True, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "html": self.render_to_string("admin/notice/tasks.html", **data) } chat.update(json_message) logger.error(chat) EchoWebSocket.send_message(chat)
class EchoWebSocket(MySocketHandler): users = dict() def check_origin(self, origin): return True def open(self): logger.info("WebSocket opened") # current_user = self.current_user # from code import interact # interact(local=locals()) # EchoWebSocket.users.update({current_user.id: self}) @classmethod def send_message(cls, chat): waiter = cls.users.get(str(chat["user_id"])) if waiter: waiter.write_message(simplejson.dumps(chat)) @classmethod def send_all(cls, chat): for waiter in cls.users.values(): waiter.write_message(simplejson.dumps(chat)) def on_message(self, message): logger.error("====[index onmessage]====") self.svc = DataBaseService() self.svc.__enter__() logger.error("\t WebSocket message: %s" % message) json_message = simplejson.loads(message) if json_message["action"] == "pro_resource_apply": self.do_notice_user(json_message) elif json_message["action"] == "notice_checker": self.do_notice_checker(json_message) elif json_message["action"] == "join": self.do_online(json_message) elif json_message["action"] == "offline": EchoWebSocket.users.pop(str(json_message["user_id"])) else: self.write_message(u"You said: " + message) self.svc.db.commit() self.svc.db.close() logger.error("====[index finish]====") def on_close(self): logger.info("WebSocket closed") def do_online(self, json_message): user_id = json_message["user_id"] svc = PtUserService(self, {"user_id": user_id}) pt_user_res = svc.get_info() pt_user = pt_user_res.data logger.info("pt_user: %s" % pt_user) data = { "level": "info", "content": u"%s已经上线!" % (pt_user.username or pt_user.email or pt_user.mobile), } try: html = self.render_to_string("admin/notice/online.html", **data) except Exception as e: logThrown() html = "" chat = {"user_id": pt_user.id, "html": html} chat.update(json_message) EchoWebSocket.users.update({user_id: self}) EchoWebSocket.send_all(chat) logger.info("**users: %s" % EchoWebSocket.users) # self.on_finish() def do_notice_user(self, json_message): svc = ProResourceApplyService(self, {"res_id": json_message["res_id"]}) resource_res = svc.get_resource() user_id = resource_res.data.user_id svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() logger.info(resource_res.data.user_id) logger.info(resource_res.data.checker_id) data = { "tasks_res": tasks_res, "imchecker": False, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "data": resource_res.data.as_dict(), "html": self.render_to_string("admin/notice/tasks.html", **data) } logger.error(chat) chat.update(json_message) EchoWebSocket.send_message(chat) # self.on_finish() # self.write_message(u"You said: " + message) def do_notice_checker(self, json_message): logger.info( "-----------------------------NOTICE CHECKER-----------------------------" ) svc = PtUserService(self) pt_users_res = svc.get_list() user_ids = [ u.id for u in pt_users_res.data if "pro_resource_apply.check" in u.get_current_perms() ] for user_id in user_ids: svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() data = { "tasks_res": tasks_res, "imchecker": True, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "html": self.render_to_string("admin/notice/tasks.html", **data) } chat.update(json_message) logger.error(chat) EchoWebSocket.send_message(chat)
class EchoWebSocket(MySocketHandler): users = dict() def check_origin(self, origin): return True def open(self): logger.info("WebSocket opened") # current_user = self.current_user # from code import interact # interact(local=locals()) # EchoWebSocket.users.update({current_user.id: self}) @classmethod def send_message(cls, chat): waiter = cls.users.get(str(chat["user_id"])) if waiter: waiter.write_message(simplejson.dumps(chat)) @classmethod def send_all(cls, chat): for waiter in cls.users.values(): waiter.write_message(simplejson.dumps(chat)) def on_message(self, message): logger.error("====[status onmessage]====") self.svc = DataBaseService() self.svc.__enter__() logger.error("\t WebSocket message: %s" % message) json_message = simplejson.loads(message) if json_message["action"] == "init_status": # svc = ProResourceApplyService(self, {"res_id": json_message["res_id"]}) # resource_res = svc.get_resource() # user_id = resource_res.data.user_id user_id = json_message["user_id"] svc = PtUserService(self, {"user_id": user_id}) pt_user_res = svc.get_info() if pt_user_res.return_code == 0: current_perms = pt_user_res.data.get_current_perms() if "pro_resource_apply.view" in current_perms: imchecker = False else: imchecker = True svc = ActHistoryService(self, {"user_id": user_id}) tasks_res = svc.get_res_tasks() data = { "tasks_res": tasks_res, "imchecker": imchecker, "STATUS_RESOURCE": STATUS_RESOURCE } chat = { "user_id": user_id, "task_html": self.render_to_string("admin/notice/tasks.html", **data) } chat.update(json_message) logger.error(chat) self.write_message(chat) # self.on_finish() # chat.update(json_message) # EchoWebSocket.send_message(chat) # self.write_message(u"You said: " + message) elif json_message["action"] == "offline": EchoWebSocket.users.pop(str(json_message["user_id"])) else: self.write_message(u"You said: " + message) self.svc.db.commit() self.svc.db.close() logger.error("====[status finish]====") def on_close(self): logger.info("WebSocket closed")
class Handler(BaseHandler, HandlersMixin): __metaclass__ = HandlerMeta def __str__(self): return self.__doc__ or self.__class__.__name__ def initialize(self, **kwargs): super(Handler, self).initialize(**kwargs) self.svc = DataBaseService() self.svc.__enter__() self.db = self.svc.db logger.warning("<" + "=" * 25 + " [initialize] " + "=" * 25 + ">") self.handler_return_url() def init_messages(self): if "messages" not in self.session: self.session["messages"] = [] self.messages = self.session.get("messages", []) self.save_session() def add_message(self, content, level="info", post_action=False, url=""): if post_action: self.post_action(content=content, level=level) self.session["messages"].append({"level": level, "content": content, "url": url}) self.session["messages_request"] = len(self.session["messages"]) self.save_session() # logger.info(self.session) def post_action(self, content="", level="info"): current_user = self.session.get("current_user") if current_user: user_id = current_user.id else: user_id = 0 task_post_action.delay(act_type=1, content=content, user_id=user_id) def get_messages(self): self.messages = self.session["messages"] logger.info(self.messages) self.session["messages"] = [] self.save_session() return self.messages def on_finish(self): # logger.info("\t" + "====[EXIT]====") # self.svc.__exit__(None, None, None) # try: # # transaction = session_dict.get("transaction") # # logger.error("transaction: %s" % transaction) # #if transaction: # # dispatch = session_dict.get("dispatch") # self.db.commit() # # self.db.flush() # logger.info("\t" + "====[COMMIT]====") # except Exception: # logThrown() # self.db.rollback() # logger.info("\t" + "====[ROLLBACK]====") # self.db.remove() self.db.close() logger.info("\t" + "====[CLOSE]====") # logger.info(self.db.is_active) # logger.info("====================== [http method (%s)] ======================" % self.request.method) # self.db.is_active # self.db.remove() # self.db.close() # logger.info(self.db) # logger.info(self.db.is_active) logger.critical("<" + "="*25 + " [finish] " + "="*25 + ">") def prepare(self): logger.warning("<" + "="*25 + " [prepare] " + "="*25 + ">") # self.svc._db_init() # self.svc.db.begin_nested() # self.svc.db.begin() # self.db = self.svc.db logger.info("\t" + "====================== [http method] ======================") logger.info("\t" + self.request.method) logger.info("\t" + "====================== [args] ======================") logger.info("\t %s" % self.args) self.init_messages() self.pjax = self.request.headers.get("X-PJAX") headers = self.request.headers x_requested_with = headers.get("X-Requested-With", "") self.ajax = x_requested_with == "XMLHttpRequest" if self.pjax: self.ajax = False def success(self, data): return self.failure(data=data) def failure(self, return_code=0, return_message="", data=None): result = ObjectDict() result.return_code = return_code result.return_message = return_message result.data = data return result def render_to_string(self, template, **kwargs): logger.info("\t [messages]:%s" % self.session["messages"]) if self.pjax: title = self.__doc__ or self.__class__.__name__ title = title.encode("utf-8") self.set_header("title", urllib.quote(title)) self.set_header("active", self.kwargs.get("active", "")) template = "%s_pjax.html" % template.split(".html")[0] tmpl = env.get_template(template) s = "&".join( ["%s=%s" % (k, v) for k, v in self.args.items() \ if k not in ["page", "_pjax", "_xsrf"]] ) logger.info(s) kwargs.update({ "CONF": CONF, "getattr": getattr, "dir": dir, "rand_time": time.time(), "handler": self, "request": self.request, "reverse_url": self.application.reverse_url, "ERR": ERR, "env_colors": env_colors, "STATUS_RESOURCE": STATUS_RESOURCE, "RESOURCE_BANDWIDTH": RESOURCE_BANDWIDTH, "STATUS_PRO_TABLES": STATUS_PRO_TABLES, "STATUS_PRIORITY": STATUS_PRIORITY, "STATUS_YESNO": STATUS_YESNO, "PRO_USER_TYPES": PRO_USER_TYPES, "PLOT_LOADBALANCE": PLOT_LOADBALANCE, "LOADBALANCE_HEALTH": LOADBALANCE_HEALTH, "GROUP": GROUP, "OP": OP, "s": s + "&" if s else "" }) # logger.info("\t [render_to_string kwargs]: %s" % kwargs) template_string = tmpl.render(**kwargs) return template_string def render(self, template, **kwargs): template_string = self.render_to_string(template, **kwargs) self.write(template_string.strip()) def getPage(self, objects, numsPerpage=8, total_count=0, page_name='page'): try: page_num = int(self.args.get(page_name, '1')) except ValueError: page_num = 1 logger.info("[page_name]: %s" % page_name) logger.info("[page_name %s]: [page_num]: %s" % (page_name, self.args.get(page_name, '1'))) logger.info("[page_num]: %s" % page_num) try: _total_count = total_count or objects.count() except Exception as e: _total_count = total_count or len(objects) paginator = Paginator(objects, numsPerpage, total_count=_total_count) try: page = paginator.page(page_num) except InvalidPage: raise HTTPError(404) if not page: raise HTTPError(404) return page # # @gen.coroutine def get_error_html(self, status_code, **kwargs): return ""
class Handler(BaseHandler, HandlersMixin): __metaclass__ = HandlerMeta def __str__(self): return self.__doc__ or self.__class__.__name__ def initialize(self, **kwargs): super(Handler, self).initialize(**kwargs) self.svc = DataBaseService() self.svc.__enter__() self.db = self.svc.db logger.warning("<" + "=" * 25 + " [initialize] " + "=" * 25 + ">") self.handler_return_url() def init_messages(self): if "messages" not in self.session: self.session["messages"] = [] self.messages = self.session.get("messages", []) self.save_session() def add_message(self, content, level="info", post_action=False, url=""): if post_action: self.post_action(content=content, level=level) self.session["messages"].append({ "level": level, "content": content, "url": url }) self.session["messages_request"] = len(self.session["messages"]) self.save_session() # logger.info(self.session) def post_action(self, content="", level="info"): current_user = self.session.get("current_user") if current_user: user_id = current_user.id else: user_id = 0 task_post_action.delay(act_type=1, content=content, user_id=user_id) def get_messages(self): self.messages = self.session["messages"] logger.info(self.messages) self.session["messages"] = [] self.save_session() return self.messages def on_finish(self): # logger.info("\t" + "====[EXIT]====") # self.svc.__exit__(None, None, None) # try: # # transaction = session_dict.get("transaction") # # logger.error("transaction: %s" % transaction) # #if transaction: # # dispatch = session_dict.get("dispatch") # self.db.commit() # # self.db.flush() # logger.info("\t" + "====[COMMIT]====") # except Exception: # logThrown() # self.db.rollback() # logger.info("\t" + "====[ROLLBACK]====") # self.db.remove() self.db.close() logger.info("\t" + "====[CLOSE]====") # logger.info(self.db.is_active) # logger.info("====================== [http method (%s)] ======================" % self.request.method) # self.db.is_active # self.db.remove() # self.db.close() # logger.info(self.db) # logger.info(self.db.is_active) logger.critical("<" + "=" * 25 + " [finish] " + "=" * 25 + ">") def prepare(self): logger.warning("<" + "=" * 25 + " [prepare] " + "=" * 25 + ">") # self.svc._db_init() # self.svc.db.begin_nested() # self.svc.db.begin() # self.db = self.svc.db logger.info( "\t" + "====================== [http method] ======================") logger.info("\t" + self.request.method) logger.info("\t" + "====================== [args] ======================") logger.info("\t %s" % self.args) self.init_messages() self.pjax = self.request.headers.get("X-PJAX") headers = self.request.headers x_requested_with = headers.get("X-Requested-With", "") self.ajax = x_requested_with == "XMLHttpRequest" if self.pjax: self.ajax = False def success(self, data): return self.failure(data=data) def failure(self, return_code=0, return_message="", data=None): result = ObjectDict() result.return_code = return_code result.return_message = return_message result.data = data return result def render_to_string(self, template, **kwargs): logger.info("\t [messages]:%s" % self.session["messages"]) if self.pjax: title = self.__doc__ or self.__class__.__name__ title = title.encode("utf-8") self.set_header("title", urllib.quote(title)) self.set_header("active", self.kwargs.get("active", "")) template = "%s_pjax.html" % template.split(".html")[0] tmpl = env.get_template(template) s = "&".join( ["%s=%s" % (k, v) for k, v in self.args.items() \ if k not in ["page", "_pjax", "_xsrf"]] ) logger.info(s) kwargs.update({ "CONF": CONF, "getattr": getattr, "dir": dir, "rand_time": time.time(), "handler": self, "request": self.request, "reverse_url": self.application.reverse_url, "ERR": ERR, "env_colors": env_colors, "STATUS_RESOURCE": STATUS_RESOURCE, "RESOURCE_BANDWIDTH": RESOURCE_BANDWIDTH, "STATUS_PRO_TABLES": STATUS_PRO_TABLES, "STATUS_PRIORITY": STATUS_PRIORITY, "STATUS_YESNO": STATUS_YESNO, "PRO_USER_TYPES": PRO_USER_TYPES, "PLOT_LOADBALANCE": PLOT_LOADBALANCE, "LOADBALANCE_HEALTH": LOADBALANCE_HEALTH, "GROUP": GROUP, "OP": OP, "s": s + "&" if s else "" }) # logger.info("\t [render_to_string kwargs]: %s" % kwargs) template_string = tmpl.render(**kwargs) return template_string def render(self, template, **kwargs): template_string = self.render_to_string(template, **kwargs) self.write(template_string.strip()) def getPage(self, objects, numsPerpage=8, total_count=0, page_name='page'): try: page_num = int(self.args.get(page_name, '1')) except ValueError: page_num = 1 logger.info("[page_name]: %s" % page_name) logger.info("[page_name %s]: [page_num]: %s" % (page_name, self.args.get(page_name, '1'))) logger.info("[page_num]: %s" % page_num) try: _total_count = total_count or objects.count() except Exception as e: _total_count = total_count or len(objects) paginator = Paginator(objects, numsPerpage, total_count=_total_count) try: page = paginator.page(page_num) except InvalidPage: raise HTTPError(404) if not page: raise HTTPError(404) return page # # @gen.coroutine def get_error_html(self, status_code, **kwargs): return ""