Exemple #1
0
 def get_user_info(cls, token, open_id):
     try:
         a_dict = {
             'access_token': token,
             'appid': Config.OAUTH_APP_ID,
             'openid': open_id
         }
         r = requests.post(Config.OAUTH_USER_URL, a_dict)
         if r.status_code != 200:
             Logger.error("get_user_info error, status_code[%s], content[%s]" % (r.status_code, r.content))
         return r.status_code, r.content
     except:
         Logger.error(traceback.format_exc())
         return None, None
Exemple #2
0
    def edit_machine(cls, machine_id, ssh_user, ssh_ip, ssh_port):
        try:
            a_dict = dict()
            if not machine_id or not ssh_user or not ssh_ip or not ssh_port:
                a_dict['success'] = False
                a_dict['msg'] = 'data invalid'
                return json.dumps(a_dict)

            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                session.query(Machines).filter(
                    Machines.id == machine_id).update({
                        Machines.ssh_user:
                        ssh_user,
                        Machines.ssh_ip:
                        ssh_ip,
                        Machines.ssh_port:
                        ssh_port
                    })
                session.commit()
                db_machine_list = session.query(
                    Machines.id, Machines.ssh_user, Machines.ssh_ip,
                    Machines.ssh_port,
                    Machines.create_time).filter(Machines.id == machine_id)[:]
                a_dict['success'] = True
                a_dict['msg'] = 'ok'
                a_dict['content'] = content = list()
                if len(db_machine_list) > 0:
                    db_machine = db_machine_list[0]
                    a_machine = {
                        'id':
                        db_machine.id,
                        'ssh_user':
                        db_machine.ssh_user,
                        'ssh_ip':
                        db_machine.ssh_ip,
                        'ssh_port':
                        db_machine.ssh_port,
                        'create_time':
                        db_machine.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    }
                    content.append(a_machine)
                    return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = False
            a_dict['msg'] = 'update db failed'
            return json.dumps(a_dict)
    def get(self, *args, **kwargs):
        login_user = self.get_login_user()
        if not login_user:
            return
        Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)

        api = self.get_argument("api", None)
        if not api:
            self.render('order/order_list.html', login_user=login_user)
            return
        room_name = self.get_argument("room_name", None)
        off_set = self.get_argument("off_set", None)
        limit = self.get_argument("limit", None)
        json_text = DbOperator.query_order_list(room_name, off_set, limit)
        self.write(json_text)
Exemple #4
0
    def set_monitor_active(cls, service_id, expect_active):
        try:
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                session.query(Services).filter(
                    Services.id == service_id).update(
                        {Services.is_active: expect_active})
                session.commit()
                values = session.query(
                    Services.id, Services.user_email, Services.service_name,
                    Services.machine_id, Services.start_cmd, Services.stop_cmd,
                    Services.is_active, Services.auto_recover,
                    Services.mail_receiver,
                    Services.create_time).filter(Services.id == service_id)[:]
                a_dict = dict()
                a_dict['success'] = True
                a_dict['msg'] = 'ok'
                a_dict['content'] = content = list()
                if len(values) == 0:
                    return json.dumps(a_dict, ensure_ascii=False)
                else:
                    value = values[0]
                    a_service = dict()
                    content.append(a_service)
                    a_service['id'] = value.id
                    a_service['user_email'] = value.user_email
                    a_service['service_name'] = value.service_name
                    a_service['machine_id'] = value.machine_id
                    a_service['start_cmd'] = value.start_cmd
                    a_service['stop_cmd'] = value.stop_cmd
                    a_service['is_active'] = value.is_active
                    a_service['auto_recover'] = value.auto_recover
                    a_service['mail_receiver'] = value.mail_receiver
                    a_service['create_time'] = value.create_time.strftime(
                        '%Y-%m-%d %H:%M:%S')
                    a_service['healthy_code'] = 0
                    a_service['monitor_time'] = '1970-01-01 00:00:00'

                    # 获取最新监测状态
                    cls.__get_monitor_status(set(service_id), [a_service])
                    return json.dumps(a_dict, ensure_ascii=False)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = False
            a_dict['content'] = None
            a_dict['msg'] = 'update db failed'
            return json.dumps(a_dict, ensure_ascii=False)
Exemple #5
0
 def get_user_info(cls, token, open_id):
     try:
         a_dict = {
             'access_token': token,
             'appid': config.server_oauth_app_id,
             'openid': open_id
         }
         r = requests.post(config.server_oauth_user_url, a_dict)
         if r.status_code != 200:
             Logger.error(
                 "get_user_info error, status_code[%s], content[%s]" %
                 (r.status_code, r.content))
         return r.status_code, r.content
     except:
         Logger.error(traceback.format_exc())
         return None, None
Exemple #6
0
 def get_access_token(cls, code):
     try:
         a_dict = {
             'code': code,
             'appid': Config.OAUTH_APP_ID,
             'appsecret': Config.OAUTH_APP_SECRET,
             'redirect_uri': Config.OAUTH_REDIRECT_URL,
             'grant_type': 'auth_code',
         }
         r = requests.post(Config.OAUTH_TOKEN_URL, a_dict)
         if r.status_code != 200:
             Logger.error("get_access_token error, status_code[%s], content[%s]" % (r.status_code, r.content))
         return r.status_code, r.content
     except:
         Logger.error(traceback.format_exc())
         return None, None
 def get(self):
     login_user = self.get_login_user()
     if not login_user:
         return
     Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
     service_id = self.get_argument('service_id')
     monitor_detail = DbOperator.query_monitor_detail(service_id)
     if not monitor_detail:
         self.redirect('/')
         return
     self.render('monitor/view_monitor.html',
                 login_user=login_user,
                 base=monitor_detail.base_info,
                 healthy=monitor_detail.healthy_check_list,
                 unhealthy=monitor_detail.unhealthy_check_list,
                 rely=monitor_detail.rely_service_list)
 def post(self):
     login_user = self.get_login_user()
     if not login_user:
         return
     Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
     user_name = self.get_argument('user_name')
     user_count = DbOperator.get_user_count(user_name)
     a_dict = dict()
     if user_count is not None:
         a_dict['code'] = 0
         a_dict['msg'] = 'OK'
         a_dict['count'] = user_count
     else:
         a_dict['code'] = 1
         a_dict['msg'] = 'Internal error'
         a_dict['count'] = -1
     self.write(json.dumps(a_dict, ensure_ascii=False))
 def post(self, *args, **kwargs):
     login_user = self.get_login_user()
     if not login_user:
         return
     Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
     room_id = self.get_argument('room_id')
     plat_id = self.get_argument('plat_id')
     checkin_date = self.get_argument('check_in_date')
     checkout_date = self.get_argument('check_out_date')
     user_name = self.get_argument('user_name')
     order_fee = self.get_argument('order_fee')
     person_count = self.get_argument('person_count')
     phone = self.get_argument('phone')
     wechat = self.get_argument('wechat')
     order_desc = self.get_argument('order_desc')
     json_text = DbOperator.insert_one_order(room_id, plat_id, checkin_date, checkout_date, user_name, order_fee, person_count, phone, wechat,
                                             order_desc)
     self.write(json_text)
Exemple #10
0
    def query_machine_list_v2(cls):
        try:
            # 创建session
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                # 查询数据
                value_query = session.query(Machines.id, Machines.ssh_user,
                                            Machines.ssh_ip, Machines.ssh_port)
                values = value_query[:]

                # 返回结果
                a_machine_list = list()
                for value in values:
                    a_machine_list.append(value)
                return a_machine_list
        except:
            Logger.error(traceback.format_exc())
            return None
Exemple #11
0
 def get_access_token(cls, code):
     try:
         a_dict = {
             'code': code,
             'appid': config.server_oauth_app_id,
             'appsecret': config.server_oauth_app_secret,
             'redirect_uri': config.server_oauth_redirect_url,
             'grant_type': 'auth_code',
         }
         r = requests.post(config.server_oauth_token_url, a_dict)
         if r.status_code != 200:
             Logger.error(
                 "get_access_token error, status_code[%s], content[%s]" %
                 (r.status_code, r.content))
         return r.status_code, r.content
     except:
         Logger.error(traceback.format_exc())
         return None, None
Exemple #12
0
    def query_monitor_detail(cls, service_id):
        try:
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                values = session.query(
                    Services.id, Services.user_email, Services.service_name,
                    Services.machine_id, Machines.ssh_user, Machines.ssh_ip,
                    Machines.ssh_port, Services.start_cmd, Services.stop_cmd,
                    Services.is_active, Services.auto_recover,
                    Services.mail_receiver, Services.create_time).join(
                        Machines, Machines.id == Services.machine_id).filter(
                            Services.id == service_id)[:]
                if len(values) == 0:
                    return None

                monitor_detail = MonitorDetail()
                # Set monitor base information
                monitor_detail.base_info = values[0]
                # query check_cmd_list
                values = session.query(
                    CheckCmd.id, CheckCmd.local_check, CheckCmd.check_shell,
                    CheckCmd.operator, CheckCmd.check_value,
                    CheckCmd.good_match).filter(
                        CheckCmd.service_id == service_id)[:]
                for value in values:
                    if value.good_match == 1:
                        # healthy_check_list.append(check_cmd)
                        monitor_detail.healthy_check_list.append(value)
                    else:
                        # unhealthy_check_list.append(check_cmd)
                        monitor_detail.unhealthy_check_list.append(value)

                # query rely services
                values = session.query(
                    Services.id, Services.service_name).join(
                        ServiceRely,
                        Services.id == ServiceRely.rely_id).filter(
                            ServiceRely.service_id == service_id)[:]
                for value in values:
                    monitor_detail.rely_service_list.append(value)
                return monitor_detail
        except:
            Logger.error(traceback.format_exc())
            return None
Exemple #13
0
    def add_one_user(cls, user_email, user_right):
        try:
            user = Users(user_email=user_email, user_right=user_right)
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                session.add(user)
                session.flush()
                session.commit()

                a_dict = dict()
                a_dict['success'] = True
                a_dict['msg'] = 'ok'
                return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = False
            a_dict['msg'] = 'insert into db error'
            return json.dumps(a_dict)
Exemple #14
0
 def query_all_operator(cls):
     try:
         session = sessionmaker(bind=cls.engine)()
         with Defer(session.close):
             values = session.query(Operator.operator)[:]
             content = list()
             for value in values:
                 item = dict()
                 content.append(item)
                 item['operator'] = value.operator
             result = dict()
             result['success'] = True
             result['content'] = content
             return json.dumps(result, ensure_ascii=False)
     except:
         Logger.error(traceback.format_exc())
         a_dict = dict()
         a_dict['success'] = False
         a_dict['content'] = list()
         return json.dumps(a_dict, ensure_ascii=False)
    def edit_user(cls, user_id, user_right):
        try:
            # 创建session
            session = sessionmaker(bind=cls.engine)()

            # 更新并获取用户信息
            count = session.query(UserList).filter(
                UserList.id == user_id).update(
                    {UserList.user_right: user_right})
            if count != 1:
                session.commit()
                session.close()
                a_dict = dict()
                a_dict['success'] = 'false'
                a_dict['content'] = dict()
                return json.dumps(a_dict)

            values = session.query(UserList).filter(UserList.id == user_id)
            # 关闭session
            session.commit()
            session.close()

            # 返回成功
            a_user = dict()
            for value in values:
                a_user['user_id'] = value.id
                a_user['user_account'] = value.user_account
                a_user['user_right'] = value.user_right
                a_user['update_time'] = datetime.datetime.fromtimestamp(
                    value.update_time).strftime('%Y-%m-%d %H:%M:%S')

            a_dict = dict()
            a_dict['success'] = 'true'
            a_dict['content'] = a_user
            return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = 'false'
            a_dict['content'] = dict()
            return json.dumps(a_dict)
    def add_user_account(cls, user_account, user_right):
        try:
            # 创建用户
            now = int(time.time())
            user = UserList(user_account=user_account,
                            user_right=user_right,
                            update_time=now)
            # 创建session
            session = sessionmaker(bind=cls.engine)()
            # 添加用户
            session.add(user)
            # 获取新id
            session.flush()
            new_user_id = user.id
            # 关闭session
            session.commit()
            session.close()

            # 插入成功,返回结果
            a_user_list = list()
            a_user = dict()
            a_user_list.append(a_user)
            a_user['user_id'] = new_user_id
            a_user['user_account'] = user_account
            a_user['user_right'] = user_right
            a_user['update_time'] = datetime.datetime.fromtimestamp(
                now).strftime('%Y-%m-%d %H:%M:%S')

            # 返回成功
            a_dict = dict()
            a_dict['success'] = 'true'
            a_dict['content'] = a_user_list
            a_dict['item_count'] = 1
            return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = 'false'
            a_dict['content'] = list()
            a_dict['item_count'] = 0
            return json.dumps(a_dict)
    def delete_network_list(cls, network_id_list):
        try:
            # 过滤参数
            split_id_list = network_id_list.split(',')
            join_id_list = list()
            for user_id in split_id_list:
                if user_id != '':
                    join_id_list.append(user_id)
            if len(join_id_list) == 0:
                a_dict = dict()
                a_dict['success'] = 'false'
                a_dict['content'] = list()
                return json.dumps(a_dict)

            # 创建session
            session = sessionmaker(bind=cls.engine)()
            # 添加用户
            count = session.query(NetworkList).filter(
                NetworkList.id.in_(join_id_list)).delete(
                    synchronize_session=False)
            # 关闭session
            session.commit()
            session.close()

            if count <= 0:
                a_dict = dict()
                a_dict['success'] = 'false'
                a_dict['content'] = list()
                return json.dumps(a_dict)

            # 返回成功
            a_dict = dict()
            a_dict['success'] = 'true'
            a_dict['content'] = join_id_list
            return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = 'false'
            a_dict['content'] = list()
            return json.dumps(a_dict)
Exemple #18
0
    def add_one_machine(cls, ssh_user, ssh_ip, ssh_port):
        try:
            machine = Machines(ssh_user=ssh_user,
                               ssh_ip=ssh_ip,
                               ssh_port=ssh_port)
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                session.add(machine)
                session.flush()
                session.commit()

                a_dict = dict()
                a_dict['success'] = True
                a_dict['msg'] = 'ok'
                return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = False
            a_dict['msg'] = 'insert into db error'
            return json.dumps(a_dict)
Exemple #19
0
    def get_hour_win(self, ad_network_id, day, hour):
        """
        :type ad_network_id: str
        :type day: datetime
        :type hour: str
        :rtype: int
        """
        if config.server_local_fake:
            return random.randint(100, 10000)

        win = None
        try:
            dt = day.strftime("%Y%m%d")
            win = self.win_redis.get('%s|%s|%s|win' %
                                     (ad_network_id, dt, hour))
        except:
            Logger.error(traceback.format_exc())
        finally:
            if not win:
                win = 0
            win = int(win)
            return win
    def post(self):
        login_user = self.get_login_user()
        if not login_user:
            return
        Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)

        a_dict = dict()
        user_name = self.get_argument('user_name')
        if not user_name:
            a_dict['code'] = 1
            a_dict['msg'] = 'User name is empty'
            self.write(json.dumps(a_dict, ensure_ascii=False))
            return
        code = DbOperator.change_user_name(login_user.user_email, user_name)
        if code == 0:
            self.set_secure_cookie("user_name", user_name, expires_days=None)
            a_dict['code'] = 0
            a_dict['msg'] = 'OK'
        else:
            a_dict['code'] = 2
            a_dict['msg'] = 'Internal error'
        self.write(json.dumps(a_dict, ensure_ascii=False))
    def add_network(cls, network_name):
        try:
            # 创建渠道
            now = int(time.time())
            network = NetworkList(network=network_name, update_time=now)
            # 创建session
            session = sessionmaker(bind=cls.engine)()
            # 添加渠道
            session.add(network)
            # 获取新id
            session.flush()
            new_network_id = network.id
            # 关闭session
            session.commit()
            session.close()

            # 插入成功,返回结果
            a_network_list = list()
            a_network = dict()
            a_network_list.append(a_network)
            a_network['network_id'] = new_network_id
            a_network['network_name'] = network_name
            a_network['update_time'] = datetime.datetime.fromtimestamp(
                now).strftime('%Y-%m-%d %H:%M:%S')

            # 返回成功
            a_dict = dict()
            a_dict['success'] = 'true'
            a_dict['content'] = a_network_list
            a_dict['item_count'] = 1
            return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = 'false'
            a_dict['content'] = list()
            a_dict['item_count'] = 0
            return json.dumps(a_dict)
Exemple #22
0
    def query_all_monitor_base(cls, service_name, off_set, limit):
        try:
            off_set = int(off_set)
            limit = int(limit)
            if limit == -1:
                limit_count = None
            else:
                limit_count = off_set + limit

            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                # 查询数据
                value_query = session.query(Services.id, Services.service_name)
                if service_name != '':
                    like_condition = '%' + service_name + '%'
                    value_query = value_query.filter(
                        Services.service_name.like(like_condition))

                values = value_query[off_set:limit_count]
                # 返回结果
                service_list = list()
                for value in values:
                    a_service = dict()
                    service_list.append(a_service)
                    a_service['id'] = value.id
                    a_service['service_name'] = value.service_name

                # 返回成功
                a_dict = dict()
                a_dict['success'] = True
                a_dict['content'] = service_list
                return json.dumps(a_dict, ensure_ascii=False)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = False
            a_dict['content'] = list()
            return json.dumps(a_dict, ensure_ascii=False)
Exemple #23
0
    def get_hour_position_res(self, ad_network_id, position_id, day, hour):
        """
        :type ad_network_id: str
        :type position_id: str
        :type day: datetime
        :type hour: str
        :rtype: int
        """
        if config.server_local_fake:
            return random.randint(100, 10000)

        res = None
        try:
            dt = day.strftime("%Y%m%d")
            res = self.win_redis.get('%s|%s|%s|%s|res' %
                                     (ad_network_id, position_id, dt, hour))
        except:
            Logger.error(traceback.format_exc())
        finally:
            if not res:
                res = 0
            res = int(res)
            return res
 def get(self):
     login_user = self.get_login_user()
     if not login_user:
         return
     if not login_user.user_right & UserRight.EDIT_MANAGER:
         self.redirect("/")
         return
     Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
     service_id = self.get_argument('service_id')
     monitor_detail = DbOperator.query_monitor_detail(service_id)
     all_rely = DbOperator.query_all_monitor_base_v2(service_id)
     all_machine = DbOperator.query_machine_list_v2()
     if monitor_detail is None or all_rely is None or all_machine is None:
         self.redirect('/')
         return
     self.render('monitor/edit_monitor.html',
                 login_user=login_user,
                 base=monitor_detail.base_info,
                 healthy=monitor_detail.healthy_check_list,
                 unhealthy=monitor_detail.unhealthy_check_list,
                 rely_id_set=set([item.id for item in monitor_detail.rely_service_list]),
                 all_rely=all_rely,
                 all_machine=all_machine)
Exemple #25
0
    def delete_monitor_detail(cls, service_id):
        try:
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                # check weather it can be deleted
                count = session.query(ServiceRely).filter(
                    ServiceRely.rely_id == service_id).count()
                if count > 0:
                    result = dict()
                    result['success'] = False
                    result['code'] = DbError.RELY_EXIST_ERROR
                    return json.dumps(result, ensure_ascii=False)

                # delete from services
                session.query(Services).filter(
                    Services.id == service_id).delete(
                        synchronize_session=False)
                # delete from check cmd
                session.query(CheckCmd).filter(
                    CheckCmd.service_id == service_id).delete(
                        synchronize_session=False)
                # delete from rely
                session.query(ServiceRely).filter(
                    ServiceRely.service_id == service_id).delete(
                        synchronize_session=False)
                session.commit()

                result = dict()
                result['success'] = True
                result['code'] = DbError.OK
                return json.dumps(result, ensure_ascii=False)
        except:
            Logger.error(traceback.format_exc())
            result = dict()
            result['success'] = False
            result['code'] = DbError.DB_OPERATE_ERROR
            return json.dumps(result, ensure_ascii=False)
    def post(self):
        login_user = self.get_login_user()
        if not login_user:
            return
        Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
        room_name = self.get_argument('room_name')
        sale_plat = self.get_argument('sale_plat')
        room_pwd_date = self.get_argument('room_pwd_date')
        room_pwd = self.get_argument('room_pwd')
        rooter_name = self.get_argument('rooter_name')
        rooter_pwd = self.get_argument('rooter_pwd')
        wifi_name = self.get_argument('wifi_name')
        wifi_pwd = self.get_argument('wifi_pwd')
        electric_date = self.get_argument('electric_date')
        electric_fee = self.get_argument('electric_fee')
        water_date = self.get_argument('water_date')
        water_fee = self.get_argument('water_fee')
        gas_date = self.get_argument('gas_date')
        gas_fee = self.get_argument('gas_fee')
        net_date = self.get_argument('net_date')
        net_fee = self.get_argument('net_fee')
        room_desc = self.get_argument('room_desc')

        a_dict = dict()
        if not room_name:
            a_dict['code'] = 1
            a_dict['msg'] = 'Room name is empty'
            self.write(json.dumps(a_dict, ensure_ascii=False))
            return
        user_id = self.get_secure_cookie('user_id')
        code, msg = DbOperator.insert_one_room(user_id, room_name, sale_plat, room_pwd_date, room_pwd,
                                               rooter_name, rooter_pwd, wifi_name, wifi_pwd, electric_date,
                                               electric_fee, water_date, water_fee, gas_date, gas_fee,
                                               net_date, net_fee, room_desc)
        a_dict['code'] = code
        a_dict['msg'] = msg
        self.write(json.dumps(a_dict, ensure_ascii=False))
Exemple #27
0
    def get_user_info(cls, user_email):
        """
        :type user_email: str
        :rtype: Users
        """
        try:
            session = sessionmaker(bind=cls.engine)()
            with Defer(session.close):
                values = session.query(Users).filter(
                    Users.user_email == user_email)

                user = None
                for value in values:
                    user = value
                    break

                if not user:
                    Logger.error("query user_email[%s] from users get none" %
                                 user_email)
                    return None
                return user
        except:
            Logger.error(traceback.format_exc())
            return None
    def get(self):
        if Config.FAKE_LOGIN:
            # 本机fake登录
            self.redirect('/fake_login')
            return

        # 线上真实登录
        Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
        user_email = self.get_current_user()
        if user_email:
            if self.check_login_valid():
                self.redirect("/")
                return

        code_from_auth = self.get_argument('code', None)
        if not code_from_auth:
            redirect_url = Config.OAUTH_AUTH_URL
            redirect_url += '?appid=%s' % Config.OAUTH_APP_ID
            redirect_url += '&response_type=code'
            redirect_url += '&redirect_uri=%s' % quote(Config.OAUTH_REDIRECT_URL)
            redirect_url += '&scope=user_info'
            redirect_url += '&state=test'
            self.redirect(redirect_url)
            return

        status, content = Login.get_access_token(code_from_auth)
        if status != 200:
            self.write(content)
            return
        Logger.info("get_access_token: [%s]" % content)

        try:
            a_dict = json.loads(content)
        except:
            Logger.error("parse token error: content[%s]" % content)
            self.write(content)
            return

        access_token = a_dict.get("access_token", None)
        openid = a_dict.get("openid", None)
        status, content = Login.get_user_info(access_token, openid)
        if status != 200:
            self.write(content)
            return
        Logger.info("get_user_info: [%s]" % content)

        try:
            a_dict = json.loads(content)
        except:
            Logger.error("parse user_info error: contnet[%s]" % content)
            self.write(content)
            return

        user_name = a_dict.get("name")
        user_email = a_dict.get("email")
        db_user = DbOperator.get_user_info(user_email)
        if not db_user:
            self.redirect('/refuse')
            return

        # 保存session
        self.set_secure_cookie("user_email", user_email, expires_days=None)
        self.set_secure_cookie("user_name", user_name, expires_days=None)
        self.set_secure_cookie("user_right", str(db_user.user_right), expires_days=None)
        self.set_secure_cookie("last_time", str(time.time()), expires_days=None)
        self.set_cookie("page_right", str(db_user.user_right), expires_days=None)

        # 重向定
        self.redirect("/")
Exemple #29
0
    def fetch_network(self, dt, ad_network_id):
        try:
            a_list = list()

            # 获取日期
            now = datetime.now()
            day = datetime.strptime(dt, '%Y-%m-%d')
            dt = day.strftime("%Y-%m-%d")

            # 获取天数据
            impression, click = self.get_day_impression_click(
                ad_network_id, day)
            total_dict = dict()
            total_dict['dt'] = dt
            total_dict['hour'] = '--'
            total_dict['ad_network_id'] = ad_network_id
            total_dict['position_id'] = '--'
            total_dict['pv'] = 0
            total_dict['impression'] = impression
            total_dict['click'] = click
            total_dict['ctr'] = '%.2f' % (
                100.0 * click / impression) if impression != 0 else '0.00'
            total_dict['req'] = 0
            total_dict['res'] = 0
            total_dict['win'] = 0
            total_dict['update_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
            a_list.append(total_dict)

            # 计算小时范围
            today_dt = now.strftime("%Y-%m-%d")
            if today_dt == dt:
                end_hour = now.hour + 1
            else:
                end_hour = 24

            # 获取小时数据
            total_req = 0
            total_res = 0
            total_win = 0
            total_imp = total_dict['impression']
            for idx in reversed(xrange(0, end_hour)):
                str_hour = '%02d' % idx
                impression, click = self.get_hour_impression_click(
                    ad_network_id, day, str_hour)
                a_dict = dict()
                a_dict['dt'] = dt
                a_dict['hour'] = str_hour
                a_dict['ad_network_id'] = ad_network_id
                a_dict['position_id'] = '--'
                a_dict['pv'] = 0
                a_dict['impression'] = impression
                a_dict['click'] = click
                a_dict['ctr'] = '%.2f' % (
                    100.0 * click / impression) if impression != 0 else '0.00'
                imp = impression
                req = self.get_hour_req(ad_network_id, day, str_hour)
                res = self.get_hour_res(ad_network_id, day, str_hour)
                win = self.get_hour_win(ad_network_id, day, str_hour)
                a_dict['req'] = req
                a_dict['res'] = res
                a_dict['win'] = win
                a_dict['res_by_req'] = '%.2f' % (100.0 * res /
                                                 req) if req != 0 else '0.00'
                a_dict['imp_by_win'] = '%.2f' % (100.0 * imp /
                                                 win) if win != 0 else '0.00'
                a_dict['imp_by_res'] = '%.2f' % (100.0 * imp /
                                                 res) if res != 0 else '0.00'
                total_req += req
                total_res += res
                total_win += win
                a_dict['update_time'] = now.strftime('%Y-%m-%d %H:%M:%S')
                a_list.append(a_dict)
            total_dict['req'] = total_req
            total_dict['res'] = total_res
            total_dict['win'] = total_win
            total_dict['res_by_req'] = '%.2f' % (
                100.0 * total_res / total_req) if total_req != 0 else '0.00'
            total_dict['imp_by_win'] = '%.2f' % (
                100.0 * total_imp / total_win) if total_win != 0 else '0.00'
            total_dict['imp_by_res'] = '%.2f' % (
                100.0 * total_imp / total_res) if total_res != 0 else '0.00'

            # 返回结果
            a_dict = dict()
            a_dict['success'] = 'true'
            a_dict['content'] = a_list
            a_dict['item_count'] = len(a_list)
            return json.dumps(a_dict)
        except:
            Logger.error(traceback.format_exc())
            a_dict = dict()
            a_dict['success'] = 'false'
            a_dict['content'] = list()
            a_dict['item_count'] = 0
            return json.dumps(a_dict)
 def get(self):
     Logger.info(json.dumps(self.request.arguments, ensure_ascii=False), self.request.uri)
     self.render('reload.html')