I have a project using a FastAPI python backend with SQLAlchemy using SQLite and…
- User
I have a project using a FastAPI python backend with SQLAlchemy using SQLite and Pydantic, and a REACT frontend using antd. What I want to be able to do, is track all background tasks, if I could give some kind of ID or some kind of way to track to see what tasks are running, potentially see when it started, it's state(this could be dependant on the task itself, some kind of state variable passed by the FastAPI background task, could potentially even show the progress and estimated time remaining), and also see when a task finished, so it needs to keep a history of tasks as well. One example of how I am starting a background task currently from an endpoint:
@router.post("/images/add-folder/") def addfolder_image_endpoint(path: str, background_tasks: BackgroundTasks): try: # Add background task to run the cleanup after sending the response background_tasks.add_task(add_folder_images_task, path) return {"message": f"Starting add folder images task on {path}"} except Exception as e: raise HTTPException(status_code=500, detail=f"Unable to initiate add folder images task: {str(e)}")I basically want to create a new endpoint router .py file that can query the background tasks, schedule tasks, queue tasks, see completed tasks and the results etc, also, we could use the SQLAlchemy crud/models to store the task information, and task states, so we could maybe even let tasks pause and resume, I also want to be able to control this from the REACT frontend, however, right now just focus on the FastAPI side for now, keeping control endpoints in mind for when we do the REACT side. Let's make sure we get this done right, in a step-by-step way, to create a flexible background task management system.
- Assistant
- User
I would like to implement a more OOP approach, I created a new utility file, utils\task.py:
from fastapi import BackgroundTasks from enum import Enum as PyEnum import datetime from database.models.tasks import BackgroundTaskModel from database.crud import tasks as crud class TaskStatus(PyEnum): PENDING = "pending" RUNNING = "running" PAUSED = "paused" FINISHED = "finished" FAILED = "failed" class Task: name: str status: TaskStatus start: datetime end: datetime def __init__(self) -> None: pass def start(self): pass def pause(self): pass def stop(self): pass def pre(self): raise Exception("Derived classes should overwrite this method.") def run(self): raise Exception("Derived classes should overwrite this method.") def post(self): raise Exception("Derived classes should overwrite this method.") def __repr__(self) -> str: passThis is just to skeleton out some functionality, I still need a way to register Task within the FastAPI application to allow accessing all current tasks, the obvious solution is to use the database to store and retrieve tasks, however we still need a way to access these Task objects, and I would like these Task objects to not only contain the task code itself(using the pre/run/post methods on derived classes), but to manage DB interactions through the model and using the crud functions. This will basically serve as the gateway to all tasks within the FastAPI application, and the task endpoints will utilize this to create/start/pause/stop and get the tasks.
- Assistant
- User
You need to implement the crud functions
- Assistant
- User
Ok, seems I might want more control over the background tasks than the FastAPI BackgroundTasks gives me, I want a simple OOP system, where I can store the tasks in the DB like before, with task state, TaskStatus, task results, start time, stop time, run time, I also when the capability to pause tasks, stop them manually, or, on program restart, restart activate tasks, this also means the task manager needs to maintain the state in memory but also in the database, which means loading tasks from the database on startup etc. Please do it in a detailed step-by-step way.
- Assistant
- User
What is the import abc?
- Assistant
The
abcmodule in Python stands for "Abstract Base Classes". It provides a framework for defining abstract base classes, which are classes that serve as blueprints for other classes without implementing some or all methods themselves. These abstract methods are intended to be overridden in concrete subclasses.When you import
abc, you typically use it to create an abstract class using theABCclass and theabstractmethoddecorator provided by this module:from abc import ABC, abstractmethod class AbstractClass(ABC): @abstractmethod def abstract_method(self): passIn this example,
AbstractClassis an abstract base class that cannot be instantiated on its own. It requires subclasses to provide an implementation for the . - User
Ok, what is involved in using Celery or RQ?
- Assistant
- User
You mention using the commandline, can I not just launch them from within FastAPI?
- Assistant
- User
How does it even function, outside of all my code that has all the logic?
- Assistant
- User
Ok, but I don't understand why I would use command-line to start workers? I get a FastAPI endpoint request, the task is to scan through a large folder with thousands of images, clearly, I want the endpoint to return immediately, but spin up a task to run in the background...I get that it is a separate process, and it is sent across using a "message broker", but it seems really counter intuitive to me to entirely isolate this background task, which needs access to the same database, the same objects etc. But how does command-line come in to this?
- Assistant
- User
Yeah, I think the issue is I am not building a website, I am building a webui app, designed to run locally on your computer, rather than on a webserver somewhere, spinning off extra processes is kind of a hassle, it is already bad enough to have a FastAPI server and a REACT server, this is why I am using SQLite over other database systems, and eventually the plan is REACT will be built and then served by the FastAPI server directly. Having tasks running in separate processes is fine, as long as they are automatically spun off and controlled by the FastAPI server. All this web stuff is really getting in the way of productivity for me, it would be so much easier if it could all be done in python(Using this because of the deep learning community appears to have chosen python as their primary language for development)
- Assistant