Skip to content

Commit cc5af4b

Browse files
committed
add timezone example
1 parent 4dc5756 commit cc5af4b

File tree

1 file changed

+121
-0
lines changed

1 file changed

+121
-0
lines changed

content/pages/examples/django/django-utils-timezone.markdown

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,3 +151,124 @@ class Migration(migrations.Migration):
151151
},
152152
),
153153
```
154+
155+
156+
## Example 3 from django-easy-timezones
157+
[django-easy-timezones](https://github.com/Miserlou/django-easy-timezones)
158+
([project website](https://www.gun.io/blog/django-easy-timezones))
159+
is a [Django](/django.html)
160+
[middleware](https://docs.djangoproject.com/en/2.2/topics/http/middleware/)
161+
[code library](https://pypi.org/project/django-easy-timezones/)
162+
to simplify handling time data in your applications using
163+
users' geolocation data.
164+
165+
[**django-easy-timezones/easy_timezones/middleware.py**](https://github.com/Miserlou/django-easy-timezones/blob/master/easy_timezones/middleware.py)
166+
167+
```python
168+
import django
169+
from django.conf import settings
170+
from django.contrib.auth import get_user_model
171+
from django.core.exceptions import ImproperlyConfigured
172+
~~from django.utils import timezone
173+
import pytz
174+
import pygeoip
175+
import os
176+
177+
from .signals import detected_timezone
178+
from .utils import get_ip_address_from_request, is_valid_ip, is_local_ip
179+
180+
181+
db_loaded = False
182+
db = None
183+
db_v6 = None
184+
185+
def load_db_settings():
186+
GEOIP_DATABASE = getattr(settings, 'GEOIP_DATABASE', 'GeoLiteCity.dat')
187+
188+
if not GEOIP_DATABASE:
189+
raise ImproperlyConfigured("GEOIP_DATABASE setting has not been " + \
190+
"properly defined.")
191+
192+
if not os.path.exists(GEOIP_DATABASE):
193+
raise ImproperlyConfigured("GEOIP_DATABASE setting is defined, " + \
194+
"but file does not exist.")
195+
196+
GEOIPV6_DATABASE = getattr(settings, 'GEOIPV6_DATABASE',
197+
'GeoLiteCityv6.dat')
198+
199+
if not GEOIPV6_DATABASE:
200+
raise ImproperlyConfigured("GEOIPV6_DATABASE setting has not " + \
201+
"been properly defined.")
202+
203+
if not os.path.exists(GEOIPV6_DATABASE):
204+
raise ImproperlyConfigured("GEOIPV6_DATABASE setting is " + \
205+
"defined, but file does not exist.")
206+
207+
return (GEOIP_DATABASE, GEOIPV6_DATABASE)
208+
209+
load_db_settings()
210+
211+
def load_db():
212+
213+
GEOIP_DATABASE, GEOIPV6_DATABASE = load_db_settings()
214+
215+
global db
216+
db = pygeoip.GeoIP(GEOIP_DATABASE, pygeoip.MEMORY_CACHE)
217+
218+
global db_v6
219+
db_v6 = pygeoip.GeoIP(GEOIPV6_DATABASE, pygeoip.MEMORY_CACHE)
220+
221+
global db_loaded
222+
db_loaded = True
223+
224+
225+
if django.VERSION >= (1, 10):
226+
from django.utils.deprecation import MiddlewareMixin
227+
middleware_base_class = MiddlewareMixin
228+
else:
229+
middleware_base_class = object
230+
231+
232+
class EasyTimezoneMiddleware(middleware_base_class):
233+
def process_request(self, request):
234+
"""
235+
If we can get a valid IP from the request,
236+
look up that address in the database to get the appropriate
237+
timezone and activate it. Else, use the default.
238+
"""
239+
240+
if not request:
241+
return
242+
243+
if not db_loaded:
244+
load_db()
245+
246+
tz = request.session.get('django_timezone')
247+
248+
if not tz:
249+
# use the default timezone (settings.TIME_ZONE) for localhost
250+
~~ tz = timezone.get_default_timezone()
251+
252+
client_ip = get_ip_address_from_request(request)
253+
ip_addrs = client_ip.split(',')
254+
for ip in ip_addrs:
255+
if is_valid_ip(ip) and not is_local_ip(ip):
256+
if ':' in ip:
257+
tz = db_v6.time_zone_by_addr(ip)
258+
break
259+
else:
260+
tz = db.time_zone_by_addr(ip)
261+
break
262+
263+
if tz:
264+
~~ timezone.activate(tz)
265+
request.session['django_timezone'] = str(tz)
266+
if getattr(settings, 'AUTH_USER_MODEL',
267+
None) and getattr(request, 'user', None):
268+
~~ detected_timezone.send(sender=get_user_model(),
269+
~~ instance=request.user,
270+
~~ timezone=tz)
271+
else:
272+
~~ timezone.deactivate()
273+
```
274+

0 commit comments

Comments
 (0)