Пример #1
0
 def get_limit_config(cls, report_type):
     key = cls.REPORT_CONFIG % {'rtype': report_type}
     if not Redis.exists(key):
         cfg = cls.collection.find_one({'report_type': report_type})
         _id = cfg and str(cfg['_id'])
         Redis.set(key, _id, 86400)
     return Redis.get(key)
Пример #2
0
    def delete_model(self):
        ret = super(Province, self).delete_model()
        if ret:
            key = self.ALL_PROVINCE_IDS
            Redis.delete(key)

        return ret
Пример #3
0
    def update_model(self, data={}):
        ret = super(Channels, self).update_model(data)
        if ret:
            key = self.ALL_CHANNELS_IDS
            Redis.delete(key)

        return ret
Пример #4
0
    def create_model(self):
        _id = super(Province, self).create_model()
        if _id:
            key = self.ALL_PROVINCE_IDS
            Redis.delete(key)

        return _id
Пример #5
0
    def clear_gifts_num(cls, user, is_money):
        pdict = {}
        for p in Product.get_all_gifts():
            pdict[p.product_id] = p.format()

        uproducts = cls.get_user_products(str(user._id))

        if is_money:
            for up in uproducts:
                if up.product_id not in pdict and not up.is_money:
                    continue
                cls.update(num=0).where(
                    UserProduct.user_id == str(user._id),
                    UserProduct.is_money == is_money,
                    UserProduct.product_id == int(up.product_id)).execute()

            key = USER_PRODUCT_KEY % (str(user._id))
            Redis.delete(key)
            return

        else:
            for up in uproducts:
                if up.product_id not in pdict and up.is_money:
                    continue
                cls.update(num=0).where(
                    UserProduct.user_id == str(user._id),
                    UserProduct.is_money == is_money,
                    UserProduct.product_id == int(up.product_id)).execute()

            key = USER_PRODUCT_KEY % (str(user._id))
            Redis.delete(key)
            return
Пример #6
0
    def update_model(self, data={}):
        ret = super(Province, self).update_model(data)
        if ret:
            key = self.ALL_PROVINCE_IDS
            Redis.delete(key)

        return ret
Пример #7
0
    def refresh_daily_tasks(cls, user_id):
        _tasks = []
        for task in Task.get_daily_tasks():
            tmp = dict(user_id=user_id,
                       task_id=task.task_id,
                       task_type=task.task_type,
                       action=task.action)
            # 每日签到任务自动完成
            if task.action == DAILY_SIGNIN:
                tmp['task_status'] = FINISHED
                tmp['finish_num'] = 1
            _tasks.append(tmp)

        with MYDB.atomic():
            # 删除旧的每日任务
            cls.delete().where(UserTask.user_id == user_id,
                               UserTask.task_type == 2).execute()
            # 增加新的每日任务
            if _tasks:
                UserTask.insert_many(_tasks).execute()
            # 修改任务刷新时间
            UserCredit.update(task_at=datetime.datetime.now()).where(
                UserCredit.user_id == user_id).execute()

        key = USER_TASK_KEY % (user_id)
        Redis.delete(key)
Пример #8
0
    def setUpClass(cls):
        Redis.flushall()
        if app.config.get('MONGO_DBNAME') in client.database_names():
            client.drop_database(app.config.get('MONGO_DBNAME'))

        print 'Create database(%s) for unittest ... ok' % (
            app.config.get('MONGO_DBNAME'))
        kw_path = app.config.get('BASE_DIR') or os.path.abspath(
            os.path.join(app.root_path, '../'))
        data_path = os.path.join(kw_path, 'wanx/tests/fixtures/')
        for fname in os.listdir(data_path):
            if not fname.startswith('.') and fname.endswith('.json'):
                collection = fname.split('.')[0]
                with open(os.path.join(data_path, fname), 'r') as f:
                    data = f.read()
                    if data:
                        data = bjson.loads(data.strip('\n'))
                        DB.create_collection(collection)
                        DB.get_collection(collection).insert_many(data)

        print 'Create mysql database(%s) for unittest ... ok' % (MYDB.database)
        sql = 'mysql -e "create database if not exists %s  DEFAULT CHARACTER SET utf8 \
               DEFAULT COLLATE utf8_general_ci;"' % (MYDB.database)
        os.popen(sql)
        for fname in os.listdir(data_path):
            if not fname.startswith('.') and fname.endswith('.sql'):
                sql_path = os.path.join(data_path, fname)
                sql = 'mysql %s < %s' % (MYDB.database, sql_path)
                os.popen(sql)
Пример #9
0
    def create_model(self):
        _id = super(Channels, self).create_model()
        if _id:
            key = self.ALL_CHANNELS_IDS
            Redis.delete(key)

        return _id
Пример #10
0
    def create_model(self):
        _id = super(VersionConfig, self).create_model()
        if _id:
            key = self.ALL_VERSION_IDS
            Redis.delete(key)

        return _id
Пример #11
0
    def get_all_lives(cls):
        """所有直播间列表
        """
        # 后台配置是否开启直播服务, 默认开启
        api_url = Config.fetch('live_api_url', None, str)
        if not api_url:
            return []

        api_url = urljoin(api_url, '/events')
        lives = Redis.get(cls.ALL_LIVES)
        if not lives:
            try:
                resp = requests.get(api_url, timeout=2)
            except requests.exceptions.Timeout:
                print_log('xlive', '[get_all_lives]: connection timeout')
                return []
            except:
                print_log('xlive', '[get_all_lives]: connection error')
                return []

            if resp.status_code != requests.codes.ok:
                print_log('xlive', '[get_all_lives]: status_code not ok')
                return []

            lives = resp.content
            lives = json.loads(lives)['data']['live']
            Redis.setex(cls.ALL_LIVES, 5, json.dumps(lives))
        else:
            lives = json.loads(lives)

        # 按照人气排序
        lives.sort(key=lambda x: x['count'], reverse=True)
        return lives
Пример #12
0
    def delete_model(self):
        ret = super(Channels, self).delete_model()
        if ret:
            key = self.ALL_CHANNELS_IDS
            Redis.delete(key)

        return ret
Пример #13
0
    def send_code(cls, phone):
        ts = datetime.now().strftime('%Y%m%d%H%M%S')
        sig_str = '%s%s%s' % (cls.sid, cls.token, ts)
        sign = hashlib.md5(sig_str).hexdigest().upper()
        code = random.randint(1000, 9999)
        _send_uri = cls.send_uri % (cls.sid, sign)
        url = '%s%s' % (cls.send_url, _send_uri)
        data = dict(
            to=phone,
            appId=cls.appid,
            templateId='1',
            datas=[code, 10],
        )
        data = json.dumps(data)
        headers = {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=utf-8',
            'Content-Length': len(data),
            'Authorization': base64.b64encode('%s:%s' % (cls.sid, ts))
        }
        resp = requests.post(url, data=data, headers=headers)
        if resp.status_code != requests.codes.ok:
            return False
        data = resp.json()
        ret = data['statusCode'] == '000000'
        if ret:
            key = 'sms:code:%s' % (phone)
            Redis.setex(key, 600, code)

        return ret
Пример #14
0
def do_task(worker, job):
    from wanx.base.log import print_log
    from wanx.base.xredis import Redis
    from wanx.models.video import UserFaverVideo
    from wanx.models.user import User
    data = job.data
    # 记录日志
    print_log('modify_video', data)

    data = json.loads(data)
    vid = data['vid']
    # action = data['action']
    # delta_count = 0
    # if action == 'offline':
    #     delta_count = -1
    # elif action == 'online':
    #     delta_count = 1
    # 更新收藏了此视频的用户计数
    uids = UserFaverVideo.favor_video_uids(vid)
    for uid in uids:
        user = User.get_one(uid, check_online=False)
        if user:
            key = UserFaverVideo.FAVER_VIDEO_IDS % ({'uid': uid})
            Redis.delete(key)
            count = UserFaverVideo.faver_video_count(uid)
            user.update_model({'$set': {'favor_count': count}})
    return ''
Пример #15
0
    def delete_model(self):
        ret = super(VersionConfig, self).delete_model()
        if ret:
            key = self.ALL_VERSION_IDS
            Redis.delete(key)

        return ret
Пример #16
0
    def update_model(self, data={}):
        ret = super(VersionConfig, self).update_model(data)
        if ret:
            key = self.ALL_VERSION_IDS
            Redis.delete(key)

        return ret
Пример #17
0
    def verify_interval(cls, key, interval, valid_count):
        count = Redis.incr(key)
        Redis.expire(key, interval)
        if count > valid_count:
            return False

        return True
Пример #18
0
 def tearDownClass(cls):
     Redis.flushall()
     print 'Drop database(%s) for unittest ... ok' % (
         app.config.get('MONGO_DBNAME'))
     client.drop_database(app.config.get('MONGO_DBNAME'))
     print 'Drop mysql database(%s) for unittest ... ok' % (MYDB.database)
     sql = 'mysql -e "drop database if exists %s;"' % (MYDB.database)
     os.popen(sql)
Пример #19
0
 def create_model(self):
     _id = super(Live_Activity, self).create_model()
     if _id:
         key = self.LIVE_HOT_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
         key = self.LIVE_NEW_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
     return _id
Пример #20
0
 def delete_model(self):
     ret = self.collection.delete_one({"_id": ObjectId(self._id)})
     key = self.OBJECT_KEY % ({
         'name': self.__class__.__name__.lower(),
         'oid': str(self._id)
     })
     Redis.delete(key)
     return ret.deleted_count
Пример #21
0
 def delete_model(self):
     ret = super(Live_Activity, self).delete_model()
     if ret:
         key = self.LIVE_HOT_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
         key = self.LIVE_NEW_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
     return ret
Пример #22
0
 def get_user_live_history(cls, uid):
     today = datetime.date.today().strftime('%y%m%d')
     key = cls.USER_LIVE_DAILY_HISTORY % {'today': today, 'uid': uid}
     if not Redis.exists(key):
         cls._load_user_live_history(uid, key)
     logs = Redis.get(key)
     history = cjson.loads(logs) if logs else []
     return history
Пример #23
0
 def update_model(self, data={}):
     obj = super(Live_Activity, self).update_model(data)
     if obj:
         key = self.LIVE_HOT_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
         key = self.LIVE_NEW_USER % ({'aid': str(self.activity_id)})
         Redis.delete(key)
     return obj
Пример #24
0
 def update_model(self, data={}):
     ret = super(Config, self).update_model(data)
     if ret:
         cache_key = self.CONFIG_PREFIX % (self.key)
         Redis.delete(cache_key)
         cache_key = self.CONFIG_PREFIX % (ret.key)
         Redis.delete(cache_key)
     return ret
Пример #25
0
 def create_model(self):
     aid = 'all'
     phone = self.phone
     device = self.device
     for k, xid in {'phone': phone, 'device': device}.iteritems():
         key = self.USER_ACTIVITY % ({'aid': aid, 'xid': xid})
         Redis.delete(key)
     return super(UserShareActivityLog, self).create_model()
Пример #26
0
 def all_banners_by_version(cls):
     key = cls.ALL_BANNERS_BY_VERSION
     if not Redis.exists(key):
         cls._load_all_banner_version()
     try:
         bids = Redis.lrange(key, 0, -1)
     except exceptions.ResponseError:
         bids = []
     return list(bids)
Пример #27
0
 def all_ad_ids(cls):
     key = cls.ALL_AD_IDS
     if not Redis.exists(key):
         cls._load_all_ad_ids()
     try:
         ad_ids = Redis.lrange(key, 0, -1)
     except exceptions.ResponseError:
         ad_ids = []
     return list(ad_ids)
Пример #28
0
 def all_module_ids(cls):
     key = cls.ALL_MODULE_IDS
     if not Redis.exists(key):
         cls._load_all_module_ids()
     try:
         mids = Redis.lrange(key, 0, -1)
     except exceptions.ResponseError:
         mids = []
     return list(mids)
Пример #29
0
 def all_banner_ids(cls):
     key = cls.ALL_BANNER_IDS
     if not Redis.exists(key):
         cls._load_all_banner_ids()
     try:
         bids = Redis.lrange(key, 0, -1)
     except exceptions.ResponseError:
         bids = []
     return list(bids)
Пример #30
0
 def all_module_game_ids(cls, module_id):
     key = cls.ALL_MODULE_GAME_IDS.format(module_id=module_id)
     if not Redis.exists(key):
         cls._load_all_module_game_ids(module_id)
     try:
         mids = Redis.lrange(key, 0, -1)
     except exceptions.ResponseError:
         mids = []
     return list(mids)