Edit: Well my previous suggestions don't work with the fact that
get_response
has to be called with the correct timezone active.
- Is the
time_zone
attribute fromGeoIP2
always compatible withpytz
btw.?
Perhaps the following would work, verifying the cookie value only once and discarding it if it doesn't fit:
cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
if cookie not in pytz.all_timezones_set:
cookie = None
if not cookie and request.ip:
try:
cookie = GeoIP2().city(request.ip).time_zone
except GeoIP2Error:
self.logger.warning('Could not determine time zone of ip address: %s', request.ip)
if cookie:
timezone.activate(pytz.timezone(cookie))
response = self.get_response(request)
if cookie:
response.set_cookie(TIMEZONE_COOKIE_NAME, cookie)
return response
So, downside is a lot of mentions of cookie
, upside is that it's not
more costly what you had before and the timezone is only set once.
Last point, if anything like this happens to be needed more than once, put it into separate functions. This snippet is a bit short to make that call.