-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.py
83 lines (56 loc) · 1.63 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# -*- coding: utf-8 -*-
#
# Copyright Adam Pritchard 2014
# MIT License : https://adampritchard.mit-license.org/
#
"""General utility functions that mostly aren't specific to this application.
"""
import re
import errno
import datetime
import logging
import dateutil.parser
import dateutil.tz
import config
def basic_validator(val, required):
if required and not val:
return False
if val is None:
return True
if not isinstance(val, str):
return False
return True
def email_validator(val, required):
if not basic_validator(val, required):
return False
if not val:
return True
if not re.fullmatch(r'[^@]+@[^@]+\.[^@]+', val):
return False
return True
def latlong_validator(val, required):
if not basic_validator(val, required):
return False
if not val:
return True
latlong = val.split(', ')
if len(latlong) != 2:
return False
try:
latitude = float(latlong[0])
longitude = float(latlong[1])
except ValueError:
return False
return latitude > -180.0 and latitude < 180.0 and \
longitude > -180.0 and longitude < 180.0
def current_datetime():
"""Returns string of current datetime.
"""
# We only want the date and not the time (and it needs to be tz-aware).
return datetime.datetime.now(dateutil.tz.gettz(config.TIMEZONE)).strftime('%Y-%m-%d')
def days_ago(datestring):
"""Returns and integer of the number of days ago the given date was.
"""
date = dateutil.parser.parse(datestring)
delta = datetime.datetime.now() - date
return delta.days