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