def on_create(data): user_id = data.get('user_id') if not user_id: # emit("join_room", {'error': 'no user id provided', 'status':'error'}) user_id = str(uuid4()) expression = get_random_expression() sentence = expression.get('text') random_word = get_random_word(sentence) user_sentence = obfuscate_in_sentence(sentence, random_word) correct_answer = random_word if random_word[-1] not in [ ',', ':', ';' ] else random_word[:-1] game_state = { 'user_id': user_id, 'score': 0, 'answers': [], 'user_sentence': user_sentence, 'correct_answer': correct_answer, 'original_sentence': sentence, 'started_on': datetime.utcnow().strftime(DATE_FORMAT), } user_game_state = generate_user_game_state(game_state) room_id = game_state['user_id'] redis.set(room_id, json.dumps(game_state), ex=THRESHOLD * 2) join_room(room_id) emit("join_room", {'game_state': user_game_state, 'status': 'ok'})
def token_verify(token): try: data = jwt.decode(token, app.config["SECRET_KEY"]) code = data["code"] key = "support_jwt_{}".format(code) data = json.loads(redis.get(key)) if not data: return "EXPIRED" elif data.get("token") != token: return "OFFLINE" else: user = TbUser.query.filter_by(code=code).first() if not user: return "NOT_EXIST" request.token = data # 更新 token redis.set(key, value=json.dumps({ "exp_time": utc_timestamp() + 24 * 60 * 60, "token": token }), ex=24 * 60 * 60) return user except TypeError: # 代表没有从 redis 中取得数据 return "EXPIRED" except Exception as e: app.logger.info("obtain data error: {}".format(str(e))) return "INVALID"
def generate_token(user) -> str: token = jwt.encode({ "code": user.code, "time": utc_timestamp() }, app.config["SECRET_KEY"]).decode() key = "support_jwt_{}".format(user.code) data = {"exp_time": utc_timestamp() + 24 * 60 * 60, "token": token} redis.set(key, value=json.dumps(data), ex=24 * 60 * 60) return token
def on_solve(data): user_id = data.get('user_id') answer = data.get('answer') if not user_id: emit("update", {'error': 'no user id provided', 'status': 'error'}) if not answer: emit("update", {'error': 'no answer provided', 'status': 'error'}) if not redis.exists(user_id): emit("update", { 'error': 'user doesnt have a game_state started', 'status': 'error' }) game_state = json.loads(redis.get(user_id)) if datetime.utcnow() - datetime.strptime(game_state['started_on'], DATE_FORMAT) > THRESHOLD: emit("update", {'error': 'game finished', 'status': 'finished'}) correct_answer = game_state['correct_answer'] original_sentence = game_state['original_sentence'] correct_answer_variations = getAnswerVariations(correct_answer) is_correct_answer = process.extractOne( answer, correct_answer_variations, score_cutoff=91) != None game_state['answers'].append({ 'answer': answer, 'sentence': reconstruct_sentence(original_sentence, answer, correct_answer), 'is_correct': is_correct_answer }) if is_correct_answer: game_state['score'] = game_state['score'] + 1 next_expression = get_random_expression() next_sentence = next_expression.get('text') next_random_word = get_random_word(next_sentence) next_user_sentence = obfuscate_in_sentence(next_sentence, next_random_word) next_correct_answer = next_random_word if next_random_word[-1] not in [ ',', ':', ';' ] else next_random_word[:-1] game_state['user_sentence'] = next_user_sentence game_state['correct_answer'] = next_correct_answer game_state['original_sentence'] = next_sentence game_state['last_time_answered'] = datetime.utcnow().strftime(DATE_FORMAT) redis.set(user_id, json.dumps(game_state), ex=2 * THRESHOLD) user_game_state = generate_user_game_state(game_state) emit("update", {'game_state': user_game_state, 'status': 'ok'})
def post(self): """ 编辑请求 """ req, error = validate_schema(universal_schema, request.json) if error: return error, 400 user = request.current_user # 执行锁住操作 key = "edit_{}_config_lock".format(ConfigNameMap.name[req["category"]]) res = redis.get(key) if res and json.loads(res)["user_code"] != user.code: return Msg.EDIT_LOCKED, 400 else: data = json.dumps({"user_code": user.code}) exp = app.config.get("EDIT_EXPIRATION") exp = int(exp) if exp else 3600 redis.set(key, data, ex=exp) return {"exp_time": exp}, 200
def set(self, data): redis.set(self.key, json.dumps(data))