ticketfrei4/src/ticketfrei3/application.py

77 lines
2.7 KiB
Python
Raw Normal View History

from blacksheep.client import ClientSession
from blacksheep.server import Application
import json
from ticketfrei3.models import Fahrt, Halt, Haltestelle
from tortoise import Tortoise
from tortoise.transactions import in_transaction
app = Application()
async def init(app: Application) -> None:
await Tortoise.init(
db_url="sqlite://db.sqlite3", modules={"models": ["ticketfrei3.models"]}
)
await Tortoise.generate_schemas()
app.services.add_instance(ClientSession(connection_timeout=30))
app.on_start += init
async def finalize(app: Application) -> None:
client = app.service_provider.get(ClientSession)
await client.close()
await Tortoise.close_connections()
app.on_stop += finalize
@app.route("/fetch_haltestellen")
async def fetch_haltestellen(client: ClientSession) -> None:
response = await client.get("https://start.vag.de/dm/api/v1/haltestellen.json/vag")
haltestellen = json.loads(await response.text())
for haltestelle in haltestellen["Haltestellen"]:
if await Haltestelle.exists(id=haltestelle["VGNKennung"]):
continue
await Haltestelle.create(
id=haltestelle["VGNKennung"],
name=haltestelle["Haltestellenname"],
longitude=haltestelle.get("Longitude"),
latitude=haltestelle.get("Latitude"),
)
@app.route("/fetch_fahrten")
async def fetch_fahrten(client: ClientSession) -> None:
for zweig in ("bus", "tram", "ubahn"):
response = await client.get(
"https://start.vag.de/dm/api/v1/fahrten.json/%s?timespan=120" % zweig
)
fahrten = json.loads(await response.text())
for fahrt in fahrten["Fahrten"]:
if await Fahrt.exists(id=fahrt["Fahrtnummer"]):
continue
async with in_transaction() as connection:
fahrt = Fahrt(id=fahrt["Fahrtnummer"], linie=fahrt["Linienname"])
await fahrt.save(using_db=connection)
response = await client.get(
"https://start.vag.de/dm/api/v1/fahrten.json/%s/%d"
% (zweig, fahrt.id)
)
details = json.loads(await response.text())
for halt in details["Fahrtverlauf"]:
haltestelle = (
await Haltestelle.filter(id=halt["VGNKennung"])
.using_db(connection)
.first()
)
await Halt(
fahrt=fahrt,
haltestelle=haltestelle,
ankunft=halt.get("AnkunftszeitIst"),
abfahrt=halt.get("AbfahrtszeitIst"),
).save(using_db=connection)