tcl-filtrage/main.py

61 lines
1.9 KiB
Python
Raw Normal View History

2021-11-09 12:33:52 +01:00
import enum
2021-11-09 13:56:42 +01:00
import re
2021-11-09 13:44:40 +01:00
from typing import Any, DefaultDict, List, Optional
2021-11-09 12:33:52 +01:00
import httpx
2021-11-09 12:33:18 +01:00
from fastapi import FastAPI, HTTPException
2021-11-09 12:50:21 +01:00
from fastapi.params import Header, Path
2021-11-09 12:33:18 +01:00
from pydantic import BaseModel
app = FastAPI()
2021-11-09 12:33:52 +01:00
2021-11-09 12:33:18 +01:00
class Passage(BaseModel):
ligne: str
2021-11-09 13:44:40 +01:00
delais: List[str]
2021-11-09 12:33:18 +01:00
2021-11-09 12:33:52 +01:00
2021-11-09 12:33:18 +01:00
class Passages(BaseModel):
passages: List[Passage]
2021-11-09 13:44:40 +01:00
stop_id: int
2021-11-09 12:33:18 +01:00
2021-11-09 12:33:52 +01:00
2021-11-09 12:33:18 +01:00
@app.get("/stop/{stop_id}", response_model=Passages)
2021-11-09 12:50:21 +01:00
async def stop(
stop_id: int = Path(
None,
description="Stop id to monitor. Can be obtained using https://data.grandlyon.com/jeux-de-donnees/points-arret-reseau-transports-commun-lyonnais/donnees",
),
authorization: Optional[str] = Header(
None,
alias="Authorization",
description="Basic auth for remote API (data grand lyon)",
),
):
2021-11-09 12:33:18 +01:00
if authorization is None:
raise HTTPException(status_code=401, detail="Not authenticated")
2021-11-09 12:33:52 +01:00
headers = {"Authorization": authorization}
2021-11-09 12:33:18 +01:00
async with httpx.AsyncClient(headers=headers) as client:
2021-11-09 12:33:52 +01:00
res = await client.get(
"https://download.data.grandlyon.com/ws/rdata/tcl_sytral.tclpassagearret/all.json?maxfeatures=-1"
)
2021-11-09 12:33:18 +01:00
if res.status_code != 200:
2021-11-09 12:33:52 +01:00
raise HTTPException(
status_code=res.status_code,
detail="HTTP error during call to remote API",
)
2021-11-09 13:44:40 +01:00
passages = DefaultDict(list)
2021-11-09 12:33:18 +01:00
for passage in res.json().get("values"):
if passage.get("id") == stop_id:
2021-11-09 13:56:42 +01:00
ligne = passage.get("ligne")
ligne = re.sub(
"[A-Z]$", "", ligne
) # Remove letter suffix to group by commercial line name
passages[ligne].append(passage.get("delaipassage"))
2021-11-09 13:44:40 +01:00
passages_list = []
for ligne, delais in passages.items():
passages_list.append(Passage(ligne=ligne, delais=delais))
return Passages(passages=passages_list, stop_id=stop_id)