How to make any method from view/model as celery task
<p>I have some of the analytics methods in <code>models.py</code> under <code>class Analytics</code> (e.g: <code>Analytics.record_read_analytics()</code>). And we are calling those methods for recording analytics, which doesn't need to be synchronous. Currently it's affecting rendering of each request so decided to add these methods in celery queue. We are already using celery for some of our tasks hence we have <code>tasks.py</code> and <code>celery.py</code> file.</p>

<p><strong>Following is section of <code>models.py</code> file:</strong></p>

<pre><code>class Analytics():
    ...
    ...

    @staticmethod
    def method_a():
        ...
        ...


    def method_b():
        ...
        ...

    @staticmethod
    def record_read_analytics():
        ...
        ...
</code></pre>

<p>I don't wanted to write again same model level class methods in <code>tasks.py</code> and wanted to make some of view method's and model level class methods as celery task.</p>

<p><strong>Following is <code>celery.py</code> file:</strong></p>

<pre><code>from __future__ import absolute_import
from celery import Celery

app = Celery('gnowsys_ndf',
             include=['gnowsys_ndf.tasks'])

app.config_from_object('gnowsys_ndf.celeryconfig')

if __name__ == '__main__':
    app.start()
</code></pre>

<p>I'm new to <code>celery</code> and looking for help. Thank you in advance.</p>

<p>You can create tasks out of <a href="http://docs.celeryproject.org/en/latest/reference/celery.contrib.methods.html" rel="nofollow">methods</a>. The bad thing about this is that the object itself gets passed around (because the state of the object in worker has to be same as the state of the caller) in order for it to be called, so you lose some flexibility. So your object has to be pickled every time, which is why I am against this solution. <strong>Of course this concerns only class methods, static methods have no such problem.</strong></p>

<p>Another solution, which I like, is to create separate tasks.py or class based tasks and call the methods from within them. This way, you will have FULL control over Analytics object within your worker.</p>

python django celery django-celery