From a205ebf3a459d6fdca3a61a7e939f66fa1ead864 Mon Sep 17 00:00:00 2001 From: CakesTwix Date: Fri, 23 Aug 2024 20:18:57 +0300 Subject: [PATCH] Reformat via black, fix for Python <3.12 and added Flask-Caching to req --- app/app.py | 88 +++++++++++++++++++++++++------------- app/models/db.py | 3 +- app/models/request_data.py | 14 +++++- app/services/torrents.py | 54 ++++++++++++++++------- requirements.txt | 1 + 5 files changed, 112 insertions(+), 48 deletions(-) diff --git a/app/app.py b/app/app.py index 85fb286..966564a 100644 --- a/app/app.py +++ b/app/app.py @@ -8,20 +8,25 @@ from flask_sqlalchemy import SQLAlchemy from toloka2MediaServer.main_logic import ( - add_release_by_url, update_release_by_name, update_releases, - search_torrents, get_torrent as get_torrent_external, - add_torrent as add_torrent_external + add_release_by_url, + update_release_by_name, + update_releases, + search_torrents, + get_torrent as get_torrent_external, + add_torrent as add_torrent_external, ) -cache = Cache(config={'CACHE_TYPE': 'SimpleCache'}) +cache = Cache(config={"CACHE_TYPE": "SimpleCache"}) app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///t2w.db" cache.init_app(app) from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass + class Base(DeclarativeBase, MappedAsDataclass): - pass + pass + db = SQLAlchemy(app, model_class=Base) @@ -30,6 +35,7 @@ from models.db import ImagesCache with app.app_context(): db.create_all() + @app.route("/") @cache.cached(timeout=1) def root_route(): @@ -38,13 +44,21 @@ def root_route(): titles = config.titles_config new_torrent = 0 for title in titles.sections(): - if request.args.get('query', '') in title: - image_cache = db.session.execute(db.select(ImagesCache).filter_by(codename=title)).scalar_one_or_none() + if request.args.get("query", "") in title: + image_cache = db.session.execute( + db.select(ImagesCache).filter_by(codename=title) + ).scalar_one_or_none() if image_cache: titles[title]["image"] = image_cache.image else: - toloka_torrent = config.toloka.get_torrent(f"https://toloka.to/{titles[title]["guid"]}") - toloka_img = f"https:{toloka_torrent.img}" if toloka_torrent.img.startswith("//") else toloka_torrent.img + toloka_torrent = config.toloka.get_torrent( + f"https://toloka.to/{titles[title]['guid']}" + ) + toloka_img = ( + f"https:{toloka_torrent.img}" + if toloka_torrent.img.startswith("//") + else toloka_torrent.img + ) db.session.add(ImagesCache(title, toloka_img)) db.session.commit() @@ -52,42 +66,59 @@ def root_route(): # Config data titles[title]["codename"] = title - titles[title]["torrent_name"] = titles[title]["torrent_name"].replace("\"", "") + titles[title]["torrent_name"] = titles[title]["torrent_name"].replace( + '"', "" + ) sections.append(titles[title]) - return render_template('index.html', titles = sections, new_torrent = new_torrent) + return render_template("index.html", titles=sections, new_torrent=new_torrent) + # First stage @app.route("/add") def add_route(): config = initiate_config() - if request.args.get('query'): - torrent = config.toloka.get_torrent(request.args.get('query')) - return render_template('add.html', torrent = torrent, episode_integers = [i for i in ''.join((ch if ch.isdigit() else ' ') for ch in f"{torrent.files[0].folder_name}/{torrent.files[0].file_name}").split()], default_dir = config.app_config.get("Toloka", "default_download_dir")) - + if request.args.get("query"): + torrent = config.toloka.get_torrent(request.args.get("query")) + return render_template( + "add.html", + torrent=torrent, + episode_integers=[ + i + for i in "".join( + (ch if ch.isdigit() else " ") + for ch in f"{torrent.files[0].folder_name}/{torrent.files[0].file_name}" + ).split() + ], + default_dir=config.app_config.get("Toloka", "default_download_dir"), + ) + if len(request.args) == 6: requestData = RequestData( - url = request.args["toloka_url"], - season = request.args["season-index"], - index = int(request.args["episode-index"]), - correction = int(request.args['adjusted-episode-number']), - title = request.args["dirname"], + url=request.args["toloka_url"], + season=request.args["season-index"], + index=int(request.args["episode-index"]), + correction=int(request.args["adjusted-episode-number"]), + title=request.args["dirname"], ) config.args = requestData operation_result = add_release_by_url(config) output = serialize_operation_result(operation_result) - return redirect(url_for('root_route')) + return redirect(url_for("root_route")) + + return render_template("add.html") - return render_template('add.html') @app.route("/about") def about_route(): - return render_template('about.html') + return render_template("about.html") + @app.route("/settings") def settings_route(): - return render_template('settings.html') + return render_template("settings.html") + @app.route("/delete/") def delete_route(codename): @@ -99,15 +130,14 @@ def delete_route(codename): return f"{codename} успішно видалений." -@app.route("/update/", defaults={'codename': None}) + +@app.route("/update/", defaults={"codename": None}) @app.route("/update/") def update_route(codename): # Process the name to update release try: config = initiate_config() - requestData = RequestData( - codename = codename - ) + requestData = RequestData(codename=codename) if codename: config.args = requestData operation_result = update_release_by_name(config) @@ -118,5 +148,5 @@ def update_route(codename): output = serialize_operation_result(operation_result) return output except Exception as e: - message = f'Error: {str(e)}' + message = f"Error: {str(e)}" return {"error": message} diff --git a/app/models/db.py b/app/models/db.py index 1e230e0..87eafa7 100644 --- a/app/models/db.py +++ b/app/models/db.py @@ -1,8 +1,9 @@ from app import db from sqlalchemy.orm import Mapped, mapped_column + class ImagesCache(db.Model): __tablename__ = "image_cache" codename: Mapped[str] = mapped_column(primary_key=True) - image: Mapped[str] = mapped_column() \ No newline at end of file + image: Mapped[str] = mapped_column() diff --git a/app/models/request_data.py b/app/models/request_data.py index 17d8aae..0d7f0a5 100644 --- a/app/models/request_data.py +++ b/app/models/request_data.py @@ -6,11 +6,21 @@ class RequestData: title: str = "" codename: str = "" force: bool = False - def __init__(self, url = "", season = 0, index = 0, correction = 0, title = "", codename = "", force=False): + + def __init__( + self, + url="", + season=0, + index=0, + correction=0, + title="", + codename="", + force=False, + ): self.url = url self.season = season self.index = index self.correction = correction self.title = title self.codename = codename - self.force = force \ No newline at end of file + self.force = force diff --git a/app/services/torrents.py b/app/services/torrents.py index dbe9141..521f6de 100644 --- a/app/services/torrents.py +++ b/app/services/torrents.py @@ -3,36 +3,58 @@ from toloka2MediaServer.logger_setup import setup_logging from toloka2MediaServer.models.config import Config from toloka2MediaServer.clients.dynamic import dynamic_client_init -def initiate_config(): - app_config_path='data/app.ini' - title_config_path='data/titles.ini' - logger_path = 'data/app_web.log' - app_config, titles_config, application_config = load_configurations(app_config_path,title_config_path) - toloka=get_toloka_client(application_config) - logger=setup_logging(logger_path) +def initiate_config(): + app_config_path = "data/app.ini" + title_config_path = "data/titles.ini" + logger_path = "data/app_web.log" + + app_config, titles_config, application_config = load_configurations( + app_config_path, title_config_path + ) + toloka = get_toloka_client(application_config) + logger = setup_logging(logger_path) config = Config( logger=logger, toloka=toloka, app_config=app_config, titles_config=titles_config, - application_config=application_config + application_config=application_config, ) client = dynamic_client_init(config) config.client = client - + return config + def serialize_operation_result(operation_result): return { - "operation_type": operation_result.operation_type.name if operation_result.operation_type else None, - "torrent_references": [str(torrent) for torrent in operation_result.torrent_references], - "titles_references": [str(titles) for titles in operation_result.titles_references], + "operation_type": ( + operation_result.operation_type.name + if operation_result.operation_type + else None + ), + "torrent_references": [ + str(torrent) for torrent in operation_result.torrent_references + ], + "titles_references": [ + str(titles) for titles in operation_result.titles_references + ], "status_message": operation_result.status_message, - "response_code": operation_result.response_code.name if operation_result.response_code else None, + "response_code": ( + operation_result.response_code.name + if operation_result.response_code + else None + ), "operation_logs": operation_result.operation_logs, - "start_time": operation_result.start_time.isoformat() if operation_result.start_time else None, - "end_time": operation_result.end_time.isoformat() if operation_result.end_time else None - } \ No newline at end of file + "start_time": ( + operation_result.start_time.isoformat() + if operation_result.start_time + else None + ), + "end_time": ( + operation_result.end_time.isoformat() if operation_result.end_time else None + ), + } diff --git a/requirements.txt b/requirements.txt index 50ba7db..b47c053 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,6 +2,7 @@ git+https://github.com/CakesTwix/toloka2python git+https://github.com/CakesTwix/Toloka2MediaServer Flask Flask-SQLAlchemy +Flask-Caching SQLAlchemy requests configparser