Skip to content

Instantly share code, notes, and snippets.

@jchome
Last active February 27, 2023 10:29
Show Gist options
  • Save jchome/8ec333eb3f8cffca4eb7d27840dc2c85 to your computer and use it in GitHub Desktop.
Save jchome/8ec333eb3f8cffca4eb7d27840dc2c85 to your computer and use it in GitHub Desktop.
Python version of the "Parking" exercise
from flask import Flask, request
import urllib.request
import json
import geopy.distance
app = Flask(__name__)
def parkings_Poitiers():
"""
Get all parkings of Poiters, as list of dict objects
Usage:
curl 'http://127.0.0.1:5000/nearOfPoint?lat=46.58570214260076&lon=0.35044408926683884&limit=1'
curl 'http://127.0.0.1:5000/all'
"""
webURL = urllib.request.urlopen(
'https://data.grandpoitiers.fr/api/records/1.0/search/?dataset=mobilites-stationnement-des-parkings-en-temps-reel&facet=nom'
)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
JSON_object = json.loads(data.decode(encoding))
records = JSON_object['records']
parkings = []
for d in records:
parking = {}
fields = d["fields"]
parking["name"] = fields["nom"]
if "geo_point_2d" in fields:
parking["lat"] = fields["geo_point_2d"][0]
parking["lon"] = fields["geo_point_2d"][1]
else:
continue
parking["capacity"] = fields["capacite"]
parking["vacancy"] = fields["places"]
parkings.append(parking)
return parkings
@app.route('/all')
def index():
"""
Return all parkings of the URL request
"""
return parkings_Poitiers()
@app.route('/nearOfPoint')
def parkings_near_of():
"""
Return sorted parkings of the URL request, limited to a number of results
"""
lat = float(request.args.get("lat"))
lon = float(request.args.get("lon"))
limit = int(request.args.get("limit"))
data = sorted(parkings_Poitiers(),
key=lambda parking: geopy.distance.geodesic(
(float(parking["lat"]), float(parking["lon"])),
(lat, lon)).km * 1000)
if limit:
return data[0:limit]
else:
return data
if __name__ == "__main__":
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment