I'd rearrange a bit first, set_cookie
isn't really useful,Edit: Well my previous suggestions don't work with the fact that block
at the end can justget_response
has to be inlined:
cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
response = self.get_response(request)
if cookie and cookie in pytz.all_timezones_set:
timezone.activate(pytz.timezone(cookie))
elif request.ip:
try:
time_zone = GeoIP2().city(request.ip).time_zone
if time_zone:
timezone.activate(pytz.timezone(time_zone))
response.set_cookie(TIMEZONE_COOKIE_NAME, time_zone)
except GeoIP2Error:
self.logger.warning('Could not determine time zone of ip address: %s', request.ip)
return response
From an efficiency and readability standpoint that's actually fine IMO,
I wouldn't necessarily change it morecalled with the correct timezone active.
However, consider the two logical blocks, "get a timezone in pytz
format" and "set the timezone cookie" as separate code blocks too e.g.:
cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
if cookie not in pytz.all_timezones_set 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)
response = self.get_response(request)
if cookie in pytz.all_timezones_set:
timezone.activate(pytz.timezone(cookie))
response.set_cookie(TIMEZONE_COOKIE_NAME, cookie)
return response
My concern would be here that some work is duplicated to get slightly
better readability, instead perhapsPerhaps the following would be betterwork,
verifying verifying the cookie value only once and
and discarding it if it doesn't
fit fit:
cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
if cookie nonot 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)
response = self.get_response(request)
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.