Flask项目中Celery的使用
一、项目目录结构
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/14d19afb21ff68f891d026ab3e1216e8.jpeg)
二、celery_config.py
- 在config中新增文件celery_config.py
from .redis_config import REDIS_HOST, REDIS_PORT, REDIS_PASSWORD
BROKER_URL = 'redis://:{}@{}:{}/1'.format(REDIS_PASSWORD, REDIS_HOST, REDIS_PORT)
RESULT_BACKEND = 'redis://:{}@{}:{}/2'.format(REDIS_PASSWORD, REDIS_HOST, REDIS_PORT)
TASK_SERIALIZER = 'json'
RESULT_SERIALIZER = 'json'
ACCEPT_CONTENT = ['json']
TIMEZONE = 'Asia/Shanghai'
ENABLE_UTC = True
三、task.py
-*- coding: utf8 -*-
import time
from celery import Celery
from flask import Flask
from config import celery_config
"""
新初始化一个Flask,否则会造成循环引用。
名字一定不能与app.py中的Flask应用重名
例如app.py中的Flask应用的名称为app,tasks.py文件中的Flask应用名称为application
"""
application = Flask(__name__)
application.config.from_object(celery_config)
def make_celery(app):
celery_server = Celery(app.import_name, backend=app.config['RESULT_BACKEND'],
broker=app.config['BROKER_URL'])
celery_server.conf.update(app.config)
task_base = celery_server.Task
class ContextTask(task_base):
abstract = True
def __call__(self, *args, **kwargs):
with app.app_context():
return task_base.__call__(self, *args, **kwargs)
celery_server.Task = ContextTask
return celery_server
celery = make_celery(application)
@celery.task
def add(x, y):
time.sleep(10)
return x + y
四、在蓝图中使用
@user_semantic_analysis.route('/hello/celery', methods=['GET', 'POST'])
def hello_celery():
add.delay(1, 5320)
return 'hello celery'
五、启动celery服务
celery -A tasks worker -l info -P eventlet -c 10
- celery成功调用
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0e284aaf2345f9d280b39a88f3187abc.jpeg)