def access_token_thread():
    log.info("开始启动缓存刷新线程...")
    # 30秒轮询一次
    SLEEP_TIME = 30
    while True:
        try:
            ttl = cache_client.ttl(WECHAT_ACCESS_TOKEN_KEY)
            log.info("当前key存活时间: key = {} ttl = {}".format(
                WECHAT_ACCESS_TOKEN_KEY, ttl))
            if ttl <= WX_CACHE_LAST_TIME:
                log.info("开始获取token...")
                update_access_token()
                log.info("获取token结束...")

            ttl = cache_client.ttl(WECHAT_JSAPI_TICKET_KEY)
            log.info("当前key存活时间: key = {} ttl = {}".format(
                WECHAT_JSAPI_TICKET_KEY, ttl))
            if ttl <= WX_CACHE_LAST_TIME:
                log.info("开始获取jsapi_ticket...")
                update_ticket()
                log.info("获取jsapi_ticket结束...")

        except Exception as e:
            log.error("缓存程序异常:")
            log.exception(e)
        time.sleep(SLEEP_TIME)
def update_access_token():
    url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
        settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET)
    try:
        resp = requests.get(url, verify=False, timeout=30)
        if resp.status_code != 200:
            log.error("访问状态码不正确: status_code = {}".format(resp.status_code))
            return False

        json_data = json.loads(resp.text)
        access_token = json_data.get('access_token')
        expires_in = json_data.get('expires_in')
        if not isinstance(access_token, basestring) or not isinstance(
                expires_in, int):
            log.error("解析出来的数据类型不正确: {}".format(resp.text))
            return False

        if expires_in <= 0:
            log.error("过期时间不正确: {}".format(expires_in))
            return False

        log.info("成功获取token: access_token = {} expires_in = {}".format(
            access_token, expires_in))

        # 设置redis
        cache_client.setex(WECHAT_ACCESS_TOKEN_KEY, expires_in, access_token)

        return True
    except Exception as e:
        log.error("访问token链接失败:")
        log.exception(e)

    return False
Beispiel #3
0
    def create(user_id, amount, transaction_id, pay_time):
        amount = int(amount)
        user_id = int(user_id)
        recharge = Recharge(user_id=user_id,
                            amount=amount,
                            transaction_id=transaction_id,
                            pay_time=pay_time)

        # 账户总额增加
        user = User.get(user_id)
        if user is None:
            log.warn("当前充值用户信息不存在: user_id = {}".format(user_id))
            return None, False

        try:
            user.balance_account += amount
            user.total_account += amount
            user.utime = datetime.now()
            db.session.add(user)
            db.session.add(recharge)
            db.session.commit()

            # 发送充值成功通知
            TemplateService.recharge_remind(user.openid, pay_time, amount)

        except IntegrityError:
            log.error("主键重复: user_id = {} amount = {}".format(user_id, amount))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: user_id = {} amount = {}".format(
                user_id, amount))
            log.exception(e)
            return None, False
        return recharge, True
Beispiel #4
0
    def create(username, password, name, address_id=Maintain.ALL_ADDRESS_ID):

        # 如果地址信息不正确,则选用所有地址可用
        if Address.get(address_id) is None:
            log.warn("当前传入地址ID没有找到相应地址信息,默认调整为全部地区: address_id = {}".format(
                address_id))

            address_id = Maintain.ALL_ADDRESS_ID

        maintain = Maintain(username=username,
                            name=name,
                            address_id=address_id)
        maintain.password = password

        try:
            db.session.add(maintain)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: username = {} name = {} address_id = {}".format(
                username, name, address_id))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: username = {} name = {} address_id = {}".format(
                username, name, address_id))
            log.exception(e)
            return None, False
        return maintain, True
Beispiel #5
0
    def find_list_by_keyword(page, size, keyword):
        query = Maintain.query

        # 先通过ID查找
        try:
            maintain_id = int(keyword)
            pagination = query.filter(Maintain.id == maintain_id).paginate(
                page=page, per_page=size, error_out=False)
            if pagination is not None and pagination.total > 0:
                return pagination.total, pagination.items
        except Exception as e:
            log.warn("通过ID查找失败: keyword = {}".format(keyword))
            log.exception(e)

        # 再通过用户名查找
        pagination = query.filter(Maintain.username == keyword).paginate(
            page=page, per_page=size, error_out=False)
        if pagination is not None and pagination.total > 0:
            return pagination.total, pagination.items

        # 再通过姓名查找
        pagination = query.filter(Maintain.name == keyword).paginate(
            page=page, per_page=size, error_out=False)
        if pagination is not None and pagination.total > 0:
            return pagination.total, pagination.items

        return 0, []
Beispiel #6
0
    def request_sms(self, mobile):
        if not settings.SMS_ENABLED:
            log.info("当前处于调试状态,没有打开短信验证码功能, 不发送短信验证码请求...")
            return True

        captcha = str(SmsSenderUtil.get_random())
        resp = self.tx_sms_sender.send_with_param("86", mobile,
                                                  self.sms_text_temp_id,
                                                  [captcha], "", "", "")

        try:
            result = json.loads(resp)
            if result.get('result') != 0:
                log.error("发送验证码失败: mobile = {} captcha = {}".format(
                    mobile, captcha))
                log.error("返回错误为: resp = {}".format(resp))
                return False

            # 存储验证码到redis中 只保留五分钟有效
            key = RedisClient.get_captcha_redis_key(mobile)
            self.__redis.setex(key, DEFAULT_EXPIRED_CAPTCHA, captcha)

            log.info("验证码发送成功: mobile = {} captcha = {}".format(
                mobile, captcha))
            return True
        except Exception as e:
            log.error("发送验证码失败: mobile = {} captcha = {}".format(
                mobile, captcha))
            log.exception(e)

        return False
Beispiel #7
0
def get_wechat_user_info(openid):
    # 默认设置是未关注状态
    subscribe, nick_name, head_img_url = 0, '', ''

    if openid is None:
        log.error("openid 为None,未知异常!!!")
        return subscribe, nick_name, head_img_url

    access_token = redis_cache_client.get(WECHAT_ACCESS_TOKEN_KEY)
    if access_token is None:
        log.error("access_token 为None,刷新token进程异常!!!")
        return subscribe, nick_name, head_img_url

    url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token={}&openid={}&lang=zh_CN'.format(
        access_token, openid)
    try:
        resp = requests.get(url, verify=False, timeout=30)
        if resp.status_code != 200:
            log.error("获取用户信息访问状态码不正确: status_code = {} url = {}".format(
                resp.status_code, url))
            return subscribe, nick_name, head_img_url

        log.info("当前获取的用户信息为: text = {}".format(resp.text))

        json_data = json.loads(resp.text)
        errcode = json_data.get('errcode')
        if errcode is not None:
            log.error("获取用户信息错误码不正常: {}".format(resp.text))
            return subscribe, nick_name, head_img_url

        subscribe = json_data.get('subscribe')
        if subscribe is None:
            log.error("获取用户信息关注状态不正常: {}".format(resp.text))
            return 0, nick_name, head_img_url

        # 如果用户关注了 才去获取昵称和头像信息
        if subscribe == 1:
            # 获得用户昵称 和头像信息
            nick_name = json_data.get('nickname', '')
            head_img_url = json_data.get('headimgurl', '')
            if isinstance(nick_name, basestring):
                nick_name = nick_name.strip()
            else:
                nick_name = ''
            if isinstance(head_img_url, basestring):
                head_img_url = head_img_url.strip()
            else:
                head_img_url = ''
            log.info(
                "当前用户关注了公众号, 能够获取昵称和头像: openid = {} nick_name = {} head_img_url = {}"
                .format(openid, nick_name, head_img_url))
        else:
            log.warn(
                "当前用户并没有关注公众号,无法获取用户信息: openid = {} subscribe = {}".format(
                    openid, subscribe))
    except Exception as e:
        log.error("访问微信用户链接失败: url = {}".format(url))
        log.exception(e)
    return subscribe, nick_name, head_img_url
Beispiel #8
0
 def delete_game_list(game):
     try:
         game_list = GameList.query.filter_by(game=game).first()
         if game_list is not None:
             db.session.delete(game_list)
             db.session.commit()
     except Exception as e:
         log.error("删除游戏失败:")
         log.exception(e)
Beispiel #9
0
 def get_current_time_charging(charging_str):
     try:
         charge_dict = json.loads(charging_str)
         charge_dict['cur_time'] = get_now_time()
         return charge_dict
     except Exception as e:
         log.error("json转换失败: charging = {}".format(charging_str))
         log.exception(e)
     return {'error': '计费json数据格式转换失败', 'status': -1}
Beispiel #10
0
 def delete_game(game):
     try:
         game_list = GameVersionManage.query.filter_by(game=game).all()
         [db.session.delete(game_item) for game_item in game_list]
         db.session.commit()
     except Exception as e:
         log.error("删除游戏失败:")
         log.exception(e)
         return False
     return True
Beispiel #11
0
    def get_game_list():

        result_list = []
        try:
            game_list = GameList.query.all()

            for game_item in game_list:
                result_list.append([game_item.game, game_item.version])
        except Exception as e:
            log.error("获取最新游戏列表失败:")
            log.exception(e)
        return result_list
Beispiel #12
0
    def delete(self):
        try:

            db.session.delete(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            log.error("未知删除错误: {}".format(
                json.dumps(self.to_dict(), ensure_ascii=False)))
            log.exception(e)
            return False
        return True
Beispiel #13
0
    def do_offline_order(record_key):
        url = 'http://localhost:8080/windows/logout'
        try:
            r = requests.post(url, json={'token': record_key}, timeout=10)
            log.info("当前处理状态status_code = {}".format(r.status_code))
            log.info("当前处理返回信息: {}".format(r.content))
            if r is not None and r.status_code == 200:
                return True
        except Exception as e:
            log.error("发送下机指令异常: ")
            log.exception(e)

        return False
Beispiel #14
0
 def delete(self):
     try:
         db.session.delete(self)
         self.address.device_num -= 1 if self.address.device_num >= 1 else 0
         db.session.add(self.address)
         db.session.commit()
     except Exception as e:
         db.session.rollback()
         log.error("未知删除错误: {}".format(
             json.dumps(self.to_dict(), ensure_ascii=False)))
         log.exception(e)
         return False
     return True
Beispiel #15
0
    def save(self):
        self.utime = datetime.now()

        try:
            db.session.add(self)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            log.error("未知存储错误: {}".format(
                json.dumps(self.to_dict(), ensure_ascii=False)))
            log.exception(e)
            return False
        return True
Beispiel #16
0
def get_user_by_id(user_id):
    # 先通过手机号码查找
    user = UserService.get_user_by_mobile(user_id)
    if user is not None:
        return success(user.to_dict())

    try:
        a_id = int(user_id)
        user = User.get(a_id)
        if user is not None:
            return success(user.to_dict())
    except Exception as e:
        log.error("用户ID信息无法转换为 int 类型: user_id = {}".format(user_id))
        log.exception(e)

    return success(None)
Beispiel #17
0
    def create(cls, name):
        role = cls(name=name)

        try:
            db.session.add(role)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: name = {}".format(name))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: name = {}".format(name))
            log.exception(e)
            return None, False

        return role, True
Beispiel #18
0
def get_dynamic_proxy(host):
    try:
        r = requests.get('http://{host}:{port}/proxy/{h}'.format(
            h=host, host=REMOTE_PROXY_CONF['host'], port=REMOTE_PROXY_CONF['port']),
            timeout=10)

        if r is None or r.status_code != 200 or 'failed' in r.text or 'False' in r.text:
            log.warn("动态代理服务异常, 重试...")
            return None

        proxies = 'http://{host}'.format(host=r.text)
        log.info('鲲鹏 ip = {}'.format(proxies))
        return proxies
    except Exception as e:
        log.error("动态代理访问异常:")
        log.exception(e)
    return None
Beispiel #19
0
    def create(cls, username, password):
        user = cls(username=username, password=password)

        try:
            db.session.add(user)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: username = {} password = {}".format(
                username, password))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: username = {} password = {}".format(
                username, password))
            log.exception(e)
            return None, False
        return user, True
Beispiel #20
0
    def online_recharge(user_id, total_fee):
        # 先获得用户缓存的信息
        user_key = RedisClient.get_user_key(user_id)

        # todo 这里需要加锁, 否则扣费下机时会有影响
        lock = DistributeLock(user_key, redis_cache_client)

        try:
            lock.acquire()
            record_key = redis_cache_client.get(user_key)
            if record_key is None:
                log.info("当前用户没有在线 record_key = None, 不需要同步在线数据: user_id = {}".
                         format(user_id))
                return

            charge_str = redis_cache_client.get(record_key)
            if charge_str is None:
                log.info(
                    "当前用户没有在线 charging = None, 不需要同步在线数据: user_id = {}".format(
                        user_id))
                return

            try:
                charge_dict = json.loads(charge_str)
                if charge_dict is None:
                    log.error("解析json数据失败: {}".format(charge_str))
                    return

                balance_account = charge_dict.get('balance_account')
                if not isinstance(balance_account, int):
                    log.error(
                        "balance_account 数据类型不正确: {}".format(balance_account))
                    return

                charge_dict['balance_account'] = balance_account + total_fee
                redis_cache_client.set(record_key, json.dumps(charge_dict))

                log.info(
                    "同步修改redis中用户余额信息成功! user_id = {} account = {}".format(
                        user_id, balance_account + total_fee))
            except Exception as e:
                log.error("解析json数据失败: {}".format(charge_str))
                log.exception(e)
        finally:
            lock.release()
Beispiel #21
0
    def create(cls, username, password, name, role_id):
        admin = cls(username=username, name=name, role_id=role_id)
        admin.password = password

        try:
            db.session.add(admin)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: username = {} name = {} role_id = {}".format(
                username, name, role_id))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: username = {} name = {} role_id = {}".format(
                username, name, role_id))
            log.exception(e)
            return None, False
        return admin, True
Beispiel #22
0
    def delete(device_id, name):
        game = DeviceGame.query.filter_by(device_id=device_id,
                                          name=name).first()
        if game is None:
            log.info("当前设备没有找到游戏: device_id = {} game = {}".format(
                device_id, name))
            return True

        try:
            db.session.delete(game)
            db.session.commit()
        except Exception as e:
            log.error("当前设备游戏删除失败: device_id = {} name = {}".format(
                device_id, name))
            log.exception(e)
            return False

        return True
Beispiel #23
0
 def create(device_id, name, newest_version):
     game = DeviceGame(device_id=device_id,
                       name=name,
                       newest_version=newest_version,
                       need_update=True)
     try:
         db.session.add(game)
         db.session.commit()
     except IntegrityError:
         log.error("主键重复: device_id = {} name = {}".format(device_id, name))
         db.session.rollback()
         return None, False
     except Exception as e:
         log.error("未知插入错误: device_id = {} name = {}".format(
             device_id, name))
         log.exception(e)
         return None, False
     return game, True
Beispiel #24
0
def get_address(location):
    if not isinstance(location, basestring) or location.strip() == '':
        log.warn("传入参数有误: location = {}".format(location))
        return fail(HTTP_OK, u"参数错误!")

    address_list = Address.find_address_by_location(location)
    if len(address_list) > 0:
        return success(address_list)

    try:
        a_id = int(location)
        address = Address.get(a_id)
        if address is not None:
            return success([address.to_dict()])
    except Exception as e:
        log.error("地址信息无法转换为 int 类型: location = {}".format(location))
        log.exception(e)

    return success([])
Beispiel #25
0
    def create(mobile, openid, nick_name="", head_img_url=""):

        user = User(mobile=mobile,
                    openid=openid,
                    nick_name=filter_emoji(nick_name),
                    head_img_url=head_img_url)

        try:
            db.session.add(user)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: mobile = {}".format(mobile))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: mobile = {}".format(mobile))
            log.exception(e)
            return None, False
        return user, True
Beispiel #26
0
 def create(cls, user_id, device_id, province, city, area, location):
     use_record = cls(user_id=user_id,
                      device_id=device_id,
                      province=province,
                      city=city,
                      area=area,
                      location=location)
     try:
         db.session.add(use_record)
         db.session.commit()
     except IntegrityError:
         log.error("未知错误: {} {}".format(user_id, device_id))
         db.session.rollback()
         return None, False
     except Exception as e:
         log.error("未知插入错误: {} {}".format(user_id, device_id))
         log.exception(e)
         return None, False
     return use_record, True
Beispiel #27
0
def get_role(role_info):
    if not isinstance(role_info, basestring) or role_info.strip() == '':
        log.warn("传入参数有误: location = {}".format(role_info))
        return fail(HTTP_OK, u"参数错误!")

    role = Role.get_by_name(role_info)
    if role is not None:
        return success([role.to_dict()])

    try:
        a_id = int(role_info)
        role = Role.get(a_id)
        if role is not None:
            return success([role.to_dict()])
    except Exception as e:
        log.error("角色名称信息无法转换为 int 类型: role_info = {}".format(role_info))
        log.exception(e)

    return success([])
Beispiel #28
0
    def create(game, version, md5):

        try:
            game_manage = GameVersionManage(game=game,
                                            version=version,
                                            md5=md5)
            db.session.add(game_manage)
            db.session.commit()
        except IntegrityError:
            log.error("主键重复: game = {} version = {} md5 = {}".format(
                game, version, md5))
            db.session.rollback()
            return None, False
        except Exception as e:
            log.error("未知插入错误: game = {} version = {} md5 = {}".format(
                game, version, md5))
            log.exception(e)
            return None, False
        return game_manage, True
Beispiel #29
0
 def create(cls, province, city, area, location, device_num=1):
     address = cls(province=province,
                   city=city,
                   area=area,
                   location=location,
                   device_num=device_num)
     try:
         db.session.add(address)
         db.session.commit()
     except IntegrityError:
         log.error("主键重复: province = {} city = {} area = {} location = {}".format(
             province, city, area, location))
         db.session.rollback()
         return None, False
     except Exception as e:
         log.error("未知插入错误: province = {} city = {} area = {} location = {}".format(
             province, city, area, location))
         log.exception(e)
         return None, False
     return address, True
Beispiel #30
0
    def update_game_all_by_http():
        url = 'http://localhost:8080/admin/backdoor/update/game'
        try_times = 3
        times = 0
        while times < try_times:
            times += 1
            try:
                r = requests.get(url, timeout=5 * 60)
                if r.status_code != 200:
                    continue
                json_data = json.loads(r.text)
                if not json_data.get('success'):
                    log.error("请求更新游戏失败: text = {}".format(r.text))
                    continue
                return True
            except Exception as e:
                log.error("请求更新游戏失败:")
                log.exception(e)

        return False