df-web/main.py

57 lines
1.5 KiB
Python
Raw Normal View History

2022-11-20 07:37:22 -08:00
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
2022-11-20 19:10:02 -08:00
from sqlalchemy import create_engine, text
import psycopg2.extras
from psycopg2.extensions import AsIs, register_adapter
2022-11-20 07:37:22 -08:00
from dataclasses import dataclass
2022-11-20 19:10:02 -08:00
from sqlalchemy.dialects.postgresql import JSONB
2022-11-20 07:37:22 -08:00
app = FastAPI()
2022-11-20 19:10:02 -08:00
engine = create_engine("postgresql://postgres?host=/home/anish/usr/df-web/postgres/")
2022-11-20 07:37:22 -08:00
conn = engine.connect()
2022-11-20 19:10:02 -08:00
psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)
2022-11-20 07:37:22 -08:00
2022-11-20 19:10:02 -08:00
class vector3(BaseModel):
2022-11-20 07:37:22 -08:00
x: float
y: float
z: float
class Route(BaseModel):
id: str
creatorName: str
2022-11-20 19:10:02 -08:00
dustPoints: list # List[Vector3]
checkpoints: list # List[Vector3]
startLocation: dict # Vector3
endLocation: dict # Vector3
creationDate: str
2022-11-20 07:37:22 -08:00
@app.get("/route")
async def get_route():
select = "SELECT * FROM routes"
result = engine.execute(select)
2022-11-20 19:10:02 -08:00
data = []
2022-11-20 07:37:22 -08:00
for route in result:
2022-11-20 19:10:02 -08:00
data.append(route)
return {"data": data}
2022-11-20 07:37:22 -08:00
@app.post("/route")
async def post_route(route: Route):
as_dict = route.dict()
2022-11-20 19:10:02 -08:00
insert = text(
"""INSERT INTO
routes (id, creatorName, creationDate, startLocation, endLocation, checkpoints, dustPoints)
VALUES
(:id, :creatorName, creationDate
CAST(:startLocation as jsonb),
CAST(:endLocation as jsonb),
CAST(:checkpoints as jsonb[]),
CAST(:dustPoints as jsonb[]))"""
).bindparams(**as_dict)
2022-11-20 07:37:22 -08:00
engine.execute(insert)
return