df-web/main.py

67 lines
1.8 KiB
Python
Raw Normal View History

2022-11-20 07:37:22 -08:00
from fastapi import FastAPI
from pydantic import BaseModel
2022-11-21 03:06:49 -08:00
from http import HTTPStatus
2022-11-20 07:37:22 -08:00
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):
2022-11-21 03:06:49 -08:00
route: dict
# id: str
# creatorName: str
# 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-23 05:26:58 -08:00
data.append(route)
2022-11-21 03:06:49 -08:00
return data
2022-11-20 07:37:22 -08:00
@app.post("/route")
2022-11-23 05:26:58 -08:00
async def post_route(route: dict):
2022-11-21 03:06:49 -08:00
print(route)
2022-11-23 05:26:58 -08:00
# as_dict = route.dict()
2022-11-20 19:10:02 -08:00
insert = text(
"""INSERT INTO
2022-11-23 05:26:58 -08:00
routes (id, "creatorName", "creationDate", name, "creatorCharacter", "startLocation", "endLocation", checkpoints, dustpoints)
2022-11-20 19:10:02 -08:00
VALUES
2022-11-21 03:06:49 -08:00
(:id, :creatorName, :creationDate, :name, :creatorCharacter,
2022-11-20 19:10:02 -08:00
CAST(:startLocation as jsonb),
CAST(:endLocation as jsonb),
CAST(:checkpoints as jsonb[]),
2022-11-23 05:26:58 -08:00
CAST(:dustpoints as jsonb[]))"""
).bindparams(**route)
2022-11-20 07:37:22 -08:00
engine.execute(insert)
2022-11-21 03:06:49 -08:00
return HTTPStatus.OK
2022-11-23 05:26:58 -08:00
@app.get("/route/delete")
async def delete_routes():
delete = text("TRUNCATE TABLE routes")
engine.execute(delete)
return HTTPStatus.OK