import uuid from flask import Blueprint, render_template, request from sqlalchemy import delete from app.extensions import db from app.models.collection import Collection from app.models.task import Task from app.models.session import Session from .tasks import parse_users_task, send_messages_task, add_to_group_task tasks = Blueprint("tasks", __name__, url_prefix="/tasks", template_folder="templates") @tasks.route("/", methods=["GET"]) def get_tasks(): tasks = Task.query.all() sessions = Session.query.filter_by(authorized=True).all() return render_template("tasks_cards.j2", tasks=tasks, sessions=sessions) @tasks.route("/session/", methods=["POST"]) def create_task(session_id: int): info = request.form collection_id = int(info['collection']) collection = Collection.query.get_or_404(collection_id) session = Session.query.get_or_404(session_id) types = list(filter(lambda item: item in ('parse', 'add', 'message'), info.keys())) if len(types) <= 0: return "", 204 type = types[0] task = Task( name = info.get('task_name') or str(uuid.uuid4()), session = session, collection = collection, status = "CREATED", status_message = "Задача создана", type = type, url = info.get('parse') or info.get('add'), message = info.get('message'), file = None ) db.session.add(task) db.session.commit() start_task(task.id) return '', 204 @tasks.route("/", methods=["DELETE"]) def delete_task(task_id: int): task: Task = Task.query.get_or_404(task_id) stop_task(task.id) db.session.delete(task) db.session.commit() return '', 204 @tasks.route("//stop", methods=["PUT"]) def stop_task(task_id: int): task = Task.query.get_or_404(task_id) fn = None match task.type: case 'message': fn = send_messages_task case 'add': fn = add_to_group_task if task.task_id and fn: task_fn = fn.AsyncResult(task.task_id) task_fn.abort() task.status = "STOPING" task.status_message = "Задача останавливается" db.session.commit() return '', 204 @tasks.route("//start", methods=["PUT"]) def start_task(task_id: int): task: Task = Task.query.get_or_404(task_id) match task.type: case 'message': send_messages_task.delay(task_id=task_id) case 'add': add_to_group_task.delay(task_id=task_id) case 'parse': parse_users_task.run(task_id=task_id) delete_task(task_id) return '', 204 @tasks.route("//change", methods=["PUT"]) def change_settings(task_id: int): task: Task = Task.query.get_or_404(task_id) data = request.form if data.get("session"): task.session = Session.query.get(data.get("session")) if data.get("name"): task.name = data.get("name") db.session.commit() return '', 204