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
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
def get_task_items(cls, wlt_id): key = cls.WLT_ITEM_KEY % ({'wlt_id': wlt_id}) items = Redis.get(key) if items: items = cjson.loads(items) else: items = list(cls.collection.find({'wlt_id': ObjectId(wlt_id)})) Redis.setex(key, 86400, cjson.dumps(items, 2)) return [cls(i) for i in items]
def get_redpacket_items(cls, lrp_id): key = cls.LRP_ITEM_KEY % ({'lrp_id': lrp_id}) items = Redis.get(key) if items: items = cjson.loads(items) else: items = list(cls.collection.find({'lrp_id': ObjectId(lrp_id)})) Redis.setex(key, 86400, cjson.dumps(items, 2)) return [cls(i) for i in items]
def new_market_id(cls): qid = uuid.uuid1().get_hex() md5 = hashlib.md5(qid) secret = cls.SECRET_MAP.get('92332706', 'invalid_appid') md5.update(secret) mid = md5.hexdigest() key = cls.MARKET_KEY % {'mid': mid} Redis.setex(key, 60, 1) return qid
def get_by_type(cls, activity_type): key = cls.ACTIVITY_CONFIG_TYPE % ({'activity_type': str(activity_type)}) activity_config = Redis.get(key) if activity_config: activity_config = cjson.loads(activity_config) else: activity_config = cls.collection.find({'type': activity_type}) activity_config = [str(a['_id']) for a in activity_config] Redis.setex(key, 86400, cjson.dumps(activity_config, 2)) return activity_config
def get_all_stores(cls): stores = Redis.get(ALL_STORE_KEY) if stores: stores = cjson.loads(stores) stores = [dict_to_model(Store, s) for s in stores] else: stores = list(cls.select()) _stores = [model_to_dict(s) for s in stores] Redis.setex(ALL_STORE_KEY, 86400, cjson.dumps(_stores, 2)) return stores
def get_all_products(cls): products = Redis.get(PRODUCT_KEY) if products: products = cjson.loads(products) products = [dict_to_model(Product, p) for p in products] else: products = list(cls.select()) _products = [model_to_dict(p) for p in products] Redis.setex(PRODUCT_KEY, 86400, cjson.dumps(_products, 2)) return products
def get_user_products(cls, user_id): key = USER_PRODUCT_KEY % (user_id) uproducts = Redis.get(key) if uproducts: uproducts = cjson.loads(uproducts) uproducts = [dict_to_model(UserProduct, up) for up in uproducts] return uproducts uproducts = list(cls.select().where(UserProduct.user_id == user_id)) _uproducts = [model_to_dict(up) for up in uproducts] Redis.setex(key, 86400, cjson.dumps(_uproducts, 2)) return uproducts
def get_store_items(cls, store_id): key = STORE_ITEM_KEY % ({'store_id': store_id}) items = Redis.get(key) if items: items = cjson.loads(items) items = [dict_to_model(StoreItem, i) for i in items] else: items = list(cls.select().where(cls.store_id == int(store_id))) _items = [model_to_dict(i) for i in items] Redis.setex(key, 86400, cjson.dumps(_items, 2)) return sorted(items, key=lambda x: x.order)
def get_user_total_gold(cls, uid, begin_at, end_at): key = USER_TOTAL_GOLD % ({'uid': uid}) total_gold = Redis.get(key) if not total_gold: total_gold = pw.fn.Sum(UserGiftLog.gold_price) total_gold = cls.select(total_gold.alias('gold')).where( UserGiftLog.user_id == uid, UserGiftLog.gift_from == const.FROM_LIVE, UserGiftLog.create_at > datetime.fromtimestamp(int(begin_at)), UserGiftLog.create_at < datetime.fromtimestamp(int(end_at))) total_gold = total_gold.get() total_gold = 0 if not total_gold.gold else total_gold.gold Redis.setex(key, 86400, total_gold) return int(total_gold)
def fetch(cls, key, default, func=None): try: cache_key = cls.CONFIG_PREFIX % (key) value = Redis.get(cache_key) if value is None: obj = cls.collection.find_one({'key': key}) value = obj['value'] if obj else None if value: Redis.setex(cache_key, 7 * 24 * 3600, value) if value is None: return default return apply(func, [value]) if callable(func) else value except: return default
def _load_os_module_ids(cls, os, key): modules = list( cls.collection.find({ 'os': os }).sort("order", pymongo.ASCENDING)) _ids = list() for m in modules: _ids.append(str(m['_id'])) return Redis.setex(key, 86400, cjson.dumps(_ids, 2))
def send_code(cls, phone): ts = str(int(time.time())) sig_str = '%s%s%s' % (cls.client_id, cls.client_key, ts) sign = hashlib.md5(sig_str).hexdigest() code = random.randint(1000, 9999) data = dict(client_id=cls.client_id, timestamp=ts, sign=sign, code=code, company='咪咕游玩', phone=phone) resp = requests.post(cls.send_url, data=data, verify=False) if resp.status_code != requests.codes.ok: return False data = resp.json() ret = int(data['error']) == 0 if ret: key = 'sms:code:%s' % (phone) Redis.setex(key, 600, code) return ret
data = dict(phones=phones, content=con) gm_client = gearman.GearmanClient(app.config['GEARMAN_SERVERS']) gm_client.submit_job(job, json.dumps(data), background=True, wait_until_complete=False, max_retries=5) except gearman.errors.GearmanError: pass except Exception, e: print_log('send_sms_err', str(e)) else: UserCertify.send_code_other(phone, code) Redis.setex('sms:{user_id}'.format(user_id=user_id), 60 * 5, code) return {} @app.route('/users/binding', methods=('POST', 'GET')) @util.jsonapi(login_required=True) def binding(): """用户绑定 (GET|POST&LOGIN) :uri: /users/binding :param platform: 平台标识 (phone, weixin, qq) :param openid: 平台id/手机号 :param token: 用户平台token/短信验证码 :returns: {} """
def _set_upload_file_meta(file_id, meta): data = json.dumps(meta) key = "upload:%s" % file_id ok = Redis.setex(key, 3600 * 24, data) if not ok: raise
def _load_activity_status(cls, aid, key): status = cls.collection.find_one({'_id': ObjectId(aid)}, {'status': 1}) return Redis.setex(key, 86400, status['status'])
def _load_ids_by_os(cls, os, key): modules = list(cls.collection.find({'os': os})) _ids = list() for m in modules: _ids.append(str(m['_id'])) return Redis.setex(key, 86400, cjson.dumps(_ids, 2))
def _load_game_activity_ids(cls, aid, key): games = list(cls.collection.find({'activity': ObjectId(aid)})) game_activity_ids = list() for g in games: game_activity_ids.append(str(g['game'])) return Redis.setex(key, 86400, cjson.dumps(game_activity_ids, 2))