From fc21e7cfc2bd4c81a8fb6ba6fd932e111e77ac39 Mon Sep 17 00:00:00 2001 From: Adriaan Mulder Date: Wed, 9 Aug 2017 19:35:58 -0700 Subject: [PATCH] WIP add celery. --- app/__init__.py | 29 +++++++++++++++++++++++++++++ requirements.txt | 1 + 2 files changed, 30 insertions(+) diff --git a/app/__init__.py b/app/__init__.py index e23dc42..f968589 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -2,6 +2,7 @@ import logging from flask import Flask, request +from celery import Celery import config @@ -11,9 +12,12 @@ def create_app(): app.config.from_object(config) setup_logging(app) + celery = setup_celery(app) + load_models(app) load_extensions(app) load_blueprints(app) + load_tasks(celery) return app @@ -58,6 +62,25 @@ def log_response(response): return response +def setup_celery(app): + celery = Celery( + app.import_name, + backend=app.config['CELERY_RESULT_BACKEND'], + broker=app.config['CELERY_BROKER_URL']) + celery.conf.update(app.config) + TaskBase = celery.Task + + class ContextTask(TaskBase): + abstract = True + + def __call__(self, *args, **kwargs): + with app.app_context(): + return TaskBase.__call__(self, *args, **kwargs) + + celery.Task = ContextTask + return celery + + def load_extensions(app): """ Dynamicaly load "extensions" specified in the `EXTENSIONS` config tuple. @@ -120,3 +143,9 @@ def load_blueprints(app): view = importlib.import_module('app.views.{0}'.format(name)) app.register_blueprint(view.bp, **kwargs) + + +def load_tasks(celery): + tasks.celery = celery + for task in config.TASKS: + importlib.import_module('app.tasks.{0}'.format(task)) diff --git a/requirements.txt b/requirements.txt index 53e5429..bd767e9 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ flask-mongoengine flask-wtf gunicorn boto3 +celery