forked from openinframap/openinframap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
290 lines (244 loc) · 8.96 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
from starlette.responses import PlainTextResponse, RedirectResponse
from starlette.applications import Starlette
from starlette.templating import Jinja2Templates
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from starlette.exceptions import HTTPException
from template_functions import (
format_power,
osm_link,
country_name,
format_length,
format_voltage,
format_percent,
)
from config import database, config
from util import cache_for, country_required
from sitemap import sitemap
from data import (
get_countries,
stats_power_line,
get_plant,
get_plant_generator_summary,
get_wikidata,
get_commons_thumbnail,
)
DEBUG = config("DEBUG", cast=bool, default=False)
templates = Jinja2Templates(directory="templates")
templates.env.filters["power"] = format_power
templates.env.filters["distance"] = format_length
templates.env.filters["voltage"] = format_voltage
templates.env.filters["percent"] = format_percent
templates.env.filters["country_name"] = country_name
templates.env.globals["osm_link"] = osm_link
app = Starlette(
debug=DEBUG,
on_startup=[database.connect],
on_shutdown=[database.disconnect],
routes=[
Mount("/static", app=StaticFiles(directory="static"), name="static"),
Route("/sitemap.xml", sitemap),
],
)
@app.route("/")
async def main(request):
# Dummy response - this endpoint is served statically in production from the webpack build
return PlainTextResponse("")
@app.route("/about")
@cache_for(3600)
async def about(request):
return templates.TemplateResponse("about.html", {"request": request})
@app.route("/about/exports")
@cache_for(3600)
async def exports(request):
return RedirectResponse("https://www.infrageomatics.com/products")
@app.route("/copyright")
@cache_for(3600)
async def copyright(request):
return templates.TemplateResponse("copyright.html", {"request": request})
@app.route("/stats")
@cache_for(86400)
async def stats(request):
power_lines = await stats_power_line()
return templates.TemplateResponse(
"index.html",
{
"request": request,
"countries": await get_countries(),
"power_lines": power_lines,
},
)
@app.route("/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(*)
FROM power_plant
WHERE ST_Contains(
(SELECT ST_Transform(geom, 3857) FROM countries.country_eez where gid = :gid),
geometry)
AND tags -> 'construction:power' IS NULL
""",
values={"gid": country["gid"]},
)
plant_source_stats = await database.fetch_all(
query="""SELECT first_semi(source) AS source, sum(convert_power(output)) AS output, count(*)
FROM power_plant
WHERE ST_Contains(
(SELECT ST_Transform(geom, 3857) FROM countries.country_eez WHERE gid = :gid),
geometry)
AND tags -> 'construction:power' IS NULL
GROUP BY first_semi(source)
ORDER BY SUM(convert_power(output)) DESC NULLS LAST""",
values={"gid": country["gid"]},
)
power_lines = await stats_power_line(country["union"])
return templates.TemplateResponse(
"country.html",
{
"request": request,
"country": country["union"],
"plant_stats": plant_stats._mapping,
"plant_source_stats": plant_source_stats,
"power_lines": power_lines,
"canonical": request.url_for("country", country=country["union"]),
},
)
@app.route("/stats/area/{country}/plants")
@country_required
@cache_for(3600)
async def plants_country(request, country):
gid = country[0]
plants = await database.fetch_all(
query="""SELECT osm_id, name, tags->'name:en' AS name_en, tags->'wikidata' AS wikidata,
tags->'plant:method' AS method, tags->'operator' AS operator,
convert_power(output) AS output,
source, ST_GeometryType(geometry) AS geom_type
FROM power_plant
WHERE ST_Contains(
(SELECT ST_Transform(geom, 3857) FROM countries.country_eez WHERE gid = :gid),
geometry)
AND tags -> 'construction:power' IS NULL
ORDER BY convert_power(output) DESC NULLS LAST, name ASC NULLS LAST """,
values={"gid": gid},
)
source = None
if "source" in request.query_params:
source = request.query_params["source"].lower()
plants = [
plant for plant in plants if source in plant["source"].lower().split(";")
]
min_output = None
if "min_output" in request.query_params:
try:
min_output = int(request.query_params["min_output"])
plants = [
plant
for plant in plants
if plant["output"] and plant["output"] >= min_output
]
except ValueError:
pass
return templates.TemplateResponse(
"plants_country.html",
{
"request": request,
"plants": plants,
"country": country["union"],
"source": source,
"min_output": min_output,
# Canonical URL for all plants without the source filter, to avoid confusing Google.
"canonical": request.url_for("plants_country", country=country["union"]),
},
)
@app.route("/stats/area/{country}/plants/construction")
@country_required
@cache_for(3600)
async def plants_construction_country(request, country):
gid = country[0]
plants = await database.fetch_all(
query="""SELECT osm_id, name, tags->'name:en' AS name_en, tags->'wikidata' AS wikidata,
tags->'plant:method' AS method, tags->'operator' AS operator,
tags->'start_date' AS start_date,
convert_power(output) AS output,
source, ST_GeometryType(geometry) AS geom_type
FROM power_plant
WHERE ST_Contains(
(SELECT ST_Transform(geom, 3857) FROM countries.country_eez WHERE gid = :gid),
geometry)
AND tags -> 'construction:power' IS NOT NULL
ORDER BY convert_power(output) DESC NULLS LAST, name ASC NULLS LAST """,
values={"gid": gid},
)
return templates.TemplateResponse(
"plants_country.html",
{
"construction": True,
"request": request,
"plants": plants,
"country": country["union"],
},
)
@app.route("/stats/object/plant/{id}")
@cache_for(86400)
async def stats_object(request):
try:
id = int(request.path_params["id"])
except ValueError:
raise HTTPException(400)
res = await database.fetch_one(
"""SELECT country_eez."union" FROM power_plant, countries.country_eez WHERE
ST_Contains(ST_Transform(country_eez.geom, 3857), geometry)
AND power_plant.osm_id = :id""",
values={"id": id},
)
if not res:
raise HTTPException(404)
return RedirectResponse(
request.url_for("plant_detail", country=res["union"], id=id)
)
@app.route("/stats/area/{country}/plants/{id}")
@country_required
@cache_for(3600)
async def plant_detail(request, country):
try:
plant_id = int(request.path_params["id"])
except ValueError:
raise HTTPException(404, "Invalid plant ID")
plant = await get_plant(plant_id, country["gid"])
if plant is None:
raise HTTPException(404, "Nonexistent power plant")
generator_summary = await get_plant_generator_summary(plant_id)
if "wikidata" in plant["tags"]:
wd = await get_wikidata(plant["tags"]["wikidata"])
else:
wd = None
image_data = None
if (
wd
and "P18" in wd["claims"]
and wd["claims"]["P18"][0]["mainsnak"]["datatype"] == "commonsMedia"
):
image_data = await get_commons_thumbnail(
wd["claims"]["P18"][0]["mainsnak"]["datavalue"]["value"], 400
)
ref_tags = []
for k, v in plant["tags"].items():
if k.startswith("ref:") or k in ["repd:id"]:
for split_val in v.split(";"):
ref_tags.append((k, split_val))
return templates.TemplateResponse(
"plant_detail.html",
{
"construction": True,
"plant": plant,
"request": request,
"generator_summary": generator_summary,
"country": country["union"],
"wikidata": wd,
"image_data": image_data,
"ref_tags": ref_tags,
},
)
import wikidata # noqa