FastAPI – Background tasks with Celery, Redis, and Flower #9

Posted by


FastAPI is a modern Python web framework that makes it easy to build APIs quickly and efficiently. In this tutorial, we will learn how to work with background tasks in FastAPI using Celery, Redis, and Flower.

Background tasks are handy for offloading time-consuming operations from your main application flow. By using a task queue like Celery and a message broker like Redis, we can easily manage and execute background tasks in FastAPI.

Here’s a step-by-step guide on how to set up background tasks in FastAPI using Celery, Redis, and Flower:

Step 1: Install the required packages

First, we need to install the necessary packages. You can install them using pip:

pip install fastapi[all] celery redis flower

Step 2: Create a Celery instance in your FastAPI app

Create a new Python file, such as celery_app.py, and define a Celery instance there:

from celery import Celery

celery = Celery("tasks", broker="redis://localhost:6379/0")

Step 3: Create a FastAPI app with Celery integration

In your main FastAPI app file, import the Celery instance from celery_app.py and integrate it:

from fastapi import FastAPI
from celery_app import celery

app = FastAPI()

@app.get("/run-task")
def run_background_task():
    task = celery.send_task('tasks.background_task')
    return {"task_id": task.id}

Step 4: Define a background task

Create a new Python file, such as tasks.py, and define a background task there using Celery decorators:

from celery import Celery

celery = Celery('tasks', broker='redis://localhost:6379/0')

@celery.task
def background_task():
    # Write your time-consuming task here
    return "Background task completed successfully"

Step 5: Run Celery worker

Start a Celery worker to process the background tasks:

celery -A tasks worker --loglevel=info

Step 6: Run FastAPI app with Flower

Run your FastAPI app and start the Flower web interface for monitoring the Celery tasks:

uvicorn main:app --reload
flower -A tasks --port=5555

Now you have successfully set up background tasks in FastAPI using Celery, Redis, and Flower. You can trigger the background task by accessing the /run-task endpoint in your FastAPI app and monitor the task execution in the Flower web interface.

This setup allows you to offload time-consuming operations to background tasks, making your FastAPI app more efficient and scalable. Have fun building awesome APIs with FastAPI and Celery!

0 0 votes
Article Rating

Leave a Reply

26 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@artemshumeiko
3 hours ago

💡 Попробуй онлайн-тренажёр для подготовки к техническому собеседованию: https://clck.ru/3B5gwP 💡

Забирай роадмап изучения самого востребованного фреймворка на Python – FastAPI здесь: https://t.me/ArtemShumeikoBot

@melordfilms
3 hours ago

Скорее к моменту прочтения вопроса уже найду ответ, но суть такая:
Flower видит и воркера, и брокера и письма отправляются, но страница с Тасками в Flower как была пустой, так и осталась
upd: такой кринж словить.. забыть .delay()

@orthodox-chanel
3 hours ago

Как хорошо что начал учить фастапи именно с этого канала, пробел по большинству вопросов уже закрыл)) Осталось разобраться с отправкой и сохранением файлов)

@БогданСокольников-т1н
3 hours ago

Привет, отличное видео!
Есть способ запустить celery через redis из docker контейнера.
Просто пропишите эту команду и redis будет работать при помощи docker :
docker run –rm -p 6379:6379 redis:7

@TheGorillav
3 hours ago

Так а что конкретно тут делает redis? Что-то не понял его функционала. Он за что отвечает?

@megalun_
3 hours ago

Супер. Но почему первый запрос был на 600 мс, а следующие на 20? И будет ли такое же поведение у BackgroundTask?

@dubrovvin5892
3 hours ago

Больше не друзья🥲

@kirillayvazov4813
3 hours ago

Спасибо!

@warflow
3 hours ago

интересная библиотека
даже своя панель управления есть

@awesomeex5821
3 hours ago

Отличный урок! Спасибо большое за твои труды)

@drillmaker5455
3 hours ago

лайк

@gayratsaidakhmedov5451
3 hours ago

спасибо

@berzerkmatters8003
3 hours ago

кто-то знает почему flower не видит результаты прошлых тасок при новом запуске? Код не менялся, просто перезапустил flower, но в админ-панели flower – пусто

@Miron_Nicolaevich
3 hours ago

Супер что о таких фишках говорят, но рассказано за 20 минут одна страницы документации. Я так понимаю это вводный курс, даже не базовый и наверное автор раскрывает по этапам в более широком разъяснении данные технологии.

@busipac1467
3 hours ago

Ошибка, когда ввожу данные(username, password) на 'auth/login' (macOS)
Сначала думал, что где-то я ошибся, потом сделал clone репы, и всё то же самое

AttributeError: module 'bcrypt' has no attribute '__about__'
version = bcrypt._about__.__version

@кударец
3 hours ago

Спасибо большое, что упомянул написать –pool=solo, а то второй день не понимал что не так

@patricross8683
3 hours ago

Спасибо за видео

@akimovvadim4736
3 hours ago

Чувак, спасибо тебе огромное за то что рассказал про этот параметр –pool=solo. Я бошку себе чуть не сломал разгадывая по чему у меня таски в винде создаются но не отрабатывают.

@chatgpktest123
3 hours ago

Не знаю почему, но моя задача которая у Вас get_email_template_dashboard – пишет что она не зарегистрирована, хотя в логах её я вижу. Ну и командой celery он её видет, а когда я делаю get запрос, то в логах celery пишет что такска не зарегистрирована

@ренанв
3 hours ago

Спасибо за видело. Интересно было бы посмотреть как селери на прод ставить, а именно процесс демонизации.

26
0
Would love your thoughts, please comment.x
()
x