1

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

@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?

1
  • A celery task has no request and/or user. You run this, for example every day, so what would the user be? So it makes not much sense to access a user/request. Commented Sep 26, 2023 at 7:14

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Okay I understand,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.