Как настроить Celery в проекте Flask

Так что я работаю над проектом уже пару месяцев, и я пытался внедрить Celery в мой проект flask, и это не прошло успешно. Я подумал, что, возможно, дело в моем компьютере или windows, или что-то в этом роде, и все ответы, которые я видел, были пару лет назад, и я не думаю, что они все еще работают, потому что это были те, которые я пытался использовать. Так что заранее спасибо за любые ответы.

Я пытался использовать конфигурацию celery из документации и некоторые учебники по чату gpt, но они не помогли. И я запускаю redis на 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.
Вернуться на верх