|
2 | 2 | app.main.py |
3 | 3 | """ |
4 | 4 | import os |
| 5 | +import logging |
5 | 6 | import datetime as dt |
6 | 7 | from typing import Dict, List |
7 | 8 |
|
8 | 9 | import fastapi |
9 | 10 | import pydantic |
10 | 11 | import uvicorn |
11 | 12 |
|
| 13 | +from .data import data_source |
12 | 14 |
|
13 | 15 | # ################################# |
14 | 16 | # Models |
@@ -80,16 +82,33 @@ class Location(pydantic.BaseModel): |
80 | 82 | ####################### |
81 | 83 |
|
82 | 84 |
|
| 85 | +# TODO this could probably just be a FastAPI dependency |
| 86 | +@APP.middleware("http") |
| 87 | +async def add_datasource(request: fastapi.Request, call_next): |
| 88 | + """Attach the data source to the request.state.""" |
| 89 | + source = request.query_params.get("source", default="jhu") |
| 90 | + request.state.source = data_source(source) |
| 91 | + LOGGER.info(f"source: {request.state.source.__class__.__name__}") |
| 92 | + response = await call_next(request) |
| 93 | + return response |
| 94 | + |
| 95 | + |
83 | 96 | # ################ |
84 | 97 | # Routes |
85 | 98 | # ################ |
86 | 99 |
|
87 | 100 |
|
88 | 101 | @APP.get("/latest", response_model=Latest) |
89 | | -def get_latest(): |
| 102 | +def get_latest(request: fastapi.Request): |
90 | 103 | """Getting latest amount of total confirmed cases, deaths, and recoveries.""" |
91 | | - sample_data = {"latest": {"confirmed": 197146, "deaths": 7905, "recovered": 80840}} |
92 | | - return sample_data |
| 104 | + locations = request.state.source.get_all() |
| 105 | + return { |
| 106 | + "latest": { |
| 107 | + "confirmed": sum(map(lambda location: location.confirmed, locations)), |
| 108 | + "deaths": sum(map(lambda location: location.deaths, locations)), |
| 109 | + "recovered": sum(map(lambda location: location.recovered, locations)), |
| 110 | + } |
| 111 | + } |
93 | 112 |
|
94 | 113 |
|
95 | 114 | @APP.get("/locations", response_model=AllLocations) |
|
0 commit comments