From 4720814e1f3c9b8953ff9062b01d45aee5e0b7a3 Mon Sep 17 00:00:00 2001 From: Edward Betts Date: Fri, 24 Nov 2023 15:13:00 +0000 Subject: [PATCH] Log usage Closes: #6 --- geocode/model.py | 17 +++++++++++++++-- lookup.py | 19 ++++++++++++------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/geocode/model.py b/geocode/model.py index fda5232..e2c30c9 100644 --- a/geocode/model.py +++ b/geocode/model.py @@ -9,9 +9,9 @@ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm import column_property from sqlalchemy.schema import Column -from sqlalchemy.types import Float, Integer, Numeric, String +from sqlalchemy.types import DateTime, Float, Integer, Numeric, String -from .database import session +from .database import now_utc, session Base = declarative_base() Base.query = session.query_property() @@ -81,3 +81,16 @@ class Scotland(Base): name = Column(String(50)) geom = Column(Geometry("MULTIPOLYGON", srid=27700)) + + +class LookupLog(Base): + """Log lookups.""" + + __tablename__ = "lookup_log" + + id = Column(Integer, primary_key=True) + dt = Column(DateTime, default=now_utc()) + lat = Column(Float) + lon = Column(Float) + remote_addr = Column(String) + result = Column(postgresql.JSONB) diff --git a/lookup.py b/lookup.py index 69db909..64c1201 100755 --- a/lookup.py +++ b/lookup.py @@ -186,14 +186,19 @@ def index() -> str | Response: lat, lon = request.args.get("lat"), request.args.get("lon") - if lat is not None and lon is not None: - result = lat_lon_to_wikidata(lat, lon)["result"] - result.pop("element", None) - result.pop("geojson", None) - return jsonify(result) + if lat is None or lon is None: + samples = sorted(geocode.samples, key=lambda row: row[2]) + return render_template("index.html", samples=samples) - samples = sorted(geocode.samples, key=lambda row: row[2]) - return render_template("index.html", samples=samples) + result = lat_lon_to_wikidata(lat, lon)["result"] + result.pop("element", None) + result.pop("geojson", None) + log = model.LookupLog( + lat=lat, lon=lon, remote_addr=request.remote_addr, result=result + ) + database.session.add(log) + database.session.commit() + return jsonify(result) @app.route("/random")