Add middleware support for detecting user timezones
This commit is contained in:
38
polyclinic_scheduling/apps/RUG_template/middleware.py
Normal file
38
polyclinic_scheduling/apps/RUG_template/middleware.py
Normal file
@ -0,0 +1,38 @@
|
||||
import pytz
|
||||
import requests
|
||||
|
||||
from ipware import get_client_ip
|
||||
from django.utils import timezone
|
||||
|
||||
# make sure you add `TimezoneMiddleware` appropriately in settings.py: 'apps.RUG_template.middleware.TimezoneMiddleware'
|
||||
class TimezoneMiddleware:
|
||||
""" Middleware to check user timezone. """
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
# One-time configuration and initialization.
|
||||
|
||||
def __call__(self, request):
|
||||
# Code to be executed for each request before
|
||||
# the view (and later middleware) are called.
|
||||
client_ip, is_routable = get_client_ip(request)
|
||||
user_time_zone = request.session.get('user_time_zone', None)
|
||||
try:
|
||||
if user_time_zone is None and is_routable and client_ip is not None:
|
||||
# Here we use an online service to get visitor info. Maybe not the nicest way to do it, but it is a way
|
||||
# Also we only check when we get a public IP address. Local networks will not be checked online
|
||||
# https://freegeoip.app
|
||||
freegeoip_response = requests.get('https://freegeoip.app/json/{0}'.format(client_ip))
|
||||
freegeoip_response_json = freegeoip_response.json()
|
||||
user_time_zone = freegeoip_response_json['time_zone']
|
||||
if user_time_zone:
|
||||
request.session['user_time_zone'] = user_time_zone
|
||||
timezone.activate(pytz.timezone(user_time_zone))
|
||||
except:
|
||||
pass
|
||||
|
||||
response = self.get_response(request)
|
||||
|
||||
# Code to be executed for each request/response after
|
||||
# the view is called.
|
||||
|
||||
return response
|
Reference in New Issue
Block a user