From fa1bd111fc5d1356a55b79fdc11b62aab282b68e Mon Sep 17 00:00:00 2001 From: misodengaku Date: Wed, 8 Nov 2023 21:21:35 +0900 Subject: [PATCH] python: generate_error_resp --- webapp/python/app.py | 220 +++++++++++++++++++++++++++---------------- 1 file changed, 138 insertions(+), 82 deletions(-) diff --git a/webapp/python/app.py b/webapp/python/app.py index fb06e1e25..270f77445 100644 --- a/webapp/python/app.py +++ b/webapp/python/app.py @@ -33,9 +33,9 @@ def initialize_handler(): result = subprocess.run(["../sql/init.sh"], capture_output=True, text=True) if result.returncode != 0: app.logger.error("init.sh failed with err=", result.stdout) - return result.stderr, 500 + return generate_error_resp(result.stderr, 500) - return {"advertise_level": 10, "language": "python"}, 200 + return {"advertise_level": 10, "language": "python"} # top @@ -51,7 +51,7 @@ def get_tag_handler(): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return requests.codes["internal_server_error"], "db error" + return generate_error_resp("db error", requests.codes["internal_server_error"]) return {"tags": tags} @@ -70,17 +70,17 @@ def get_streamer_theme_handler(username: str): c.execute(sql, [username]) user = c.fetchone() if user is None: - return "not found", requests.codes["not_found"] + return generate_error_resp("not found", requests.codes["not_found"]) sql = "SELECT * FROM themes WHERE user_id = %s" c.execute(sql, [user["id"]]) theme = c.fetchone() if theme is None: - return "not found", requests.codes["not_found"] + return generate_error_resp("not found", requests.codes["not_found"]) conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return {"id": theme["id"], "dark_mode": theme["dark_mode"] == 1} @@ -94,7 +94,7 @@ def reserve_livestream_handler(): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) req = get_request_json() @@ -110,7 +110,9 @@ def reserve_livestream_handler(): reserve_end_at = datetime.fromtimestamp(float(req["end_at"]), tz=timezone.utc) if reserve_start_at >= term_end_at or reserve_end_at <= term_start_at: - return "bad reservation time range", requests.codes["bad_request"] + return generate_error_resp( + "bad reservation time range", requests.codes["bad_request"] + ) # 予約枠をみて、予約が可能か調べる sql = "SELECT * FROM reservation_slots WHERE start_at >= %s AND end_at <= %s" @@ -118,7 +120,7 @@ def reserve_livestream_handler(): slots = c.fetchall() if not slots: app.logger.error("予約枠一覧取得でエラー発生") - return ( + return generate_error_resp( "failed to get reservation_slots", requests.codes["internal_server_error"], ) @@ -129,7 +131,7 @@ def reserve_livestream_handler(): c.execute(sql, [slot["start_at"], slot["end_at"]]) count = c.fetchone() if not count: - return ( + return generate_error_resp( "failed to get reservation_slots", requests.codes["internal_server_error"], ) @@ -144,7 +146,7 @@ def reserve_livestream_handler(): }, ) if count < 1: - return ( + return generate_error_resp( f"予約区間 {req['start_at']} ~ {req['end_at']}が予約できません", requests.codes["bad_request"], ) @@ -186,7 +188,9 @@ def reserve_livestream_handler(): livestream = fill_livestream_response(c, livestream_model) if not livestream: - return "failed to fill livestream", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to fill livestream", requests.codes["internal_server_error"] + ) conn.commit() conn.close() @@ -211,7 +215,9 @@ def search_livestreams_handler(): c.execute(sql, [key_tag_name]) tags = c.fetchall() if not tags: - return "tag not match", requests.codes["internal_server_error"] + return generate_error_resp( + "tag not match", requests.codes["internal_server_error"] + ) tag_id_list = list(map(lambda x: x["id"], tags)) sql = "SELECT * FROM livestream_tags WHERE tag_id IN (%s)" # idかtag_idか要確認 @@ -245,14 +251,16 @@ def search_livestreams_handler(): for livestream_model in livestream_models: livestream = fill_livestream_response(c, livestream_model) if not livestream: - return "error", requests.codes["internal_server_error"] + return generate_error_resp( + "error", requests.codes["internal_server_error"] + ) livestreams.append(livestream) conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return livestreams @@ -264,7 +272,7 @@ def get_my_livestreams_handler(): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) try: conn = dbh() @@ -274,7 +282,7 @@ def get_my_livestreams_handler(): c.execute(sql, [sess_user_id]) livestream_models = c.fetchall() if not livestream_models: - return ( + return generate_error_resp( "failed to get livestreams", requests.codes["internal_server_error"], ) @@ -283,7 +291,7 @@ def get_my_livestreams_handler(): for i, livestream_model in enumerate(livestream_models): livestream = fill_livestream_response(c, livestream_model) if not livestream: - return ( + return generate_error_resp( "failed to fill livestream", requests.codes["internal_server_error"], ) @@ -291,7 +299,7 @@ def get_my_livestreams_handler(): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return livestreams @@ -309,13 +317,15 @@ def get_user_livestreams_handler(username): c.execute(sql, [username]) user = c.fetchone() if not user: - return "failed to get user", requests.codes["not_found"] + return generate_error_resp( + "failed to get user", requests.codes["not_found"] + ) sql = "SELECT * FROM livestreams WHERE user_id = %s" c.execute(sql, [user["id"]]) livestream_models = c.fetchall() if not livestream_models: - return ( + return generate_error_resp( "failed to get livestreams", requests.codes["internal_server_error"], ) @@ -324,7 +334,7 @@ def get_user_livestreams_handler(username): for i, livestream_model in enumerate(livestream_models): livestream = fill_livestream_response(c, livestream_model) if not livestream: - return ( + return generate_error_resp( "failed to fill livestream", requests.codes["internal_server_error"], ) @@ -332,7 +342,7 @@ def get_user_livestreams_handler(username): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return livestreams @@ -351,13 +361,13 @@ def get_livestream_handler(livestream_id: int): c.execute(sql, [livestream_id]) livestream_model = c.fetchone() if livestream_model is None: - return "not found", requests.codes["not_found"] + return generate_error_resp("not found", requests.codes["not_found"]) livestream = fill_livestream_response(c, livestream_model) conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return livestream @@ -382,19 +392,21 @@ def get_livecomments_handler(livestream_id: int): livecomments = c.fetchall() if livecomments is None or len(livecomments) == 0: - return "not found", requests.codes["not_found"] + return generate_error_resp("not found", requests.codes["not_found"]) print(livecomments) for i, livecomment in enumerate(livecomments): livecomment = fill_livecomment_response(c, livecomment) print(livecomment) if not livecomment: - return "error", requests.codes["internal_server_error"] + return generate_error_resp( + "error", requests.codes["internal_server_error"] + ) livecomments[i] = livecomment conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return livecomments @@ -407,7 +419,7 @@ def post_livecomment_handler(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) req = get_request_json() @@ -419,7 +431,9 @@ def post_livecomment_handler(livestream_id: int): c.execute(sql) ng_words = c.fetchall() if ng_words is None: - return "failed to get NG words", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get NG words", requests.codes["internal_server_error"] + ) for ng_word in ng_words: sql = """ @@ -433,11 +447,15 @@ def post_livecomment_handler(livestream_id: int): c.execute(sql, [req["comment"], ng_word["word"]]) hit_spam = c.fetchone() if not hit_spam: - return "failed to get hitspam", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get hitspam", requests.codes["internal_server_error"] + ) hit_spam = hit_spam["COUNT(*)"] app.logger.info(f"[hitSpam={hit_spam}] comment = {req['comment']}") if hit_spam >= 1: - return "このコメントがスパム判定されました", requests.codes["bad_request"] + return generate_error_resp( + "このコメントがスパム判定されました", requests.codes["bad_request"] + ) now = int(datetime.now().timestamp()) @@ -467,7 +485,7 @@ def post_reaction_handler(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) req = get_request_json() @@ -516,7 +534,9 @@ def get_reactions_handler(livestream_id: int): reaction_models = c.fetchall() if reaction_models is None: app.logger.info("reaction_models") - return "failed to get reactions", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get reactions", requests.codes["internal_server_error"] + ) reactions = [] for reaction_model in reaction_models: @@ -543,14 +563,16 @@ def get_livecomment_reports_handler(livestream_id: int): livestream_model = c.fetchone() if not livestream_model: app.logger.info("livestream_model") - return "failed to get livestream", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get livestream", requests.codes["internal_server_error"] + ) sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) if livestream_model["user_id"] != sess_user_id: - return ( + return generate_error_resp( "can't get other streamer's livecomment reports", requests.codes["forbidden"], ) @@ -560,7 +582,7 @@ def get_livecomment_reports_handler(livestream_id: int): report_models = c.fetchall() if report_models is None: app.logger.info("report_model") - return ( + return generate_error_resp( "failed to get livecomment reports", requests.codes["internal_server_error"], ) @@ -570,7 +592,7 @@ def get_livecomment_reports_handler(livestream_id: int): report = fill_livecomment_report_response(c, report_model) if not report: app.logger.info("failed to fill livecomment report") - return ( + return generate_error_resp( "failed to fill livecomment report", requests.codes["internal_server_error"], ) @@ -588,7 +610,7 @@ def get_ngwords(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) try: conn = dbh() @@ -599,13 +621,15 @@ def get_ngwords(livestream_id: int): ngwords = c.fetchall() if ngwords is None: app.logger.error("failed to get ngwords") - return "error", requests.codes["internal_server_error"] + return generate_error_resp( + "error", requests.codes["internal_server_error"] + ) if len(ngwords) == 0: return [] conn.commit() return ngwords except: - return "error", requests.codes["internal_server_error"] + return generate_error_resp("error", requests.codes["internal_server_error"]) # ライブコメント報告 @@ -620,7 +644,9 @@ def report_livecomment_handler(livestream_id: int, livecomment_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "failed to find user-id from session", requests.codes["unauthorized"] + return generate_error_resp( + "failed to find user-id from session", requests.codes["unauthorized"] + ) conn = dbh() conn.begin() @@ -653,11 +679,13 @@ def moderate_handler(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "failed to find user-id from session", requests.codes["unauthorized"] + return generate_error_resp( + "failed to find user-id from session", requests.codes["unauthorized"] + ) req = get_request_json() if not req or "ng_word" not in req: - return ( + return generate_error_resp( "failed to decode the request body as json", requests.codes["bad_request"], ) @@ -671,7 +699,7 @@ def moderate_handler(livestream_id: int): c.execute(sql, [livestream_id, sess_user_id]) owned_livestreams = c.fetchall() if owned_livestreams is None or len(owned_livestreams) == 0: - return ( + return generate_error_resp( "A streamer can't moderate livestreams that other streamers own", requests.codes["bad_request"], ) @@ -714,7 +742,7 @@ def moderate_handler(livestream_id: int): conn.commit() return {"word_id": word_id}, requests.codes["created"] except: - return "error", requests.codes["internal_server_error"] + return generate_error_resp("error", requests.codes["internal_server_error"]) # livestream_viewersにINSERTするため必要 @@ -727,7 +755,9 @@ def enter_livestream_handler(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "failed to find user-id from session", requests.codes["unauthorized"] + return generate_error_resp( + "failed to find user-id from session", requests.codes["unauthorized"] + ) conn = dbh() conn.begin() @@ -748,7 +778,9 @@ def exit_livestream_handler(livestream_id: int): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "failed to find user-id from session", requests.codes["unauthorized"] + return generate_error_resp( + "failed to find user-id from session", requests.codes["unauthorized"] + ) conn = dbh() conn.begin() @@ -765,7 +797,7 @@ def exit_livestream_handler(livestream_id: int): def register_handler(): req = get_request_json() if not req: - return ( + return generate_error_resp( "failed to decode the request body as json", requests.codes["bad_request"], ) @@ -774,13 +806,15 @@ def register_handler(): key in req for key in ["name", "password", "display_name", "description", "theme"] ): - return ( + return generate_error_resp( "failed to decode the request body as json", requests.codes["bad_request"], ) if req["name"] == "pipe": - return "the username 'pipe' is reserved", requests.codes["bad_request"] + return generate_error_resp( + "the username 'pipe' is reserved", requests.codes["bad_request"] + ) hashed_password = bcrypt.hashpw(req["password"].encode(), bcrypt.gensalt(rounds=4)) @@ -827,12 +861,16 @@ def register_handler(): text=True, ) if result.returncode != 0: - return result.stdout, requests.codes["internal_server_error"] + return generate_error_resp( + result.stdout, requests.codes["internal_server_error"] + ) user = fill_user_response(c, user_model) conn.commit() except pymysql.err.IntegrityError: - return "failed to insert user", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to insert user", requests.codes["internal_server_error"] + ) return user, requests.codes["created"] @@ -841,7 +879,7 @@ def login_handler(): try: req = get_request_json() if not req: - return ( + return generate_error_resp( "failed to decode the request body as json", requests.codes["bad_request"], ) @@ -853,11 +891,15 @@ def login_handler(): c.execute(sql, [req["username"]]) user = c.fetchone() if not user: - return "invalid username or password", requests.codes["unauthorized"] + return generate_error_resp( + "invalid username or password", requests.codes["unauthorized"] + ) # password: $2b$04$RkawbeHu.1GLl8kPuHNYoOJCyK.LCcTZahJptUaF3p7z6VD0j24Gi if not bcrypt.checkpw(req["password"].encode(), user["password"].encode()): - return "invalid username or password", requests.codes["unauthorized"] + return generate_error_resp( + "invalid username or password", requests.codes["unauthorized"] + ) session_end_at = datetime.now() + timedelta(hours=1) session_id = str(uuid.uuid4()) @@ -874,7 +916,7 @@ def login_handler(): return "", requests.codes["ok"] except: - return "error", requests.codes["internal_server_error"] + return generate_error_resp("error", requests.codes["internal_server_error"]) @app.route("/api/user/me", methods=["GET"]) @@ -885,7 +927,7 @@ def get_me_handler(): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) try: conn = dbh() @@ -898,7 +940,7 @@ def get_me_handler(): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return user @@ -920,7 +962,7 @@ def get_user_handler(username: str): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return user @@ -957,7 +999,7 @@ def get_user_statistics_handler(username: str): c.execute(sql, [user["id"]]) reactions = c.fetchone() if not reactions: - return ( + return generate_error_resp( "failed to count reactions", requests.codes["internal_server_error"], ) @@ -971,7 +1013,7 @@ def get_user_statistics_handler(username: str): c.execute(sql, [user["id"]]) tips = c.fetchone() if not tips: - return ( + return generate_error_resp( "failed to count tips", requests.codes["internal_server_error"], ) @@ -1002,7 +1044,7 @@ def get_user_statistics_handler(username: str): c.execute(sql, [username]) total_reactions = c.fetchone() if not total_reactions: - return ( + return generate_error_resp( "failed to count total reactions", requests.codes["internal_server_error"], ) @@ -1017,7 +1059,7 @@ def get_user_statistics_handler(username: str): livestreams = c.fetchall() if livestreams is None: app.logger.error("livestreams livecomments") - return ( + return generate_error_resp( "failed to get livestreams", requests.codes["internal_server_error"], ) @@ -1028,7 +1070,7 @@ def get_user_statistics_handler(username: str): livecomments = c.fetchall() if livecomments is None: app.logger.error("livecomments") - return ( + return generate_error_resp( "failed to get livecomments", requests.codes["internal_server_error"], ) @@ -1044,7 +1086,7 @@ def get_user_statistics_handler(username: str): livestreams = c.fetchall() if livestreams is None: app.logger.error("viewers_count") - return ( + return generate_error_resp( "failed to get livestreams", requests.codes["internal_server_error"], ) @@ -1054,7 +1096,7 @@ def get_user_statistics_handler(username: str): c.execute(sql, [livestream["id"]]) cnt = c.fetchone() if not cnt: - return ( + return generate_error_resp( "failed to get livestream_view_history", requests.codes["internal_server_error"], ) @@ -1103,7 +1145,9 @@ def get_icon_handler(username: str): c.execute(sql, [username]) user = c.fetchone() if not user: - return "user not found", requests.codes["internal_server_error"] + return generate_error_resp( + "user not found", requests.codes["internal_server_error"] + ) sql = "SELECT image FROM icons WHERE user_id = %s" c.execute(sql, [user["id"]]) @@ -1124,7 +1168,7 @@ def get_icon_handler(username: str): except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) @app.route("/api/icon", methods=["POST"]) @@ -1135,11 +1179,11 @@ def post_icon_handler(): sess_user_id = flask.session.get(DEFAULT_USER_ID_KEY) if not sess_user_id: - return "unauthorized", requests.codes["unauthorized"] + return generate_error_resp("unauthorized", requests.codes["unauthorized"]) req = get_request_json() if not req or "image" not in req: - return ( + return generate_error_resp( "failed to decode the request body as json", requests.codes["bad_request"], ) @@ -1159,7 +1203,7 @@ def post_icon_handler(): conn.commit() except pymysql.Error as err: app.logger.exception(err) - return "db error", requests.codes["internal_server_error"] + return generate_error_resp("db error", requests.codes["internal_server_error"]) return {"id": icon_id}, requests.codes["created"] @@ -1180,13 +1224,17 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) livestream = c.fetchone() if livestream is None: - return "failed to get livestream", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get livestream", requests.codes["internal_server_error"] + ) sql = "SELECT * FROM livestreams" c.execute(sql) livestreams = c.fetchall() if livestreams is None: - return "failed to get livestreams", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to get livestreams", requests.codes["internal_server_error"] + ) # ランク算出 ranking = [] @@ -1195,7 +1243,7 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) reactions = c.fetchone() if reactions is None: - return ( + return generate_error_resp( "failed to get livestream", requests.codes["internal_server_error"], ) @@ -1205,7 +1253,9 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) total_tips = c.fetchone() if total_tips is None: - return "failed to count tips", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to count tips", requests.codes["internal_server_error"] + ) total_tips = total_tips["IFNULL(SUM(l2.tip), 0)"] score = reactions + total_tips @@ -1233,7 +1283,7 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) viewers_count = c.fetchone() if viewers_count is None: - return ( + return generate_error_resp( "failed to get viewers_count", requests.codes["internal_server_error"], ) @@ -1244,7 +1294,7 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) max_tip = c.fetchone() if max_tip is None: - return ( + return generate_error_resp( "failed to get max_tip", requests.codes["internal_server_error"], ) @@ -1255,7 +1305,7 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) total_reactions = c.fetchone() if total_reactions is None: - return ( + return generate_error_resp( "failed to get total_reactions", requests.codes["internal_server_error"], ) @@ -1266,7 +1316,7 @@ def get_livestream_statistics_handler(livestream_id: int): c.execute(sql, [livestream_id]) total_reports = c.fetchone() if total_reports is None: - return ( + return generate_error_resp( "failed to get total_reports", requests.codes["internal_server_error"], ) @@ -1291,7 +1341,9 @@ def get_payment_result(): c.execute(sql) total_tip = c.fetchone() if not total_tip: - return "failed to count total tip", requests.codes["internal_server_error"] + return generate_error_resp( + "failed to count total tip", requests.codes["internal_server_error"] + ) conn.commit() return {"total_tip": total_tip} @@ -1480,6 +1532,10 @@ def get_request_json() -> dict: return json.loads(flask.request.get_data().decode()) +def generate_error_resp(msg: str, code: int) -> tuple[dict, int]: + return {"error": f"code={code}, message={msg}", "message": msg}, code + + if __name__ == "__main__": # // DB接続 # conn, err := connectDB(e.Logger)