Reject invalid coordinates with HTTP 400
This commit is contained in:
parent
93a4572a5d
commit
45dc2c2e67
2 changed files with 69 additions and 8 deletions
15
lookup.py
15
lookup.py
|
|
@ -3,6 +3,7 @@
|
|||
|
||||
import inspect
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
|
|
@ -315,7 +316,7 @@ def parse_coordinate(coord_str: str) -> float:
|
|||
(?P<direction>[NSEW])?
|
||||
"""
|
||||
|
||||
match = re.match(dms_pattern, coord_str, re.VERBOSE)
|
||||
match = re.fullmatch(dms_pattern, coord_str, re.VERBOSE)
|
||||
if match:
|
||||
degrees = int(match.group("degrees"))
|
||||
minutes = int(match.group("minutes"))
|
||||
|
|
@ -337,15 +338,15 @@ def parse_coordinate(coord_str: str) -> float:
|
|||
|
||||
def validate_coordinates(lat: float, lon: float) -> str | None:
|
||||
"""Validate latitude and longitude ranges. Returns error message if invalid."""
|
||||
if lat < -90 or lat > 90:
|
||||
if not math.isfinite(lat) or lat < -90 or lat > 90:
|
||||
return "Latitude must be between -90 and 90 degrees"
|
||||
if lon < -180 or lon > 180:
|
||||
if not math.isfinite(lon) or lon < -180 or lon > 180:
|
||||
return "Longitude must be between -180 and 180 degrees"
|
||||
return None
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index() -> str | Response:
|
||||
def index() -> str | Response | tuple[Response, int] | tuple[Response, int, dict[str, str]]:
|
||||
"""Index page."""
|
||||
t0 = time()
|
||||
database.session.execute(text("SELECT 1"))
|
||||
|
|
@ -359,8 +360,6 @@ def index() -> str | Response:
|
|||
samples = sorted(geocode.samples, key=lambda row: row[2])
|
||||
return render_template("index.html", samples=samples)
|
||||
|
||||
lat, lon = float(lat_str), float(lon_str)
|
||||
|
||||
try:
|
||||
lat = parse_coordinate(lat_str)
|
||||
lon = parse_coordinate(lon_str)
|
||||
|
|
@ -370,10 +369,10 @@ def index() -> str | Response:
|
|||
error="Invalid coordinate format. "
|
||||
+ "Please use decimal degrees (e.g., 56.099600) "
|
||||
+ "or DMS format (e.g., 56°5'58.56\"N)",
|
||||
)
|
||||
), 400
|
||||
|
||||
if error_msg := validate_coordinates(lat, lon):
|
||||
return jsonify(coords={"lat": lat, "lon": lon}, error=error_msg)
|
||||
return jsonify(coords={"lat": lat_str, "lon": lon_str}, error=error_msg), 400
|
||||
|
||||
needs_commons = request.args.get("needs_commons", "true").lower() != "false"
|
||||
try:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue