I have a requirement where i want to show date time in user's local datetime. For which I have added a middleware code in django which gets the local date time from user's session through browser and activate that session.In my django settings.py I have added the timezone which is by default 'America/New york'
Now I have celery where the database operations are performed asynchronously. But in celery the timezone which I am activating in middleware is not getting through. It is always picking it up from django settings.py file.If i remove the default timezone setting then it is taking the timezone as 'America/Chicago'.
Below is my code for Middleware
# middleware.pyfrom django.utils import timezoneclass TimezoneMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_timezone = request.GET.get('user_timezone', 'America/New_York') request.session['user_timezone'] = user_timezone response = self.get_response(request) return response
And here is my code for celery task
# tasks.pyfrom celery import Celery, Taskfrom django.contrib.sessions.models import Sessionfrom django.utils import timezoneapp = Celery('yourapp', broker='pyamqp://guest@localhost//')class TimezoneAwareTask(Task): def __call__(self, *args, **kwargs): # Get user timezone from session or use a default user_timezone = self.get_user_timezone(kwargs.get('session_key')) # Set the timezone for the task execution timezone.activate(user_timezone) try: result = super(TimezoneAwareTask, self).__call__(*args, **kwargs) finally: timezone.deactivate() return result def get_user_timezone(self, session_key): try: session = Session.objects.get(session_key=session_key) return session.get_decoded().get('user_timezone', 'America/New_York') except Session.DoesNotExist: return 'America/New_York'app.tasks.register(TimezoneAwareTask())
So here the task is going under exception i.e. SessionDoesNotExist and the local timezone of the user can't be fetched.