Created
October 12, 2016 17:29
-
-
Save geoffreybauduin/f5fa6e4924739897d9505f14edc5a190 to your computer and use it in GitHub Desktop.
Flask and Celery with __call__ or run
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
amqp==1.4.9 | |
anyjson==0.3.3 | |
billiard==3.3.0.23 | |
celery==3.1.24 | |
click==6.6 | |
Flask==0.11.1 | |
itsdangerous==0.24 | |
Jinja2==2.8 | |
kombu==3.0.37 | |
MarkupSafe==0.23 | |
pytz==2016.7 | |
Werkzeug==0.11.11 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, Response | |
from celery import Celery | |
import celery | |
def make_celery(app): | |
celery = Celery(app.import_name, broker="memory://localhost/") | |
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 | |
class NewContextTask(celery.Task): | |
abstract = True | |
def __call__(self, *args, **kwargs): | |
with app.app_context(): | |
return self.run(*args, **kwargs) | |
app = Flask(__name__) | |
app.config.update({ | |
'CELERY_ALWAYS_EAGER': True, | |
'DEBUG': True, | |
}) | |
cel = make_celery(app) | |
@cel.task(bind=True) | |
def _celery_task(self, *args, **kwargs): | |
print("Current context: {}".format(self.request)) | |
@cel.task(bind=True, base=NewContextTask) | |
def _new_celery_task(self, *args, **kwargs): | |
print("Current context: {}".format(self.request)) | |
@app.route("/task") | |
def task(): | |
_celery_task.apply_async() | |
return Response() | |
@app.route("/new_task") | |
def new_task(): | |
_new_celery_task.apply_async() | |
return Response() | |
app.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Console output: