Skip to content

Instantly share code, notes, and snippets.

@sourceperl
Created February 9, 2018 14:44
Show Gist options
  • Save sourceperl/9567e1e0714c86fe6f81689e22604f8e to your computer and use it in GitHub Desktop.
Save sourceperl/9567e1e0714c86fe6f81689e22604f8e to your computer and use it in GitHub Desktop.
Python request of parking availability of the city of Lille (from MEL opendata platform)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import dateutil.parser
import requests
import pandas as pd
import datetime
# some consts
NAN = float('nan')
URL = 'https://opendata.lillemetropole.fr/api/records/1.0/search/'
PARK_REQ = '?dataset=disponibilite-parkings&rows=50'
# set global options
pd.set_option('display.width', 120)
# some vars
park_df = pd.DataFrame(columns=['name', 'state', 'display', 'available', 'capacity', 'update', 'occupied'])
park_df.index.name = 'id'
# request Lille parking dataset
try:
park_raw_d = requests.get(URL + PARK_REQ).json()
except requests.exceptions.RequestException:
park_raw_d = None
# process data
try:
for record in list(park_raw_d['records']):
# decode 'fields' part
fields = dict(record['fields'])
try:
park_id = str(fields['id'])
park_name = str(fields['libelle'])
park_state = str(fields['etat'])
park_display = str(fields.get('aff', ''))
try:
park_update = dateutil.parser.parse(fields.get('datemaj', ''))
except (KeyError, ValueError):
park_update = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
park_available = float(fields.get('dispo', NAN))
park_capacity = float(fields.get('max', NAN))
except KeyError:
# ignore this one, go next
continue
# process park data
park_df.loc[park_id, 'name'] = park_name
park_df.loc[park_id, 'state'] = park_state
park_df.loc[park_id, 'display'] = park_display
park_df.loc[park_id, 'available'] = park_available
park_df.loc[park_id, 'capacity'] = park_capacity
park_df.loc[park_id, 'update'] = park_update
except (TypeError, KeyError):
# global json fmt mismatch
print('json not available or not valid')
exit()
# add "occupied" ratio
park_df['occupied'] = 100 - 100 * park_df['available']/park_df['capacity']
# echo parking selection
print(park_df.loc[['LIL0005', 'LIL0006', 'LIL0007', 'LIL0008']].sort_values(by='occupied', ascending=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment