Skip to content

Instantly share code, notes, and snippets.

@geoffreybauduin
Created October 12, 2016 17:29
Show Gist options
  • Save geoffreybauduin/f5fa6e4924739897d9505f14edc5a190 to your computer and use it in GitHub Desktop.
Save geoffreybauduin/f5fa6e4924739897d9505f14edc5a190 to your computer and use it in GitHub Desktop.
Flask and Celery with __call__ or run
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
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()
@geoffreybauduin
Copy link
Author

Console output:

(venv) > python run.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger pin code: 107-501-531
Current context: <Context: {}>
127.0.0.1 - - [12/Oct/2016 19:28:30] "GET /task HTTP/1.1" 200 -
Current context: <Context: {'called_directly': False, 'delivery_info': {'is_eager': True}, 'id': '8d6c3c25-e2c8-4b2e-a39e-736dbf4f973a', 'loglevel': 0, 'kwargs': {}, 'is_eager': True, 'headers': None, 'callbacks': None, 'errbacks': None, 'retries': 0, 'logfile': None, 'args': ()}>
127.0.0.1 - - [12/Oct/2016 19:28:34] "GET /new_task HTTP/1.1" 200 -
^C%  

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment