Django. Celery delay() not printing to terminal - django

I have a simple Celery task in Django:
from celery.decorators import task
#task
def celery_test(x, y):
print x + y
return None
I call it in a view:
...
def get_queryset(self, *args, **kwargs):
celery_test.delay("uno ", "dos")
...
So, when I call the function with delay it doesn't print anything to the terminal, why?, ... when I call it whithout delay it prints things correctly. I'm using RabbitMQ server and it is running fine.

Check your log file for celery. It'll probably print it there.
EDIT
When you use .delay() the task is decoupled from the terminal and all you get printed is something like this:
AsyncResult: 3df665f1-547d-49bb-937b-8190a63bfeb7.
What happens is that you've passed the code to the broker and the broker can't print back to terminal. But if you have a print statements in your code they'll be printed into your celery log.

Related

How do I ensure a Django Channels message is sent immediately without delay?

The idea is to run a background task on the worker.connect worker. While executing the task, I would like to send its progress to a connected client via the notifications Group.
The problem: the messages sent to the notifications Group are delayed until the task on the worker is finished. So: both messages 'Start' and 'Stop' appear simultaneously on the client, after a delay of 5 seconds (sleep(5)). I would expect the message 'Start', followed by a 5sec delay, followed by the message 'Stop'. Any idea why this is not the case?
I have the following three processes running:
daphne tests.asgi:channel_layer
python manage.py runworker --exclude-channel=worker.connect
python manage.py runworker --only-channel=worker.connect
In views.py:
def run(request, pk):
Channel('worker.connect').send({'pk': pk})
return HttpResponse(status=200)
In consumers.py:
def ws_connect(message):
Group('notifications').add(message.reply_channel)
message.reply_channel.send({"accept": True})
def worker_connect(message):
run_channel(message)
In views.py:
def run_channel(message):
Group('notifications').send({'text': 'Start'})
sleep(5)
Group('notifications').send({'text': 'Stop'})
routing.py
channel_routing = {
'websocket.connect': consumers.ws_connect,
'worker.connect': consumers.worker_connect,
}
You can add immediately=True as argument to the send function. According to the source:
Sends are delayed until consumer completion. To override this, you may pass immediately=True.
https://github.com/django/channels/blob/master/channels/channel.py#L32

Celery group multiple tasks in one design

I just getting familiar with Celery and have a question. My setup is Django-Redis-Celery
Lets take an example of a task sending email:
TASKS
#task
def send_email(message):
mailserver.sendOneMessage(message)
VIEWS
class newaccount(APIView):
def post(self, request, format=None):
send_email.delay(request.data.email)
This works perfectly, Django sends messages to Redis and those are picked up by Celery then to execute task. But I want to improve the system so that Celery picks up all messages from Redis at certain intervals and executes a single task with multiple messages. This because, connecting to the email server is slow and sending multiple messages as a single request will result in a faster process.
I want something like this to work:
TASKS
#task
def send_emails(messages):
mailserver.sendMultipleMessages(messages)
Thoughts?
Since i am using redis as a cache (django-redis) already i implemented the following workflow:
Step 1. Create a task that adds new emails to cache
#shared_task()
def add_email(user_id):
cache.set("email#{}".format(user_id), None, timeout=None)
Step 2. Create a periodic task that runs every second and looks up for new emails in the cache
class ProcessEmailsTask(PeriodicTask):
run_every = timedelta(seconds=1)
def run(self, **kwargs):
call_email()
def call_email():
item_exists = True
ids = []
while item_exists:
try:
key = next(cache.iter_keys("email#*"))
ids.append(key.split("email#")[1])
cache.delete_pattern(key)
except:
item_exists = False
if len(ids) > 0:
send_emails_to(ids)
Step 3. Run both celery workers and celery beat and profit!

stop django command using sys.exit()

Hi I have a problem with the django commands the thing is I need to stop the command if some condition happen, normally in python script I do this using sys.exit() because I don't want the script still doing things I try this with Django and doesn't work there is another way to stop the command running ?
Health and good things.
from the docs:
from django.core.management.base import BaseCommand, CommandError
from polls.models import Poll
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
parser.add_argument('poll_id', nargs='+', type=int)
def handle(self, *args, **options):
for poll_id in options['poll_id']:
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise CommandError('Poll "%s" does not exist' % poll_id)
poll.opened = False
poll.save()
self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
i.e. you should raise a CommandError
though sys.exit generally ought to work fine too (I mean, you said it didn't for you - if it was me I'd be curious to work out why not anyway)
I am surprised to see these solutions, for neither of them works. Sys.exit() just finishes off the current thread and raising a 'CommandError' only starts exception handling. Nor does raising a KeyboardInterrupt have any effect. Perhaps these solutions once worked with earlier versions, or with the server started in a different context.
The one solution I came across here is _thread.interrupt_main(). It stops the server after neatly finishing the current request.

Logging request timeouts on Django + Gunicorn + Heroku

We have a Django app running Gunicorn with sync workers that's deployed on Heroku. Our request response time shows several requests that hit 30s (and die), which is the default Gunicorn timeout.
What is the best way to log these requests and analyze the timeout? Gunicorn doesn't seem to provide a hook for catching these timeouts, at least not something that's obvious.
One rather rough way to do it is have a "watchdog" timer that interrupts the process after, say, 25 seconds. Once you have an idea of which procs are slow, you can refine the data to figure out what's going on.
Example:
import signal
def timeout(_signum, _frame):
print 'TIMEOUT'
signal.signal(signal.SIGALRM, timeout)
signal.alarm(1) # send SIGALRM in 1 second
print 'waiting'
signal.pause()
print 'done'
Another approach is to fire off a Thread which pokes the main code after a certain amount of elapsed time. It has several caveats -- be sure to read the ActiveState link.
Here's one implementation by Aaron Swartz from ActiveState.com
import threading
class TimeoutError(Exception): pass
def timelimit(timeout):
def internal(function):
def internal2(*args, **kw):
class Calculator(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.result = None
self.error = None
def run(self):
try:
self.result = function(*args, **kw)
except:
self.error = sys.exc_info()[0]
c = Calculator()
c.start()
c.join(timeout)
if c.isAlive():
raise TimeoutError
if c.error:
raise c.error
return c.result
return internal2
return internal
https://github.com/benoitc/gunicorn/pull/768/files added a worker_abort signal which is what I'm using in this case.

Django celery task keep global state

I am currently developing a Django application based on django-tenants-schema. You don't need to look into the actual code of the module, but the idea is that it has a global setting for the current database connection defining which schema to use for the application tenant, e.g.
tenant = tenants_schema.get_tenant()
And for setting
tenants_schema.set_tenant(xxx)
For some of the tasks I would like them to remember the current global tenant selected during the instantiation, e.g. in theory:
class AbstractTask(Task):
'''
Run this method before returning the task future
'''
def before_submit(self):
self.run_args['tenant'] = tenants_schema.get_tenant()
'''
This method is run before related .run() task method
'''
def before_run(self):
tenants_schema.set_tenant(self.run_args['tenant'])
Is there an elegant way of doing it in celery?
Celery (as of 3.1) has signals you can hook into to do this. You can alter the kwargs that were passed in, and on the other side, undo your alterations before they're given to the actual task:
from celery import shared_task
from celery.signals import before_task_publish, task_prerun, task_postrun
from threading import local
current_tenant = local()
#before_task_publish.connect
def add_tenant_to_task(body=None, **unused):
body['kwargs']['tenant_middleware.tenant'] = getattr(current_tenant, 'id', None)
print 'sending tenant: {t}'.format(t=current_tenant.id)
#task_prerun.connect
def extract_tenant_from_task(kwargs=None, **unused):
tenant_id = kwargs.pop('tenant_middleware.tenant', None)
current_tenant.id = tenant_id
print 'current_tenant.id set to {t}'.format(t=tenant_id)
#task_postrun.connect
def cleanup_tenant(**kwargs):
current_tenant.id = None
print 'cleaned current_tenant.id'
#shared_task
def get_current_tenant():
# Here is where you would do work that relied on current_tenant.id being set.
import time
time.sleep(1)
return current_tenant.id
And if you run the task (not showing logging from the worker):
In [1]: current_tenant.id = 1234; ct = get_current_tenant.delay(); current_tenant.id = 5678; ct.get()
sending tenant: 1234
Out[1]: 1234
In [2]: current_tenant.id
Out[2]: 5678
The signals are not called if no message is sent (when you call the task function directly, without delay() or apply_async()). If you want to filter on the task name, it is available as body['task'] in the before_task_publish signal handler, and the task object itself is available in the task_prerun and task_postrun handlers.
I am a Celery newbie, so I can't really tell if this is the "blessed" way of doing "middleware"-type stuff in Celery, but I think it will work for me.
I'm not sure what you mean here, is before_submit executed before the task is called by a client?
In that case I would rather use a with statement here:
from contextlib import contextmanager
#contextmanager
def set_tenant_db(tenant):
prev_tenant = tenants_schema.get_tenant()
try:
tenants_scheme.set_tenant(tenant)
yield
finally:
tenants_schema.set_tenant(prev_tenant)
#app.task
def tenant_task(tenant=None):
with set_tenant_db(tenant):
do_actions_here()
tenant_task.delay(tenant=tenants_scheme.get_tenant())
You can of course create a base task that does this automatically,
you can apply the context in Task.__call__ for example, but I'm not sure
if that saves you much if you can just use the with statement explicitly.