async def post(self): encryptedData = self.get_argument("encryptedData", "") iv = self.get_argument("iv", "") uuid = self.current_user.uuid user_info_session_key = "sx_info:" + uuid union_id = to_str( self.redis_spare.hget(user_info_session_key, "union_id")) if not union_id: if encryptedData and iv: open_id = to_str( self.redis_spare.hget(user_info_session_key, "openid")) session_dict = self.get_session(open_id) session_key = session_dict[0].get("session_key", "") print("session_key", session_key) print("encryptedData", encryptedData) print("iv", iv) pc = WXBizDataCrypt(APPID, session_key) WX_data = pc.decrypt(encryptedData, iv) union_id = WX_data.get("unionId", "") self.redis_spare.hset(user_info_session_key, "uniond_id", union_id) else: return self.write_json(status=-1, msg="上报信息有误,请核对") data = {"unionId": union_id} self.write_json(data)
def load_body(self, body=None): """ pass """ # 如果没有文件,则根据body写入文件 if body is None: raise Exception("No body") file_name = self.tmp_filename() try: with open(file_name, 'w+b') as codefp: codefp.write(body) work_book = xlrd.open_workbook(file_name) sheet = work_book.sheet_by_index(0) title = [] for c in xrange(sheet.ncols): title.append(sheet.cell(0, c).value) data = [] for r in xrange(1, sheet.nrows): unit = {} for c in xrange(sheet.ncols): cell = sheet.cell(r, c) if cell.ctype == xlrd.XL_CELL_DATE: unit[title[c]] = to_str( self._get_date(cell.value, dateformat)) else: unit[title[c]] = to_str(cell.value) data.append(unit) return data finally: os.remove(file_name)
def load(self, head, file_name=None, body=None): ''' 加载excel @head 标题头 @file_name 文件名 @body 文件数据 ''' if file_name is None and body is None: raise Exception("No file name or body") # 如果没有文件,则根据body写入文件 if file_name is None: file_name = self.tmp_filename() with open(file_name, 'w+b') as codefp: codefp.write(body) title, data = [], [] work_book = xlrd.open_workbook(file_name) sheet = work_book.sheet_by_index(0) for c in xrange(sheet.ncols): title.append(sheet.cell(0, c).value) for r in xrange(1, sheet.nrows): unit = {} for c in xrange(sheet.ncols): for k, v in head: if title[c].encode('utf-8') == v: cell = sheet.cell(r, c) # 如果是日期类型 if cell.ctype == xlrd.XL_CELL_DATE: unit[k] = to_str(self._get_date(cell.value)) else: unit[k] = to_str(cell.value) data.append(unit) os.remove(file_name) return data
def get_members(self, user, iid, output_name, format=None): """ Output memberships and per-source information. """ self.logger.debug('Get members for %s of user %s', iid, user) sqllist.GLOBALS['i'] = self.get_global_iid(user, iid) sql = sqllist.get_sql('members', to_str(self.catalog.error_columns, ','), to_str(self.catalog.magnitude_columns, ',')) return self.output_sql(sql, output_name, format)
def get_members_iid(self, iid, output_name, xformat=None): """ Get all possible cluster members. """ self.logger.debug('Get members for %s', iid) sqllist.GLOBALS['i'] = iid if self.catalog.CATALOG == 'xmatch': sqlname = 'xmatch-members' else: sqlname = 'members' sql = sqllist.get_sql(sqlname, to_str(self.catalog.magnitude_columns, ','), to_str(self.catalog.error_columns, ',')) return self.output_sql(sql, output_name, xformat)
async def get(self): uuid = self.get_argument("uuid", "") if not uuid: return self.write_json(status=-1, msg="请稍后重试") # 1. 删缓存 user_info_session_key = "sx_info" + uuid open_id = to_str( self.redis_spare.hget(user_info_session_key, b"open_id")) name = to_str(self.redis_spare.hget(user_info_session_key, b"name")) self.redis_spare.delete(user_info_session_key) # 2.更新数据库 cur = self.cur sql = "update user_level set `level`= %s, next_level=%s, current_score=%s where uuid =%s" cur.execute(sql, [1, 2, 0, uuid]) cur.connection.commit() sql_query = "select `level`, target_score, color_num from game_config where `level`=%s" cur.execute(sql_query, [1]) result = cur.fetchone() if not result: return self.write_json(status=-2, msg="请重新刷新配置") next_target_score = result.get("target_score", 0) next_color_num = result.get("color_num", 0) # set缓存 self.save_user_info_session(user_uuid=uuid, openid=open_id, level=1, current_score=0, target_score=next_target_score, color_num=next_color_num) # 存入排行榜 self.redis_spare.zadd("world_rank", {name: 0}) color_array = random_color_array(1, int(next_color_num)) data = { "level": 1, "target_score": next_target_score, # "next_color_num": next_color_num, "current_score": 0, "color_array": color_array } self.write_json(data)
async def get(self): data = [] # result = [] result = self.redis_spare.zrevrange("world_rank", 0, 100, withscores=True) if result: for key, value in result: name = to_str(key) score = int(value) rank = result.index((key, value)) + 1 avatar = to_str(self.redis_spare.hget("user_avatar", name)) data.append({ "rank": rank, "name": name, "score": score, "avatar": avatar }) else: # 缓存失效的情况 cur = self.cur # 前100名排名 sql = "select a.*, (@rowNum:=@rowNum+1) as rank from (SELECT @rownum := 0) as r, " \ "(select avatar, name, current_score from user_level as ul left join user as u on u.uuid=ul.uuid " \ "order by ul.current_score DESC ) as a " cur.execute(sql) result = cur.fetchall() if not result: return self.write_json(status=-1, msg="请稍后重试") for rk in result: name = rk.get("name", "") avatar = rk.get("avatar", "") score = int(rk.get("current_score", 0)) rank = int(rk.get("rank", 0)) data.append({ "rank": rank, "name": name, "score": score, "avatar": avatar }) # 排好的名次push入redis缓存 self.redis_spare.zadd("world_rank", {name: score}) self.redis_spare.hset("user_avatar", name, avatar) self.write_json(data)
def get_current_uuid(self, uuid): # print("session", self.session) user_info_session_key = "sx_info:" + uuid open_id = to_str(self.redis_spare.hget(user_info_session_key, "openid")) if open_id is None: return False user_session_key = 'sx:' + open_id session_key = self.redis_spare.hget(user_session_key, "session_key") return session_key
def get(self, request_handler=None): if request_handler is None: session_id = None hmac_key = None else: session_id = to_str(request_handler.get_secure_cookie("session_id")) hmac_key = to_str(request_handler.get_secure_cookie("verification")) if session_id is None: session_exists = False session_id = self._generate_id() hmac_key = self._generate_hmac(session_id) else: session_exists = True check_hmac = self._generate_hmac(session_id) if hmac_key != check_hmac: raise InvalidSessionException() session = SessionData(session_id, hmac_key) if session_exists: session_data = self._fetch(session_id) for key, data in session_data.items(): session[key] = data return session
def load_file(self, file_name, dateformat="%Y-%m-%d"): ''' assume the first line is title ''' work_book = xlrd.open_workbook(file_name) sheet = work_book.sheet_by_index(0) title = [] for c in xrange(sheet.ncols): title.append(sheet.cell(0, c).value) data = [] for r in xrange(1, sheet.nrows): unit = {} for c in xrange(sheet.ncols): cell = sheet.cell(r, c) if cell.ctype == xlrd.XL_CELL_DATE: unit[title[c]] = to_str( self._get_date(cell.value, dateformat)) else: unit[title[c]] = to_str(cell.value) data.append(unit) return data
async def post(self): req_data = json.loads(to_str(self.request.body)) js_code = req_data.get("code", "") sceneId = req_data.get("sceneId", "") query = req_data.get("query", "") encryptedData = req_data.get("encryptedData", "") iv = req_data.get("iv", "") if type(sceneId) not in [str, int]: env_code = 0 else: env_code = int(sceneId) from_id = "" if query: from_keys = list(query.keys()) if from_keys: from_id = from_keys[0] from_id = encode_tuuid(from_id) # js_code = self.get_argument("code", "") # env_code = int(self.get_argument("sceneId", "") or 0) # from_id = str(self.get_argument("from_id", "") or 0) # 三个参数缺一不可 if not js_code: return self.write_json(status=-1, msg="上报code有误,请核对") # 1.获取用户信息 # print("js_code", js_code) user_info = get_user_info(js_code) # user_info = {"openid": "sss", "session_key": "aaa"} # print("user_info", user_info) open_id = user_info.get("openid", "") if not open_id: return self.write_json(status=-2, msg="上报code有误,请核对") # 2.获取session_key session_key = user_info.get("session_key", "") # user_session_key = USER_SESSION_KEY + open_id user_session = self.get_session(open_id) if encryptedData and iv: pc = WXBizDataCrypt(APPID, session_key) WX_data = pc.decrypt(encryptedData, iv) unionId = WX_data.get("unionId", "") else: unionId = "" today = time.strftime("%Y-%m-%d", time.localtime()) day_time = int(time.mktime(datetime.date.today().timetuple())) # 3. 登陆时未找到缓存 if user_session == [{}] or not user_session: user_uuid = str(uuid.uuid4()) # 3.1 用户是否注册过 try: # 3.1.1 注册过,缓存过期 existed_user = await self.application.objects.get( User, open_id=open_id) user_uuid = existed_user.uuid login_time = existed_user.login_time.strftime('%Y-%m-%d') name = existed_user.name existed_user_level = await self.application.objects.get( User_Level, uuid=user_uuid) level = existed_user_level.level current_score = existed_user_level.current_score restart = existed_user_level.restart history_score = existed_user_level.history_score game_config = await self.application.objects.get(Game_Config, level=level) target_score = game_config.target_score color_num = game_config.color_num direct = game_config.direct user_coins = await self.application.objects.get(User_Coins, uuid=user_uuid) coins = user_coins.coins verified = 1 if name else 0 tools_result = await self.application.objects.execute( User_Tools.select( User_Tools.tool_id, User_Tools.count).where(User_Tools.uuid == user_uuid)) tools = {} for res in tools_result: tool_id = res.tool_id count = res.count tools[tool_id] = count # 最后登录 user_sign = await self.application.objects.get(User_Sign, uuid=user_uuid) lastest_sign_date = user_sign.lastest_sign_date.strftime( '%Y-%m-%d') continuous_sign_days = user_sign.continuous_sign_days timeArray = time.strptime(lastest_sign_date, "%Y-%m-%d") lastest_sign_timestamp = int(time.mktime(timeArray)) extra = int(user_sign.extra) if lastest_sign_timestamp < day_time - 3600 * 24: continuous_sign_days = 0 if lastest_sign_timestamp == day_time - 3600 * 24 and int( continuous_sign_days) == 7: continuous_sign_days = 0 today_sign_status = 0 if lastest_sign_date == today: # signboard = 0 today_sign_status = 1 if lastest_sign_date != today and extra: today_sign_status = 0 user_sign.extra = 0 await self.application.objects.update(user_sign) extra = 0 signboard = 0 try: user_loto = await self.application.objects.get( User_Loto, uuid=user_uuid) loto_num = user_loto.number except User_Loto.DoesNotExist as e: user_loto = await self.application.objects.create( User_Loto, uuid=user_uuid, number=3) loto_num = 3 # loto_num = user_loto.number if lastest_sign_date < today: signboard = 1 if login_time < today: existed_user.login_time = today await self.application.objects.update(existed_user) # loto user_loto.number = loto_num = 3 await self.application.objects.update(user_loto) for i in range(1, 6): user_mall = await self.application.objects.get( User_Mall, uuid=user_uuid, action_id=i) # if i == 1: user_mall.daily_status = 0 if user_mall.status == 2: user_mall.status = 0 await self.application.objects.update(user_mall) lotoboard = 1 if loto_num else 0 if int(env_code) == 1089: # 收藏渠道4 try: user_mall = await self.application.objects.get( User_Mall, uuid=user_uuid, action_id=4) if not user_mall.status: user_mall.status = 1 await self.application.objects.update(user_mall) except User_Mall.DoesNotExist as e: pass elif int(env_code) == 1131: # 浮窗渠道5 try: user_mall = await self.application.objects.get( User_Mall, uuid=user_uuid, action_id=5) if not user_mall.status: user_mall.status = 1 await self.application.objects.update(user_mall) except User_Mall.DoesNotExist as e: pass new_user = 0 # 闯关模式 try: user_challenge = await self.application.objects.get( User_Challenge, uuid=user_uuid) challenge_info = user_challenge.challenge_info challenge_info_json = json.dumps(to_str(challenge_info)) except User_Challenge.DoesNotExist as e: challenge_info = {"1": 0} challenge_info_json = json.dumps(challenge_info) await self.application.objects.create( User_Challenge, uuid=user_uuid, challenge_info=challenge_info_json) # 3.1.2 未注册过 # TODO 新用户初始化 except User.DoesNotExist as e: login_time = today await self.application.objects.create(User, open_id=open_id, uuid=user_uuid, login_time=login_time) user_level = await self.application.objects.create( User_Level, uuid=user_uuid, level=1, next_level=2, current_score=0, history_score=0) current_score = 0 history_score = 0 game_config = await self.application.objects.get(Game_Config, level=1) level = game_config.level target_score = game_config.target_score color_num = game_config.color_num direct = game_config.direct tools = {} tool_source = [] tool_config = Config.tool_config.keys() for key in tool_config: tools[key] = 0 tool_source.append({ "uuid": user_uuid, "tool_id": key, "count": 0 }) await self.application.objects.execute( User_Tools.insert_many(tool_source)) coins = 0 restart = 0 # 生成签到表 await self.application.objects.create( User_Sign, uuid=user_uuid, lastest_sign_date="1900-01-01", continuous_sign_days=0, extra=0) # 生成mall表 data_source = [ { "uuid": user_uuid, "action_id": 1, "action_name": "视频广告", "status": 0, "daily_status": 0 }, { "uuid": user_uuid, "action_id": 2, "action_name": "邀请好友", "status": 0, "daily_status": 0 }, { "uuid": user_uuid, "action_id": 3, "action_name": "客服会话", "status": 0, "daily_status": 0 }, { "uuid": user_uuid, "action_id": 4, "action_name": "收藏", "status": 0, "daily_status": 0 }, { "uuid": user_uuid, "action_id": 5, "action_name": "浮窗", "status": 0, "daily_status": 0 }, ] # field = (User_Mall.uuid, User_Mall.action_id, User_Mall.action_name, User_Mall.status) await self.application.objects.execute( User_Mall.insert_many(data_source)) await self.application.objects.create(User_Coins, uuid=user_uuid, coins=0) await self.application.objects.create(User_Loto, uuid=user_uuid) loto_num = 3 lotoboard = 1 signboard = 1 continuous_sign_days = 0 today_sign_status = 0 lastest_sign_date = "1900-01-01" extra = 0 verified = 0 new_user = 1 # # 是否邀请而来 if from_id: try: user_mall = await self.application.objects.get( User_Mall, uuid=from_id, action_id=2) if user_mall.status == 0: user_mall.status = 1 await self.application.objects.update(user_mall) except User_Mall.DoesNotExist as e: pass # 初始化闯关模式 challenge_info = {"1": 0} challenge_info_json = json.dumps(challenge_info) await self.application.objects.create( User_Challenge, uuid=user_uuid, challenge_info=challenge_info_json) # 3.1.3 保存缓存 self.save_user_session(user_uuid, open_id, session_key) self.save_user_info_session(user_uuid=user_uuid, openid=open_id, level=level, current_score=current_score, target_score=target_score, color_num=color_num, verified=verified, tools=str(tools), coins=coins, direct=direct, history_score=history_score) user_info_session_key = "sx_info:" + user_uuid self.redis_spare.hset(user_info_session_key, "lastest_sign_date", lastest_sign_date) self.redis_spare.hset(user_info_session_key, "continuous_sign_days", continuous_sign_days) self.redis_spare.hset(user_info_session_key, "login_time", login_time) self.redis_spare.hset(user_info_session_key, "restart", restart) self.redis_spare.hset(user_info_session_key, "loto_num", loto_num) self.redis_spare.hset(user_info_session_key, "extra", extra) self.redis_spare.hset(user_info_session_key, "challenge_info", challenge_info_json) else: user_session = user_session[0] user_uuid = user_session.get("uuid", "") user_info_session = self.get_user_info_session(user_uuid) level = user_info_session.get("level", 1) current_score = user_info_session.get("current_score", 0) target_score = user_info_session.get("target_score", TARGET_SCORE_CONST) color_num = user_info_session.get("color_num", COLOR_NUM_CONST) name = user_info_session.get("name", "") continuous_sign_days = user_info_session.get( "continuous_sign_days", 0) lastest_sign_date = user_info_session.get("lastest_sign_date", "") coins = user_info_session.get("coins", 0) login_time = user_info_session.get("login_time", "") tools = eval(user_info_session.get("tools", "{}")) restart = int(user_info_session.get('restart', 0)) direct = user_info_session.get('direct', 0) extra = int(user_info_session.get('extra', 0)) history_score = int(user_info_session.get("history_score", 0)) # challenge_info = eval(user_info_session.get("challenge_info", {})) if not history_score: user_level = await self.application.objects.get(User_Level, uuid=user_uuid) history_score = user_level.history_score if history_score: user_info_session_key = "sx_info:" + user_uuid self.redis_spare.hset(user_info_session_key, "history_score", history_score) timeArray = time.strptime(lastest_sign_date, "%Y-%m-%d") lastest_sign_timestamp = int(time.mktime(timeArray)) if lastest_sign_timestamp == day_time - 3600 * 24 and int( continuous_sign_days) == 7: continuous_sign_days = 0 if int(env_code) == 1089: # 收藏渠道4 try: user_mall = await self.application.objects.get( User_Mall, uuid=user_uuid, action_id=4) if not user_mall.status: user_mall.status = 1 await self.application.objects.update(user_mall) except User_Mall.DoesNotExist as e: pass elif int(env_code) == 1131: # 浮窗渠道5 try: user_mall = self.application.objects.get(User_Mall, uuid=user_uuid, action_id=5) if user_mall.status != 1: user_mall.status = 1 await self.application.objects.update(user_mall) except User_Mall.DoesNotExist as e: pass verified = 1 if name else 0 new_user = 0 user_info_session_key = "sx_info:" + user_uuid today_sign_status = 0 signboard = 0 if lastest_sign_date != today: signboard = 1 today_sign_status = 0 if lastest_sign_date == today: signboard = 0 today_sign_status = 1 if lastest_sign_date != today and extra: user_sign = await self.application.objects.get(User_Sign, uuid=user_uuid) user_sign.extra = 0 await self.application.objects.update(user_sign) self.redis_spare.hset(user_info_session_key, "extra", 0) extra = 0 try: user_loto = await self.application.objects.get(User_Loto, uuid=user_uuid) loto_num = user_loto.number except User_Loto.DoesNotExist as e: user_loto = await self.application.objects.create( User_Loto, uuid=user_uuid, number=3) loto_num = 3 # signboard = 0 # if lastest_sign_date < today: # signboard = 1 if login_time < today: existed_user = await self.application.objects.get( User, uuid=user_uuid) existed_user.login_time = today await self.application.objects.update(existed_user) self.redis_spare.hset(user_info_session_key, "login_time", today) user_loto.number = loto_num = 3 await self.application.objects.update(user_loto) self.redis_spare.hset(user_info_session_key, "loto_num", loto_num) for i in range(1, 6): user_mall = await self.application.objects.get( User_Mall, uuid=user_uuid, action_id=i) # if i == 1: user_mall.daily_status = 0 if user_mall.status == 2: user_mall.status = 0 await self.application.objects.update(user_mall) lotoboard = 1 if loto_num else 0 # 微信小程序不能设置cookie,把用户信息存在了headers中 self.set_header("Authorization", user_uuid) # 超越好友 user_robot_key = "robot:" + user_uuid robot_user_dict = self.redis_spare.hgetall(user_robot_key) if not robot_user_dict: next_game_config = await self.application.objects.get( Game_Config, level=int(level) + 1) next_target_score = next_game_config.target_score if next_game_config.target_score else target_score robot_user_dict, robot_last = random_robot(Config.robot_config, "", int(target_score), int(next_target_score)) print(robot_user_dict, robot_last) # self.redis_spare.hset(user_info_session_key, str(robot_user)) robot_user_dict["robot_list"] = robot_last robot_user_dict["restart"] = 0 if "id" in robot_user_dict: robot_user_dict.pop("id") self.redis_spare.hmset(user_robot_key, robot_user_dict) robot_user = { "robot_name": robot_user_dict.get("name", 0), "robot_avatar": robot_user_dict.get("avatar", ""), "robot_score": robot_user_dict.get("score", "") } # 生成color地图 random_dict = {} # if int(level) == 1 or int(level) % 10 == 0: # default_config = Config.default_config # color_array = default_config.get(int(level), []) # for ca in color_array: # for c in ca: # if c not in random_dict: # random_dict[c] = 1 # else: # random_dict[c] += 1 # else: color_array, random_list = random_color_array(int(level), int(color_num)) for rl in random_list: random_dict[rl] = 0 for ca in color_array: for c in ca: random_dict[c] += 1 payload = {"uuid": user_uuid, "exp": datetime.datetime.utcnow()} tuuid = jwt.encode(payload, SECRET_KEY, algorithm="HS256") double = 1 if lastest_sign_date != today else 0 extra_sign = 0 if extra else 1 data = { "uuid": to_str(tuuid), "openid": open_id, "level": level, "current_score": current_score, "target_score": target_score, "color_num": color_num, "direct": direct, # 是否可以看视频通关 "color_array": color_array, "verified": verified, "continuous_sign_days": continuous_sign_days, "today_sign_status": today_sign_status, "signboard": signboard, # 1显示,0不显示 "coins": coins, "tools": tools, "restart": restart, "random_dict": random_dict, "loto_num": loto_num, "lotoboard": lotoboard, "double_sign": double, "extra_sign": extra_sign, "history_score": history_score, "robot": robot_user, "new_user": new_user, # 是否为新用户 "unionid": unionId, # unionid } self.write_json(data, msg="success")
async def get(self): data = [] # result = [] result = self.redis_spare.zrevrange("world_rank", 0, 99, withscores=True) if result: for key, value in result: name = to_str(key) if name != "visitor访客": score = int(value) rank = result.index((key, value)) + 1 avatar = to_str(self.redis_spare.hget("user_avatar", name)) data.append({ "rank": rank, "name": name, "score": score, "avatarUrl": avatar }) else: pass else: # 缓存失效的情况 # 前100名排名 # result = self.application.objects.execute( # User_Level.select(User_Level.uuid, User_Level.current_score, fn.rank())\ # .order_by(User_Level.current_score) # ) result = await self.application.objects.execute( User_Level.select( User.name, User.avatar, User_Level.uuid, User_Level.current_score, User_Level.history_score).join( User, JOIN.LEFT_OUTER, on=(User.uuid == User_Level.uuid )).order_by(-User_Level.current_score)) for rk in result: print(rk) name = rk.uuid.name score = rk.current_score history_score = rk.history_score if name and (score or history_score): avatar = rk.uuid.avatar score = rk.current_score if rk.current_score > rk.history_score else rk.history_score data.append({ "name": name, "score": score, "avatarUrl": avatar }) # 排好的名次push入redis缓存 self.redis_spare.zadd("world_rank", {name: score}) self.redis_spare.hset("user_avatar", name, avatar) else: pass # TODO 改成mysql直接输出排名 for d in data: rank = data.index(d) d["rank"] = rank + 1 self.write_json(data)
async def get(self): uuid = self.get_argument("uuid", "") level = self.get_argument("level", "") score = self.get_argument("score", "") if not uuid or not score or not level: return self.write_json(status=-1, msg="请稍后重试") cur = self.cur level = int(level) next_level = level + 1 # 先删缓存,再更新数据库 # to do 分布式缓存 # user_session_key = USER_SESSION_KEY + uuid # self.session[user_session_key].pop('level') # self.session.save() # 1. 删缓存 user_info_session_key = "sx_info:" + uuid open_id = to_str(self.redis_spare.hget(user_info_session_key, b"open_id")) name = to_str(self.redis_spare.hget(user_info_session_key, b"name")) self.redis_spare.delete(user_info_session_key) # 2.更新数据库 score = int(score) # print(uuid, level, next_level, score) # sql = "insert into user_level (uuid, `level`, next_level,current_score) values(%s, %s, %s, %s)" sql = "update user_level set `level`=%s, next_level=%s, current_score=%s where uuid = %s" cur.execute(sql, [level, next_level, score, uuid]) cur.connection.commit() sql_query = "select `level`, target_score, color_num from game_config where level in (%s, %s)" cur.execute(sql_query, [level, next_level]) result = cur.fetchall() if not result: return self.write_json(status=-2, msg="请重新刷新配置") next_target_score = next_color_num = 0 if len(result) == 1: # 已到最大关卡 next_level = level for res in result: next_target_score = res.get("target_score", 0) next_color_num = res.get("color_num", 0) elif len(result) == 2: # 未达到最大关卡 for res in result: level = res.get("level", 0) if level == next_level: next_target_score = res.get("target_score", 0) next_color_num = res.get("color_num", 0) # set 缓存 self.save_user_info_session( user_uuid=uuid, openid=open_id, level=level, current_score=score, target_score=next_target_score, color_num=next_color_num ) # 存入排行榜 self.redis_spare.zadd("world_rank", {name: score}) # if int(next_level) <= 10: default_config = Config.default_config color_array = default_config.get(int(next_level), []) else: color_array = random_color_array(int(next_level), int(next_color_num)) data = { "next_level": next_level, "next_target_score": next_target_score, # "next_color_num": next_color_num, "score": score, "color_array": color_array } self.write_json(data)
async def post(self): # print(self.request.body) req_data = json.loads(to_str(self.request.body)) js_code = req_data.get('code', '') # print(js_code) # # js_code = "061GyiJJ0rM1G92nTAHJ0KZfJJ0GyiJB" # if not js_code: data = {"state": -1, "msg": "上报code有误,请核对"} return self.write_json(data) value = {} cur = self.cur # # 获取玩家信息 user_info = get_user_info(js_code) # user_info = {"openid": "sss", "session_key": "www"} open_id = user_info.get("openid", "") if not open_id: data = {"state": -2, "msg": "解析code有误,请核对1"} return self.write_json(data) session_key = user_info.get("session_key", "") user_session_key = USER_SESSION_KEY + open_id # 缓存中尝试获取uuid # print(user_session_key) # 用来维护用户的登录态(to do 分布式) # self.session[user_session_key] = dict( # user_uuid=user_uuid, # open_id=open_id, # session_key=session_key, # ) # self.session.save() # print(user_session_key) user_session = self.get_session(user_session_key) # print(user_session) if user_session == [None] or not user_session: user_uuid = str(uuid.uuid4()) self.save_user_session(user_uuid, open_id, session_key) # print(user_uuid, open_id, session_key) # 1.(数据库)存储用户信息 value["user_uuid"] = user_uuid save_result = self.save_user_info(open_id=open_id, user_uuid=user_uuid) if save_result == "False": data = { "state": False, "msg": "id问题,请重新登录1", "open_id": open_id, "user_uuid": user_uuid } return self.write_json(data, ) # 注册过但缓存过期, 查数据库,重新hset elif save_result == "already": # self.redis_spare.hget(user_session_key, level) sql = "select u.uuid, ul.level, ul.current_score, gc.target_score, gc.color_num from user as u " \ "left join user_level as ul on ul.uuid = u.uuid " \ "left join game_config as gc on gc.level = ul.level " \ "where open_id=%s" cur.execute(sql, open_id) result = cur.fetchone() if not result: data = {"state": False, "msg": "id问题,请重新登录2"} return self.write_json(data) user_uuid = result.get("uuid", "") level = result.get("level", 0) current_score = result.get("current_score", 0) target_score = result.get("target_score", 0) color_num = result.get("color_num", 0) # 生成color地图 # color_array = random_color_array(int(color_num)) else: # 未登陆过,生成配置,写数据库,hset缓存 target_score = current_score = 0 level = 1 sql_new = "select color_num, target_score from game_config where level = 1" cur.execute(sql_new) result = cur.fetchone() color_num = result.get("color_num", 0) next_level = level + 1 target_score = result.get("target_score", 0) sql_new1 = "insert into user_level (uuid, level, next_level, current_score) values(%s,%s,%s,%s)" cur.execute(sql_new1, [user_uuid, level, next_level, current_score]) cur.connection.commit() # 生成color地图 # color_array = random_color_array(int(color_num)) # 2.(缓存)存储用户信息 self.save_user_info_session(user_uuid=user_uuid, openid=open_id, level=level, current_score=current_score, target_score=target_score, color_num=color_num) else: # print(user_session) user_uuid = to_str(user_session.get(b"uuid", "")) user_info_session = self.get_user_info_session(user_uuid) level = to_str(user_info_session.get(b"level", 1)) current_score = to_str(user_info_session.get(b"current_score", 0)) target_score = to_str( user_info_session.get(b"target_score", TARGET_SCORE_CONST)) color_num = to_str( user_info_session.get(b"color_num", COLOR_NUM_CONST)) # 微信小程序不能设置cookie,把用户信息存在了headers中 self.set_header("Authorization", user_uuid) # 生成color地图 if int(level) <= 10: default_config = Config.default_config color_array = default_config.get(int(level), []) else: color_array = random_color_array(int(level), int(color_num)) # 登录判断是否授权过 user_info_session_key = "sx_info:" + user_uuid name = to_str(self.redis_spare.hget(user_info_session_key, "name")) if name: verified = 1 else: verified = 0 data = { "uuid": user_uuid, "openid": open_id, "level": level, "current_score": current_score, "target_score": target_score, # "color_num": color_num, "color_array": color_array, "verified": verified } # print(data) self.write_json(data, msg="success")
async def get(self): uuid = self.current_user.uuid print(uuid) # 1. 删缓存 user_info_session_key = "sx_info:" + uuid # open_id = self.redis_spare.hget(user_info_session_key, "open_id") name = self.redis_spare.hget(user_info_session_key, "name") tools = self.redis_spare.hget(user_info_session_key, "tools") print(type(tools)) # verified = self.redis_spare.hget(user_info_session_key, "verified") # coins = self.redis_spare.hget(user_info_session_key, "coins") # print(self.redis_spare.hgetall(user_info_session_key)) # print(coins) # self.redis_spare.delete(user_info_session_key) # 2. 更新数据库 user_level = await self.application.objects.get(User_Level, uuid=uuid) user_level.level = 1 user_level.next_level = 2 current_score = int(user_level.current_score) user_level.current_score = 0 user_level.restart = 1 history_score = user_level.history_score await self.application.objects.update(user_level) try: game_config = await self.application.objects.get(Game_Config, level=1) next_target_score = game_config.target_score next_color_num = game_config.color_num nn_next_game_config = await self.application.objects.get( Game_Config, level=2) nnext_target_score = nn_next_game_config.target_score except Game_Config.DoesNotExist as e: return self.write_json(status=-2, msg="请重新刷新配置") # set缓存 value = { "level": user_level.level, "current_score": user_level.current_score, "target_score": next_target_score, "color_num": next_color_num, "restart": 1 } self.redis_spare.hmset(user_info_session_key, value) # 存入排行榜 20200213 删掉 # if name: # # name = "visitor访客" # self.redis_spare.zadd("world_rank", {name: 0}) color_array, random_list = random_color_array(1, int(next_color_num)) payload = {"uuid": uuid, "exp": datetime.datetime.utcnow()} tuuid = jwt.encode(payload, SECRET_KEY, algorithm="HS256") random_dict = {} for rl in random_list: random_dict[rl] = 0 for ca in color_array: for c in ca: random_dict[c] += 1 # 超越好友 user_robot_key = "robot:" + uuid restart_times = int( self.redis_spare.hget(user_robot_key, "restart") or 0) + 1 robot_user_dict, robot_last = random_robot(Config.robot_config, "", current_score, nnext_target_score, restart=restart_times) robot_user_dict["restart"] = restart_times self.redis_spare.hmset(user_robot_key, robot_user_dict) robot_user = { "robot_name": robot_user_dict.get("name", 0), "robot_avatar": robot_user_dict.get("avatar", ""), "robot_score": robot_user_dict.get("score", "") } data = { "level": 1, "target_score": next_target_score, # "next_color_num": next_color_num, "current_score": 0, "color_array": color_array, "tools": eval(tools), "uuid": to_str(tuuid), "random_dict": random_dict, "history_score": history_score, "robot": robot_user } self.write_json(data)