iptime: cache the external IP

master
Michael Hope 3 years ago
parent c2a63719a9
commit 8573ab58c1

@ -1,4 +1,5 @@
import datetime
import functools
import time
from geoip import geolite2
@ -12,10 +13,16 @@ app = flask.Flask(__name__)
_ = prometheus_flask_exporter.PrometheusMetrics(app)
def to_sec(dt):
def _to_sec(dt):
return dt.hour * 60 * 60 + dt.minute * 60 + dt.second
@functools.lru_cache(maxsize=5)
def _external_ip():
r = requests.get('https://api.ipify.org?format=json')
return r.json().get('ip')
@app.route('/now')
def now():
ip = flask.request.args.get('ip')
@ -23,8 +30,7 @@ def now():
ip = flask.request.remote_addr
if ip.startswith('192.168.') or ip.startswith('10.') or ip.startswith(
'127.0.'):
r = requests.get('https://api.ipify.org?format=json')
ip = r.json().get('ip')
ip = _external_ip()
loc = geolite2.lookup(ip)
if loc is None:
flask.abort(
@ -45,10 +51,10 @@ def now():
longitude=loc.location[1],
timezone=loc.timezone,
dawn=dawn,
dawn_sec=to_sec(dawn),
dawn_sec=_to_sec(dawn),
dusk=dusk,
dusk_sec=to_sec(dusk),
dusk_sec=_to_sec(dusk),
local_time=now,
day_sec=to_sec(now),
day_sec=_to_sec(now),
posix_sec=int(epoch))
return flask.jsonify(resp)

Loading…
Cancel
Save