3
\$\begingroup\$

Is the set_cookie variable the correct way to signal that the cookie should be set? It does not seems pythonic to me:

cookie = request.COOKIES.get(TIMEZONE_COOKIE_NAME)
set_cookie = False
if cookie and cookie in pytz.all_timezones_set:
    timezone.activate(pytz.timezone(cookie))
elif request.ip:
    geo = GeoIP2()
    try:
        time_zone = geo.city(request.ip).time_zone
        if time_zone:
            timezone.activate(pytz.timezone(time_zone))
            set_cookie = True
    except GeoIP2Error:
        self.logger.warning('Could not determine time zone of ip address: %s', request.ip)

response = self.get_response(request)
if set_cookie:
    response.set_cookie(TIMEZONE_COOKIE_NAME, time_zone)
return response
\$\endgroup\$
1
+50
\$\begingroup\$

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 from GeoIP2 always compatible with pytz 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 call to set the timezone is only there 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.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Sorry, I forgot forgot to mention that get_response must be called after the time zone was activated! Otherwise the page would be rendered with the default time zone. \$\endgroup\$ – R3turnz Apr 22 '17 at 11:29
  • \$\begingroup\$ Right, that changes things :) \$\endgroup\$ – ferada Apr 22 '17 at 11:29
  • 1
    \$\begingroup\$ I have exactly your both snippets written before :) With this the cookie is always send with the response, even if it's already set. I know that it is not a big overhead, but my above solution covers it. \$\endgroup\$ – R3turnz Apr 22 '17 at 12:26
  • \$\begingroup\$ Then I'm pretty sure you're good with what you have. \$\endgroup\$ – ferada Apr 22 '17 at 13:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.