首页 > 解决方案 > 将 Celery 与烧瓶路线一起使用

问题描述

我正在使用 gunicorn 对并行客户端请求进行多处理,并且我想提高我的应用程序的性能。如果直接应用在 api 路由上,celery 是否效果很好,或者它对后台任务更有用。并与我核实我对 celery 的调用是否正确:

from celery import Celery


def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config["CELERY_BACKEND_URL"],
        broker=app.config["CELERY_BROKER_URL"],
    )
    celery.conf.update(app.config)

    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)

    celery.Task = ContextTask
    return celery

# We use the Flask framework to create an instance of the flask app
# We then update our broker and backend URLs with the env variables
app = Flask(__name__)
app.config.update(
    CELERY_BROKER_URL=os.environ.get("CELERY_BROKER_URL"),
    CELERY_BACKEND_URL=os.environ.get("CELERY_BACKEND_URL"),
)
# create an instance of celery using the function created earlier


cel_app = make_celery(app)

谢谢

标签: python-3.xflaskredisrabbitmqcelery

解决方案


推荐阅读