<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Decorator on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/decorator/</link>
    <description>Recent content in Decorator on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Wed, 10 Oct 2012 20:58:02 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/decorator/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Python Celery Asynchronous Task Decorator</title>
      <link>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</link>
      <pubDate>Wed, 10 Oct 2012 20:58:02 +0000</pubDate>
      <guid>https://mpcabd.xyz/python-celery-asynchronous-task-decorator/</guid>
      <description>&lt;p&gt;A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.&lt;/p&gt;
&lt;p&gt;Executing asynchronous tasks in Python can be made in multiple ways, one of them is using &lt;a href=&#34;http://celeryproject.org/&#34; title=&#34;Celery: Distributed Task Queue&#34; target=&#34;_blank&#34;&gt;celery&lt;/a&gt;, a distributed task queue written in Python which has proved itself to be a great solid task queue system.&lt;/p&gt;
&lt;p&gt;And if you’re using Django then there is a Django app to make your life easier, &lt;a href=&#34;https://github.com/celery/django-celery/&#34; title=&#34;Celery integration for Django&#34; target=&#34;_blank&#34;&gt;django-celery&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>A while ago I was working on a project in Django that had many tasks that needed to be executed asynchronously such as sending emails, generating reports, and checking some database related issues.</p>
<p>Executing asynchronous tasks in Python can be made in multiple ways, one of them is using <a href="http://celeryproject.org/" title="Celery: Distributed Task Queue" target="_blank">celery</a>, a distributed task queue written in Python which has proved itself to be a great solid task queue system.</p>
<p>And if you’re using Django then there is a Django app to make your life easier, <a href="https://github.com/celery/django-celery/" title="Celery integration for Django" target="_blank">django-celery</a>.</p>
<p>Now as always I like to make my own life easier also by implementing generic solutions for my needs, so I have written this simple piece of code to create a function decorator that declares the function as an asynchronous task, which means that by just adding this decorator to the function it becomes asynchronous.</p>
<p>So let’s get started!</p>
<figure class="auto center">
    <img loading="lazy" src="/wp-content/uploads/2012/10/celery-python.png"/> 
</figure>

<h3 id="description">Description</h3>
<p>The following code will allow you to decorate Python functions with a decorator that will allow them to be executed asynchronously in a seamless easy way. You don’t have to change any thing in your code, just add the <code>asynchronous_task</code> decorator to the functions you want them to be executed asynchronously and you’re done.</p>
<p>This code can be used with Django also, just uncomment the Django block in it and it’ll work.</p>
<p>I wrote this code in a file called <code>celery_tasks.py</code> which probably the place you’ll have your all celery tasks, it adds a task called <code>execute</code> that is responsible for executing the passed function and parameters.</p>
<pre class="lang:python decode:true">import os, sys
from celery.task import task

sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, os.path.dirname(__file__))

##########################
# Uncomment the following code block to enable it to work with Django.
# Either put this file next to the settings.py file, or change the block code to import your settings module from the correct path.
##########################

#from django.core.management import setup_environ
#import settings
#setup_environ(settings)

@task(name='execute')
def execute(module_name, method_name, *args, **kwargs):
	try:
		m = __import__(module_name)
		if m.__name__ != module_name:
			modules = module_name.split('.')[1:]
			for module in modules:
				m = getattr(m, module)
		f = getattr(m, method_name)
		if hasattr(f, 'func'):
			f = f.func
		return f(*args, **kwargs)
	except Exception, e:
		raise e
</pre>
<p>The code looks like a mess I know, but simply what it does is that you pass this task the following parameters:</p>
<ol>
<li>Python module name to get the function from</li>
<li>Method name to be executed</li>
<li>Positional and named parameters</li>
</ol>
<p>The second part is defining the decorator, lets assume that this file is called <code>celery_decorator.py</code>:</p>
<p><strong>Note that I’m assuming that <code>celery_decorator.py</code> is in the same folder of your <code>celery_tasks.py</code> file.</strong></p>
<pre class="lang:python decode:true">from django.utils.decorators import available_attrs
from django.utils.functional import wraps

def asynchronous_task(check_if_active = False):
	def wrapper(f):
		try:
			@wraps(f, assigned=available_attrs(f))
			def _wrapper(*args, **kwargs):
				try:
					if check_if_active:
						from celery.task.control import inspect
						insp = inspect()
						d = insp.active()
						if not d:
							raise Exception
					from celery_tasks import execute
					execute.delay(f.__module__, f.func_name, *args, **kwargs)
				except Exception as e:
					f(*args, **kwargs)
			_wrapper.func = f
			return _wrapper
		except Exception:
			return f
	return wrapper
</pre>
<p>This decorator simply wraps the function in a call to the <code>execute</code> task on celery, so that it’ll be executed asynchronously, it accept an optional parameter that defines whether the decorator should check if celery is running and if it’s not then execute the function synchronously, it is set to <code>False</code> by default because it takes some time to check celery, so it makes the performance poor a little bit.</p>
<p>Now we can us it on any function inside our code:</p>
<pre class="lang:python decode:true">from celery_decorator import asynchronous_task

#Default not to check if celery is running
@asynchronous_task
def a_very_long_process(p1, p2):
    pass #TODO: Do something

#Force check
@asynchronous_task(check_if_active = True)
def another_very_long_process(p1, p2):
    pass #TODO: Do something
</pre>
<p>Now in your code you just simply don’t change anything, all the calls to these two functions will be asynchronous calls.</p>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download a copy of <code>celery_tasks.py</code> and <code>celery_decorators.py</code> from this Gist: <a href="https://gist.github.com/3874979">https://gist.github.com/3874979</a></p>
<p>Hope this helps somebody to perform faster 🙂</p>]]></content:encoded>
    </item>
  </channel>
</rss>
