"""Compare the latest Calgary building-permit count with the same month a year earlier. Run with Python 3.8 or later: python3 fonsora_calgary_permits.py Walkthrough: https://fonsora.net/examples/calgary-building-permits/ """ import csv import hashlib import io import json from urllib.error import URLError from urllib.request import urlopen CATALOG = "https://fonsora.net/data/catalog.json" DATASET = "calgary-expansion/building-permits-issued-monthly" def main(): with urlopen(CATALOG, timeout=30) as response: catalog = json.load(response) dataset = next((item for item in catalog["dataset"] if item["identifier"] == DATASET), None) if dataset is None: raise ValueError("The Calgary permits dataset is unavailable in the current catalog.") csv_file = next((item for item in dataset["distribution"] if item["encodingFormat"] == "text/csv"), None) if csv_file is None: raise ValueError("The current release has no CSV download.") with urlopen(csv_file["contentUrl"], timeout=30) as response: contents = response.read() if hashlib.sha256(contents).hexdigest() != csv_file["sha256"]: raise ValueError("The CSV checksum differs from the catalog. Fetch the release again.") rows = csv.DictReader(io.StringIO(contents.decode("utf-8-sig"), newline="")) latest = max(rows, key=lambda row: row["issue_month"], default=None) if latest is None: raise ValueError("The current release contains no observations.") month = latest["issue_month"][:7] print(f"{month}: {int(latest['issued_permit_count']):,} permits issued in Calgary.") previous = latest["issued_permit_count_year_earlier"] change = latest["year_over_year_change_pct"] if previous: print(f"Same month one year earlier: {int(previous):,} permits.") if change: print(f"Year-over-year change: {change}%.") else: print("A year-over-year percentage is unavailable for this month.") print(f"Fonsora release: {dataset['url']}") print(f"City of Calgary source: {dataset['isBasedOn']}") print(dataset["creditText"], dataset["license"]) if __name__ == "__main__": try: main() except (URLError, TimeoutError, ValueError) as error: raise SystemExit(str(error))