PaperParser/app/blueprints/api/tasks/routes.py

104 lines
2.6 KiB
Python

import uuid
from flask import Blueprint, render_template, request
from app.extensions import db
from app.models.task import Task
from app.models.session import Session
from .tasks import 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.all()
return render_template("tasks_cards.j2", tasks=tasks, sessions=sessions)
@tasks.route("/<int:task_id>", methods=["GET"])
def get_task(task_id: int):
...
@tasks.route("/session/<int:session_id>", methods=["POST"])
def create_task(session_id: int):
info = request.form
session = Session.query.get_or_404(session_id)
task = Task(
name = str(uuid.uuid4()),
session = session,
status = "CREATED",
status_message = "Задача создана",
type = info.get('task'),
url = info.get('url'),
message = info.get('message'),
file = None
)
db.session.add(task)
db.session.commit()
start_task(task.id)
return 'Created', 200
@tasks.route("/<int:task_id>", 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 'Deleted', 200
@tasks.route("/<int:task_id>/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 'Stoping', 200
@tasks.route("/<int:task_id>/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)
return 'Started', 200
@tasks.route("/<int:task_id>/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 'Changed', 200