df-web/main.py

61 lines
1.7 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-21 03:06:49 -08:00
data.append({"route": route})
return data
2022-11-20 07:37:22 -08:00
@app.post("/route")
async def post_route(route: Route):
2022-11-21 03:06:49 -08:00
print(route)
as_dict = route.dict()['route']
as_dict['id'] = "astoehsteaohus"
2022-11-20 19:10:02 -08:00
insert = text(
"""INSERT INTO
2022-11-21 03:06:49 -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[]),
CAST(:dustPoints as jsonb[]))"""
).bindparams(**as_dict)
2022-11-20 07:37:22 -08:00
engine.execute(insert)
2022-11-21 03:06:49 -08:00
return HTTPStatus.OK