Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access request or request.user in celery task

I am trying to access request.user in django celery task function but it is unable to access as the function is not accepting any request instance, so How can I access it?

@shared_task
def run_everyday():
     return 0

I have configured that celery function in settings.py to run every day like

CELERY_BEAT_SCHEDULE = {
    "run_day": {
        "task": "blog.tasks.run_everyday",
        "schedule": crontab(hour=10, minute=5),
    },
}

I tried by defining another function to return request as result but another function needs to pass the request already like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@shared_task
def run_everyday():
     user = get_request_user()

     return 0

def get_request_user(request):
     return request.user

It shows

request is not defined

so How exactly can I access it? Do I need to created a middleware to get the request.user in celery task view? If yes, will that be efficient?

>Solution :

so How exactly can I access it?

You don’t: it makes no sense. Celery triggers a function, but there is no HTTP request involved, nor a logged in user. What would that user be? Celery just triggers a function at certain timestamps.

This is not how a view is accessed when you view a page. In that case the browser sends a HTTP request, and Django pre-processes the HTTP request, for example by looking at the session cookie and then sets a user on that request.

But that does not hold when you run a function, just when some time has been elapsed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading