所以我已经在一个项目上工作了几个月了,我一直在尝试将 Celery 实现到我的 Flask 项目中,但进展并不顺利。我想也许是我的电脑或窗户之类的东西,我看到的所有回复都是几年前的,我不认为它们仍然有效,因为那些是我尝试使用的。 所以感谢您提前回复。
我尝试使用文档和一些聊天 gpt 教程中的 celery 配置,但它们没有帮助。我在本地主机上运行 redis
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.