How Can I Setup Celery in my Flask Project

So I've been working on a project for a couple months now and I've been trying to implement Celery into my flask project and it has not gone well. I thought maybe it's my computer or windows or something like, and all the responses I've seen are from a couple years ago and I don't think that they would still work because those were the ones I tried using. So thank you for any responses in advance.

I tried using the celery config from the documentation and some chat gpt tutorials but they haven't been of help. And I'm running redis on the localhost

To set up Celery in your Flask project with Redis as the message broker, follow these steps:

1. Install Required Packages
First, install Flask, Celery, and Redis using pip:

bash
Copy code
pip install Flask Celery redis
2. Create Your Flask App
Create a basic Flask app and configure Celery. Here’s an example:

python
Copy code
# app.py
from flask import Flask
from celery import Celery

app = Flask(__name__)

# Configuration for Celery
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'  # Redis as a broker
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

# Initialize Celery
def make_celery(app):
    celery = Celery(
        app.import_name,
        broker=app.config['CELERY_BROKER_URL'],
        backend=app.config['CELERY_RESULT_BACKEND']
    )
    celery.conf.update(app.config)
    return celery

celery = make_celery(app)

# Define a background task
@celery.task
def long_task(n):
    import time
    time.sleep(n)
    return f"Task completed after {n} seconds!"

@app.route('/start-task/<int:n>')
def start_task(n):
    task = long_task.delay(n)
    return f"Task started: {task.id}"

if __name__ == '__main__':
    app.run(debug=True)
3. Set Up Redis
Make sure Redis is running on your machine or server. You can start it using the following command:

bash
Copy code
redis-server
4. Run Celery Worker
In a separate terminal, navigate to your project directory and run the Celery worker:

bash
Copy code
celery -A app.celery worker --loglevel=info
5. Run the Flask App
Run your Flask app using the following command:

bash
Copy code
python app.py
6. Test the Celery Task
Visit http://localhost:5000/start-task/5 in your browser. This will start a task that sleeps for 5 seconds before completing. You can check the status of tasks in the Celery worker logs.

This setup uses Redis as the broker and result backend, and the task execution is handled in the background by Celery. You can easily customize it based on your needs, such as by adding more tasks or configuring different broker/result backends.

If you continue to face issues, double-check the versions of Celery, Redis, and Flask, as compatibility problems can arise from outdated libraries.
Вернуться на верх