Skip to content

Open Infrastructure Map, a view of infrastructure data in OpenStreetMap

Updated styling, sitemap, info pages

Russ Garrett2ed23d192098
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..7fe3056
--- /dev/null
+++ b/README.md
@@ -0,0 +1,6 @@
+New OpenInfraMap web backend, serving info and stats pages.
+
+## Development
+
+ poetry install
+ poetry run uvicorn main:app --reload
diff --git a/config.py b/config.py
new file mode 100644
index 0000000..4017551
--- /dev/null
+++ b/config.py
@@ -0,0 +1,9 @@
+from databases import Database
+from starlette.config import Config
+
+config = Config(".env")
+
+DATABASE_URL = config("DATABASE_URL")
+
+database = Database(DATABASE_URL)
+
diff --git a/data.py b/data.py
new file mode 100644
index 0000000..3e74fe8
--- /dev/null
+++ b/data.py
@@ -0,0 +1,10 @@
+from config import database
+
+
+async def get_countries():
+ return await database.fetch_all(
+ query="""SELECT "union" FROM countries.country_eez
+ WHERE "union" != \'Antarctica\'
+ AND pol_type = \'Union EEZ and country\'
+ ORDER BY "union" ASC"""
+ )
diff --git a/main.py b/main.py
index 3b9ddb3..d689feb 100644
--- a/main.py
+++ b/main.py
@@ -1,92 +1,63 @@
-from decimal import Decimal
-from functools import wraps
+from starlette.responses import PlainTextResponse
from starlette.applications import Starlette
-from starlette.exceptions import HTTPException
from starlette.templating import Jinja2Templates
-from starlette.config import Config
-from starlette.routing import Mount
+from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
-from databases import Database
-config = Config(".env")
+from template_functions import format_power, osm_link
+from config import database, config
+from util import cache_for, country_required
+from sitemap import sitemap
+from data import get_countries
+
DEBUG = config("DEBUG", cast=bool, default=False)
-DATABASE_URL = config("DATABASE_URL")
+templates = Jinja2Templates(directory="templates")
-database = Database(DATABASE_URL)
+templates.env.filters["power"] = format_power
+templates.env.globals["osm_link"] = osm_link
-templates = Jinja2Templates(directory="templates")
app = Starlette(
debug=DEBUG,
on_startup=[database.connect],
on_shutdown=[database.disconnect],
- routes=[Mount("/static", app=StaticFiles(directory="static"), name="static")],
+ routes=[
+ Mount("/static", app=StaticFiles(directory="static"), name="static"),
+ Route("/sitemap.xml", sitemap),
+ ],
)
-def format_power(val):
- if val is None:
- return ""
- elif val >= 50e6:
- return "{:,.0f} MW".format(val / Decimal(1e6))
- elif val >= 1e6:
- return "{:.2f} MW".format(val / Decimal(1e6))
- else:
- return "{:.0f} kW".format(val / Decimal(1e3))
-
-
-templates.env.filters["power"] = format_power
-
-
-def osm_link(osm_id, geom_type):
- url = "https://www.openstreetmap.org/"
- if osm_id < 0:
- osm_id = -osm_id
- url += "relation"
- elif geom_type == "ST_Point":
- url += "node"
- else:
- url += "way"
- return url + "/" + str(osm_id)
-
-
-templates.env.globals["osm_link"] = osm_link
-
-
-def country_required(func):
- @wraps(func)
- async def wrap_country(request):
- country = request.path_params["country"]
+async def main(request):
+ # Dummy response - this endpoint is served statically in production from the webpack build
+ return PlainTextResponse('')
- res = await database.fetch_one(
- query='SELECT gid, "union" FROM countries.country_eez WHERE "union" = :union',
- values={"union": country},
- )
- if not res:
- raise HTTPException(404)
- return await func(request, res)
+@cache_for(3600)
+async def about(request):
+ return templates.TemplateResponse("about.html", {"request": request})
- return wrap_country
[email protected]("/copyright")
+@cache_for(3600)
+async def copyright(request):
+ return templates.TemplateResponse("copyright.html", {"request": request})
-async def main(request):
- countries = await database.fetch_all(
- query="""SELECT "union" FROM countries.country_eez
- WHERE "union" != \'Antarctica\'
- AND pol_type = \'Union EEZ and country\'
- ORDER BY "union" ASC"""
- )
+@cache_for(86400)
+async def stats(request):
return templates.TemplateResponse(
- "index.html", {"request": request, "countries": countries}
+ "index.html", {"request": request, "countries": await get_countries()}
)
[email protected]("/area/{country}")
[email protected]("/stats/area/{country}")
@country_required
+@cache_for(3600)
async def country(request, country):
plant_stats = await database.fetch_one(
query="""SELECT SUM(convert_power(output)) AS output, COUNT(*)
@@ -113,15 +84,16 @@ async def country(request, country):
"country.html",
{
"request": request,
- "country": country['union'],
+ "country": country["union"],
"plant_stats": plant_stats,
"plant_source_stats": plant_source_stats,
},
)
[email protected]("/area/{country}/plants")
[email protected]("/stats/area/{country}/plants")
@country_required
+@cache_for(3600)
async def plants_country(request, country):
gid = country[0]
diff --git a/poetry.lock b/poetry.lock
index ff7a023..d291f30 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1,39 +1,47 @@
[[package]]
-category = "main"
-description = "File support for asyncio."
name = "aiofiles"
+version = "0.5.0"
+description = "File support for asyncio."
+category = "main"
optional = false
python-versions = "*"
-version = "0.5.0"
[[package]]
+name = "asgi-sitemaps"
+version = "0.3.2"
+description = "Sitemap generation for ASGI applications."
category = "main"
-description = "An asyncio PostgreSQL driver"
+optional = false
+python-versions = ">=3.7"
+
+[[package]]
name = "asyncpg"
+version = "0.21.0"
+description = "An asyncio PostgreSQL driver"
+category = "main"
optional = false
python-versions = ">=3.5.0"
-version = "0.21.0"
[package.extras]
-dev = ["Cython (0.29.20)", "pytest (>=3.6.0)", "Sphinx (>=1.7.3,<1.8.0)", "sphinxcontrib-asyncio (>=0.2.0,<0.3.0)", "sphinx-rtd-theme (>=0.2.4,<0.3.0)", "pycodestyle (>=2.5.0,<2.6.0)", "flake8 (>=3.7.9,<3.8.0)", "uvloop (>=0.14.0,<0.15.0)"]
+dev = ["Cython (==0.29.20)", "pytest (>=3.6.0)", "Sphinx (>=1.7.3,<1.8.0)", "sphinxcontrib-asyncio (>=0.2.0,<0.3.0)", "sphinx-rtd-theme (>=0.2.4,<0.3.0)", "pycodestyle (>=2.5.0,<2.6.0)", "flake8 (>=3.7.9,<3.8.0)", "uvloop (>=0.14.0,<0.15.0)"]
docs = ["Sphinx (>=1.7.3,<1.8.0)", "sphinxcontrib-asyncio (>=0.2.0,<0.3.0)", "sphinx-rtd-theme (>=0.2.4,<0.3.0)"]
test = ["pycodestyle (>=2.5.0,<2.6.0)", "flake8 (>=3.7.9,<3.8.0)", "uvloop (>=0.14.0,<0.15.0)"]
[[package]]
-category = "main"
-description = "Composable command line interface toolkit"
name = "click"
+version = "7.1.2"
+description = "Composable command line interface toolkit"
+category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
-version = "7.1.2"
[[package]]
-category = "main"
-description = "Async database support for Python."
name = "databases"
+version = "0.4.0"
+description = "Async database support for Python."
+category = "main"
optional = false
python-versions = ">=3.6"
-version = "0.4.0"
[package.dependencies]
sqlalchemy = "*"
@@ -45,20 +53,20 @@ postgresql_aiopg = ["aiopg"]
sqlite = ["aiosqlite"]
[[package]]
-category = "main"
-description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1"
name = "h11"
+version = "0.11.0"
+description = "A pure-Python, bring-your-own-I/O implementation of HTTP/1.1"
+category = "main"
optional = false
python-versions = "*"
-version = "0.11.0"
[[package]]
-category = "main"
-description = "A very fast and expressive template engine."
name = "jinja2"
+version = "2.11.2"
+description = "A very fast and expressive template engine."
+category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*"
-version = "2.11.2"
[package.dependencies]
MarkupSafe = ">=0.23"
@@ -67,20 +75,20 @@ MarkupSafe = ">=0.23"
i18n = ["Babel (>=0.8)"]
[[package]]
-category = "main"
-description = "Safely add untrusted strings to HTML/XML markup."
name = "markupsafe"
+version = "1.1.1"
+description = "Safely add untrusted strings to HTML/XML markup."
+category = "main"
optional = false
python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*"
-version = "1.1.1"
[[package]]
-category = "main"
-description = "Database Abstraction Library"
name = "sqlalchemy"
+version = "1.3.20"
+description = "Database Abstraction Library"
+category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
-version = "1.3.20"
[package.extras]
mssql = ["pyodbc"]
@@ -95,23 +103,23 @@ postgresql_psycopg2cffi = ["psycopg2cffi"]
pymysql = ["pymysql"]
[[package]]
-category = "main"
-description = "The little ASGI library that shines."
name = "starlette"
+version = "0.13.8"
+description = "The little ASGI library that shines."
+category = "main"
optional = false
python-versions = ">=3.6"
-version = "0.13.8"
[package.extras]
full = ["aiofiles", "graphene", "itsdangerous", "jinja2", "python-multipart", "pyyaml", "requests", "ujson"]
[[package]]
-category = "main"
-description = "The lightning-fast ASGI server."
name = "uvicorn"
+version = "0.12.2"
+description = "The lightning-fast ASGI server."
+category = "main"
optional = false
python-versions = "*"
-version = "0.12.2"
[package.dependencies]
click = ">=7.0.0,<8.0.0"
@@ -121,15 +129,19 @@ h11 = ">=0.8"
standard = ["websockets (>=8.0.0,<9.0.0)", "watchgod (>=0.6,<0.7)", "python-dotenv (>=0.13)", "PyYAML (>=5.1)", "httptools (>=0.1.0,<0.2.0)", "uvloop (>=0.14.0)", "colorama (>=0.4)"]
[metadata]
-content-hash = "967394b9c137d4b9116713b0ef3410869aa50b5c3fd3d706bcf9c1cb798019d6"
-lock-version = "1.0"
+lock-version = "1.1"
python-versions = "^3.8"
+content-hash = "5b22be7eddf64818d3b97550501ac6e26326c6b8ae892b320746ed51abd74321"
[metadata.files]
aiofiles = [
{file = "aiofiles-0.5.0-py3-none-any.whl", hash = "sha256:377fdf7815cc611870c59cbd07b68b180841d2a2b79812d8c218be02448c2acb"},
{file = "aiofiles-0.5.0.tar.gz", hash = "sha256:98e6bcfd1b50f97db4980e182ddd509b7cc35909e903a8fe50d8849e02d815af"},
]
+asgi-sitemaps = [
+ {file = "asgi-sitemaps-0.3.2.tar.gz", hash = "sha256:ede30466cddb8d242f0e1169f9824ab810d56ac9b4beaf56ada2a90779439caf"},
+ {file = "asgi_sitemaps-0.3.2-py3-none-any.whl", hash = "sha256:b20aa963f1553a1ff5b1757b4fb130fafcf11ec70f985668f95c62c63c1fb432"},
+]
asyncpg = [
{file = "asyncpg-0.21.0-cp35-cp35m-macosx_10_13_x86_64.whl", hash = "sha256:09badce47a4645cfe523cc8a182bd047d5d62af0caaea77935e6a3c9e77dc364"},
{file = "asyncpg-0.21.0-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:6b7807bfedd24dd15cfb2c17c60977ce01410615ecc285268b5144a944ec97ff"},
diff --git a/pyproject.toml b/pyproject.toml
index f65c729..aa027d4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,6 +12,7 @@ asyncpg = "^0.21.0"
aiofiles = "^0.5.0"
jinja2 = "^2.11.2"
uvicorn = "^0.12.2"
+asgi-sitemaps = "^0.3.2"
[tool.poetry.dev-dependencies]
diff --git a/sitemap.py b/sitemap.py
new file mode 100644
index 0000000..cd5b64c
--- /dev/null
+++ b/sitemap.py
@@ -0,0 +1,30 @@
+import asgi_sitemaps
+from starlette.datastructures import URL
+from starlette.requests import Request
+
+from data import get_countries
+
+
+class StaticSitemap(asgi_sitemaps.Sitemap):
+ def items(self):
+ return ["main", "about", "stats", "copyright"]
+
+ def location(self, item):
+ request = Request(scope=self.scope)
+ url = request.url_for(item)
+ return URL(url).path
+
+
+class CountryPageSitemap(asgi_sitemaps.Sitemap):
+ async def items(self):
+ return [row[0] for row in await get_countries()]
+
+ def location(self, item):
+ request = Request(scope=self.scope)
+ url = request.url_for("country", country=item)
+ return URL(url).path
+
+
+sitemap = asgi_sitemaps.SitemapApp(
+ [StaticSitemap(), CountryPageSitemap()], domain="openinframap.org"
+)
diff --git a/static/main.css b/static/main.css
index 2390a7f..2b86919 100644
--- a/static/main.css
+++ b/static/main.css
@@ -3,11 +3,14 @@ html, body {
padding: 0;
border: 0;
font-size: 18px;
+ height: 100%;
}
body {
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #333;
+ display: flex;
+ flex-direction: column;
}
a, a:visited {
@@ -18,6 +21,7 @@ header {
padding: 3px 8px;
border-bottom: 1px solid #ccc;
background-color: #eee;
+ flex: 0 0 auto;
}
h1, h2 {
@@ -32,15 +36,17 @@ h1 a, h2 a {
}
#content {
- margin: 0px auto;
+ margin: 0px auto;
+ padding: 0px 10px;
max-width: 1000px;
- min-height: 80vh;
+ flex: 1 0 auto;
}
footer {
- margin-top: 20px;
+ flex-shrink: 0;
padding: 8px 8px;
- font-size: 0.8em;
+ font-size: 0.7em;
+ background-color: #fafafa;
}
footer, footer a, footer a:visited {
diff --git a/template_functions.py b/template_functions.py
new file mode 100644
index 0000000..f127537
--- /dev/null
+++ b/template_functions.py
@@ -0,0 +1,24 @@
+from decimal import Decimal
+
+
+def format_power(val):
+ if val is None:
+ return ""
+ elif val >= 50e6:
+ return "{:,.0f} MW".format(val / Decimal(1e6))
+ elif val >= 1e6:
+ return "{:.2f} MW".format(val / Decimal(1e6))
+ else:
+ return "{:.0f} kW".format(val / Decimal(1e3))
+
+
+def osm_link(osm_id, geom_type):
+ url = "https://www.openstreetmap.org/"
+ if osm_id < 0:
+ osm_id = -osm_id
+ url += "relation"
+ elif geom_type == "ST_Point":
+ url += "node"
+ else:
+ url += "way"
+ return url + "/" + str(osm_id)
diff --git a/templates/_base.html b/templates/_base.html
index c425f0f..2f82d22 100644
--- a/templates/_base.html
+++ b/templates/_base.html
@@ -8,8 +8,7 @@
</head>
<body>
<header>
- <h1><a href="https://openinframap.org">OpenInfraMap</a>
- &rang; <a href="{{url_for('main')}}">Stats</a></h1>
+ <h1><a href="{{url_for('main')}}">OpenInfraMap</a>
{% if breadcrumbs %}
<h2>
{% for name, url in breadcrumbs %}
@@ -29,7 +28,7 @@
<footer>
Data <a href="https://www.openstreetmap.org/copyright">&copy; OpenStreetMap contributors, ODbL</a>.
International regions <a href="https://www.marineregions.org/disclaimer.php">&copy; MarineRegions.org, CC-BY</a>.
- Analysis &copy; OpenInfraMap, CC-BY.
+ Analysis <a href="{{url_for('copyright')}}">&copy; OpenInfraMap, CC-BY</a>.
</footer>
</body>
</html>
diff --git a/templates/about.html b/templates/about.html
new file mode 100644
index 0000000..af7c067
--- /dev/null
+++ b/templates/about.html
@@ -0,0 +1,79 @@
+{% extends "_base.html" %}
+{% block title %}About{% endblock %}
+{% set breadcrumbs = [('About', None)] %}
+{% block content -%}
+ <p class="lead"><a href="/">Open Infrastructure Map</a> is a view of the world's hidden infrastructure mapped in the
+ <a href="http://www.openstreetmap.org/">OpenStreetMap database</a>.</p>
+ <p>By and large, this data isn't exposed on the main OSM map, so I built
+ Open Infrastructure Map to visualise it.</p>
+
+ <h2>How do I contribute?</h2>
+ <p>If you want to edit the data and you're new to OpenStreetMap, check out
+ <a href="https://learnosm.org">learnOSM.</a></p>
+ <p>
+ If you already have some OSM experience and want to start tagging infrastructure things,
+ take a look at the tagging guidelines for
+ <a href="http://wiki.openstreetmap.org/wiki/Power">power</a> and <a href="http://wiki.openstreetmap.org/wiki/Telecoms">telecoms</a>.
+ </p>
+
+ <h2>How is OIM made?</h2>
+ <p>The following mess of tools and services make Open Infrastructure Map run:</p>
+ <ul>
+ <li><a href="https://www.postgresql.org/">Postgres</a>/<a href="http://postgis.net/">PostGIS</a> for data storage
+ <li><a href="https://imposm.org/">Imposm3</a> for filtering and importing the OSM data
+ <li><a href="http://tegola.io/">Tegola</a> for vector tile rendering and serving
+ <li>The <a href="https://github.com/MapLibre/maplibre-gl-js">MapLibre GL JS</a> web interface</li>
+ </ul>
+
+ <p>The background map data is kindly provided by <a href="https://www.maptiler.com/"><img width="150px" src="img/maptiler.png" alt="MapTiler"></a>.</p>
+
+ <h2>Where's the code?</h2>
+ <p>You can find some bits of OIM on the
+ <a href="https://github.com/openinframap/">openinframap Github organisation</a>.
+ More to come, soon.</p>
+
+ <h2>Who made this?</h2>
+ <p>I'm <a href="https://russ.garrett.co.uk">Russ</a>, and I like infrastructure.
+ Please don't contact me about copyright claims or similar, these should properly
+ be directed <a href="https://wiki.osmfoundation.org/wiki/Takedown_procedure">to
+ OpenStreetMap</a>.</p>
+
+ <h2>Get in touch</h2>
+ <p>If you want to get in touch with the OSM infrastructure mapping community, join
+ <a href="irc://irc.oftc.net/osm-infrastructure">#osm-infrastructure on irc.oftc.net</a>.
+
+ Join this channel with IRCCloud:
+ <a href="https://www.irccloud.com/invite?channel=%23osm-infrastructure&amp;hostname=irc.oftc.net&amp;port=6697&amp;ssl=1" target="_blank"><img src="https://www.irccloud.com/invite-svg?channel=%23osm-infrastructure&amp;hostname=irc.oftc.net&amp;port=6697&amp;ssl=1" height="18"></a>.</p>
+
+ <p>You can also follow <a href="https://twitter.com/openinframap">OpenInfraMap on Twitter</a>
+ for occasional status updates.</p>
+ <h2>Support OpenInfraMap</h2>
+ <p>OpenInfraMap is a personal side project which costs me around $1200/year to run. If you like
+ OpenInfraMap, you can chip in to help with these costs on Liberapay: <script src="https://liberapay.com/russss/widgets/button.js"></script>
+ <noscript><a href="https://liberapay.com/russss/donate"><img alt="Donate using Liberapay" src="https://liberapay.com/assets/widgets/donate.svg"></a></noscript>
+ </p>
+
+ <h2>How do I access the data?</h2>
+ <p>All the data currently displayed on OpenInfraMap is sourced directly from OpenStreetMap.</p>
+
+ <p>If you can consume vector data in Mapbox Vector Tiles format, you can fetch vector data directly
+ from the OpenInfraMap tile server using the <a href="/map.json">TileJSON file</a>.</p>
+
+ <p>If you need relatively small extracts of data, you can use
+ <a href="https://overpass-turbo.eu/">Overpass Turbo</a> to generate these in GeoJSON and
+ similar formats.</p>
+
+ <p>For larger amounts of data, you will need to fetch and process the raw OSM data directly,
+ which is relatively complex.</p>
+
+ <p>I can provide exports from the OpenInfraMap database, for which I charge a fee of
+ £85 to cover my time. More complex work will normally be billed at £100/hour although I am
+ happy to negotiate this based on the task. Please contact
+ <a href="mailto:[email protected]">[email protected]</a> if you are interested in this.</p>
+
+ <p>If you use this data, you will need to comply with the
+ <a href="https://www.openstreetmap.org/copyright">OpenStreetMap licensing terms</a>, which
+ require that you attribute OpenStreetMap. Attribution of "OpenInfraMap", and a link to this
+ website, would be appreciated but is not required.
+ </p>
+{% endblock %}
diff --git a/templates/copyright.html b/templates/copyright.html
new file mode 100644
index 0000000..b93e9d0
--- /dev/null
+++ b/templates/copyright.html
@@ -0,0 +1,24 @@
+{% extends "_base.html" %}
+{% block title %}Copyright{% endblock %}
+{% set breadcrumbs = [('Copyright', None)] %}
+{% block content -%}
+ <h3>Map data</h3>
+ <p>All map data on OpenInfraMap is open data from OpenStreetMap, and is licensed under
+ the Open Database License.</p>
+ <p>You are free to copy, distribute, transmit and adapt OpenStreetMap
+ data, as long as you credit OpenStreetMap and its contributors. If you alter or build upon the
+ data, you may distribute the result only under the same licence.</p>
+ <p><a href="https://www.openstreetmap.org/copyright">More information on the OpenStreetMap license</a>.</p>
+ <h3>Map design and analysis</h3>
+ <p>The design of OpenInfraMap, and any analysis, is copyright OpenInfraMap and is licensed under the
+ <a href="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International</a>
+ license.
+ </p>
+ <p>You are free to copy and use images of OpenInfraMap, and any analysis available on this site, as long as
+ you credit OpenInfraMap and provide a link back.</p>
+ <h3>Regions</h3>
+ <p>Data on exclusive economic zone boundaries, used in statistics and analysis, is copyright
+ <a href="https://www.marineregions.org/">marineregions.org</a> and is used under the Creative
+ Commons Attribution license.</p>
+
+{% endblock %}
diff --git a/templates/country.html b/templates/country.html
index b511977..c706899 100644
--- a/templates/country.html
+++ b/templates/country.html
@@ -1,5 +1,5 @@
{% extends "_base.html" %}
-{% set breadcrumbs = [(country, None)] %}
+{% set breadcrumbs = [('Stats', url_for('stats')), (country, None)] %}
{% block title %}{{country}}{% endblock %}
{% block content -%}
<p><strong>{{country}}</strong> has {{plant_stats.count}} power plants totalling {{plant_stats.output|power}} mapped on OpenStreetMap.</p>
diff --git a/templates/index.html b/templates/index.html
index bf0074f..92f8ed9 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -1,4 +1,5 @@
{% extends "_base.html" %}
+{% set breadcrumbs = [('Stats', None)] %}
{% block content -%}
<p>Select an area to view stats:</p>
<form>
@@ -29,7 +30,7 @@
if (optionFound) {
this.setCustomValidity("");
- window.location.href = "/area/" + this.value;
+ window.location.href = "/stats/area/" + this.value;
} else {
this.setCustomValidity("Please select a valid value.");
}
diff --git a/templates/plants_country.html b/templates/plants_country.html
index 6712b69..daceca3 100644
--- a/templates/plants_country.html
+++ b/templates/plants_country.html
@@ -1,10 +1,10 @@
{% extends "_base.html" %}
-{% set breadcrumbs = [(country, url_for('country', country=country)), ("Power Plants", None)] %}
+{% set breadcrumbs = [('Stats', url_for('stats')), (country, url_for('country', country=country)), ("Power Plants", None)] %}
{% block title %}{{country}} Power Plants{% endblock %}
{% block content -%}
{% set english_name = false %}
-{% if country not in ('United Kingdom', 'United States', 'Canada', 'Australia', 'New Zealand', 'Ireland') %}
+{% if country not in ('United Kingdom', 'United States', 'Canada', 'Australia', 'New Zealand', 'Ireland', 'Alaska', 'Hawaii') %}
{% set english_name = true %}
{% endif %}
diff --git a/util.py b/util.py
new file mode 100644
index 0000000..8ee7202
--- /dev/null
+++ b/util.py
@@ -0,0 +1,33 @@
+from functools import wraps
+from starlette.exceptions import HTTPException
+
+from config import database
+
+
+def country_required(func):
+ @wraps(func)
+ async def wrap_country(request):
+ country = request.path_params["country"]
+
+ res = await database.fetch_one(
+ query='SELECT gid, "union" FROM countries.country_eez WHERE "union" = :union',
+ values={"union": country},
+ )
+
+ if not res:
+ raise HTTPException(404)
+ return await func(request, res)
+
+ return wrap_country
+
+
+def cache_for(lifetime):
+ def cache_for_inner(func):
+ @wraps(func)
+ async def wrap_cache(*args, **kwargs):
+ response = await func(*args, **kwargs)
+ response.headers['Cache-Control'] = f"public, max-age={lifetime}"
+ return response
+
+ return wrap_cache
+ return cache_for_inner