def leave_live_room(target_sid=None): global room_info # room_info = cache.get("room_info") if target_sid is None: target_sid = request.sid for room in room_info: for sid in list(room_info[room]["users"]): if sid == target_sid: del room_info[room]["users"][sid] room_id = room leave_room(room_id, sid=sid, namespace="/live") if len(room_info[room_id]["users"]) == 0: del room_info[room_id] else: if sid == room_info[room_id]["room_master"]: room_info[room_id]["room_master"] = list(room_info[room_id]["users"])[0] emit("update_room_info", { "users": room_info[room_id]["users"], "room_master": room_info[room_id]["room_master"], "setting": room_info[room_id]["setting"] }, room=room_id, namespace="/live") cache.set("room_info", room_info)
def get_day_language_xp_list(self, since: arrow.Arrow) -> List[DailyLanguageXp]: cache_key = get_key_with_prefix( f"{self.username}_{since.strftime('%Y-%m-%d')}", 'day_language_xp') lock_key = get_key_with_prefix(cache_key, 'lock') data = cache.get(cache_key) # add lock to make sure only one request is fetching response from server (hopefully) lock = cache.cache.inc(lock_key, delta=1) set_redis_expire_seconds(lock_key, 15) while data is None and isinstance(lock, int) and lock > 1: time.sleep(1) data = cache.get(cache_key) lock = cache.get(lock_key) if data is None: post_data = '''{ profile(username: "******") { day_language_xps: dayLanguageXps(since: "%s") {date language xp} } }''' % (self.username, since.strftime('%Y-%m-%d')) response_json = requests.post( 'https://codestats.net/profile-graph', data=post_data).json() current_app.logger.info('response json from %s: %s', self.username, response_json) data = response_json['data']['profile']['day_language_xps'] cache.set(cache_key, data, timeout=30 * 60) current_app.logger.info('set cache [%s]', cache_key) cache.delete(lock_key) self.day_language_xp_list = DailyLanguageXpSchema().load(data, many=True) return self.day_language_xp_list
def ratelimit_wrapper(*args, **kwargs): ip_address = current_user.get_ip() key = f"{key_prefix}:{ip_address}:{request.endpoint}" current = cache.get(key) if request.method == method: if (current and int(current) > limit - 1): return abort(429) else: if current is None: cache.set(key, 1, timeout=interval) else: cache.set(key, int(current) + 1, timeout=interval) return f(*args, **kwargs)
def fetch_spread_sheet(): from app.cache import cache gc = gspread.authorize(credentials).open("문법") wks = gc.get_worksheet(0) rows = wks.get_all_values() print(rows) try: data = [] for i in range(1, len(rows) + 1, 2): # row_tuple = Munhak(*row) # row_tuple = row_tuple._replace(keywords=json.loads(row_tuple.keywords)) # if row_tuple.is_available == "TRUE": # data.append(row_tuple) row1 = rows[i] row2 = rows[i + 1] if dict(zip(rows[0], row1))["is_available"] == "T": temp_dict = {} temp_dict["quiz_seq"] = int(row1[0]) problem = row1[1].strip() if problem[-1] == "." or problem[-1] == '?' or problem[ -1] == "!": problem = problem[:len(problem) - 1] + " " + problem[-1] correct = row2[1].strip() if correct[-1] == "." or correct[-1] == '?' or correct[ -1] == "!": correct = correct[:len(correct) - 1] + " " + correct[-1] temp_dict["quiz"] = {"problem": problem, "correct": correct} data.append(temp_dict) except: pass cache.set('quiz_data', data, timeout=99999999999999999) print(data) print(data) print(data) # print(munhak_rows) return len(data)
def set_real_username(self) -> None: # use lowercase for cache key because it's case insensitive username_lower = self.username.lower() cache_key = get_key_with_prefix(username_lower, 'real_username') real_username = cache.get(cache_key) if real_username is None: response = requests.get( f'https://codestats.net/api/users/{self.username}') if response.status_code == requests.codes.not_found: raise UserNotFoundException() real_username = response.json()['user'] current_app.logger.info('got real username %s for %s', real_username, self.username) cache.set(cache_key, real_username, timeout=24 * 60 * 60) current_app.logger.info('set cache [%s]', cache_key) # username in profile-graph api is case sensitive so set the username to the correct one self.username = real_username
def fetch_spread_sheet(): from app.cache import cache gc = gspread.authorize(credentials).open("문학따먹기") wks = gc.get_worksheet(0) rows = wks.get_all_values() # print(rows) Munhak = namedtuple("Munhak", rows[0]) try: data = [] for row in rows[1:]: # row_tuple = Munhak(*row) # row_tuple = row_tuple._replace(keywords=json.loads(row_tuple.keywords)) # if row_tuple.is_available == "TRUE": # data.append(row_tuple) temp_dict = dict(zip(rows[0], row)) if temp_dict["is_available"] == "TRUE": if temp_dict["title"] == "" or temp_dict["writer"] == "": break temp_dict["keywords"] = json.loads(temp_dict["keywords"]) temp_dict["munhak_seq"] = int(temp_dict["munhak_seq"]) data.append(temp_dict) except: pass # global munhak_rows_data munhak_rows_data = data munhak_quiz_rows_data = [munhak_row for munhak_row in munhak_rows_data if len(munhak_row["keywords"]) != 0] munhak_rows_data_dict = {} for munhak_row in munhak_rows_data: munhak_rows_data_dict[munhak_row["munhak_seq"]] = munhak_row cache.set('munhak_rows_data', munhak_rows_data, timeout=99999999999999999) cache.set('munhak_rows_data_dict', munhak_rows_data_dict, timeout=99999999999999999) cache.set('munhak_quiz_rows_data', munhak_quiz_rows_data, timeout=99999999999999999) # print(data) # print(munhak_rows) return len(data)
def create_app(config_filename): app = Flask(__name__, static_url_path='', static_folder='../static', template_folder='../templates') app.secret_key = os.environ.get('SECRET_KEY', None) app.config.from_object(config_filename) # app.response_class = MyResponse from app.db import db from app.session import sess # db.init_app(app) # db.app = app sess.init_app(app) # pjax.init_app(app) # sched.init_app(app) # redis_client.init_app(app) from app.cache import cache # Blueprints from app.others.views import others_bp from app.quiz.views import quiz_bp # from app.students.views import users_bp # from app.schools.views import schools_bp # from app.meals.views import meals_bp # from app.board.views import board_bp # # app.register_blueprint(quiz_bp, url_prefix='/quiz') app.register_blueprint(others_bp, url_prefix='/') # app.register_blueprint(board_bp, url_prefix='/') # app.register_blueprint(user_bp, url_prefix='/') # app.register_blueprint(users_bp, url_prefix='/api/students') # app.register_blueprint(schools_bp, url_prefix='/api/schools') # app.register_blueprint(meals_bp, url_prefix='/api/meals') # app.register_blueprint(board_bp, url_prefix='/api/board') # sched.add_job(lambda: update_meal_board_views(), 'cron', second='05', id="update_meal_board_views") # Markdown(app, extensions=['nl2br', 'fenced_code']) fetch_spread_sheet() cache.set("room_info", {}, timeout=999999999999999) app.add_template_global(name="TAG_SOURCE", f=list( {"건국신화", "고대가요", "설화", "향가", "4구체", "8구체", "한시", "전", "소악부", "시조", "한시", "고려속요", "가전체", "한문소설", "악장", "경기체가", "가사", "몽유록", "고대", "중세", "근대", "사대부", "국문", "사설시조", "국문소설", "야담", "구비문학", "신소설", "근대소설", "잡가", "사실주의", "계급주의", "낭만주의", "서사시", "모더니즘", "농촌소설", "역사소설", "순수소설", "순수시", "생명파", "전원파", "민요", "창가", "신체시", "자유시", "저항시", "청록파", "일제강점기", "전후소설", "사실주의", "참여시", "민중시", "포스트모더니즘" "반어법", "역설법", "수미상관", "서정시", "극시", "서경시", "정형시", "자유시", "산문시", "판소리", "마당극", "인형극", "패관문학", })) CORS(app) return app