53 lines
1.9 KiB
Python
53 lines
1.9 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from fastapi.encoders import jsonable_encoder
|
|
from app.schemas import QueryPayload, ExecutePayload
|
|
from app.db import get_engine, run_query, run_execute
|
|
|
|
app = FastAPI(title="Polo informatico SQL API", version="1.0.0")
|
|
|
|
ALLOWED_ORIGINS = [
|
|
"http://192.168.10.94/",
|
|
"http://192.168.10.94:8080/",
|
|
"http://localhost:8080",
|
|
"http://localhost"
|
|
]
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=ALLOWED_ORIGINS,
|
|
allow_credentials=False, # set True only if you use cookies/auth
|
|
allow_methods=["GET", "POST", "OPTIONS"], # include OPTIONS for preflight
|
|
allow_headers=["*"], # or list specific headers
|
|
max_age=86400, # cache preflight for 1 day
|
|
)
|
|
|
|
def _trim_strings(obj):
|
|
if isinstance(obj, str):
|
|
return obj.strip()
|
|
if isinstance(obj, list):
|
|
return [_trim_strings(x) for x in obj]
|
|
if isinstance(obj, dict):
|
|
return {k: _trim_strings(v) for k, v in obj.items()}
|
|
return obj
|
|
|
|
@app.post("/query")
|
|
async def query(payload: QueryPayload):
|
|
try:
|
|
engine = get_engine(payload)
|
|
result = await run_query(engine, payload.sql, payload.params, payload.max_rows)
|
|
result = _trim_strings(result)
|
|
return JSONResponse(content=jsonable_encoder(result))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
@app.post("/execute")
|
|
async def execute(payload: ExecutePayload):
|
|
try:
|
|
engine = get_engine(payload)
|
|
result = await run_execute(engine, payload.sql, payload.params, payload.autocommit)
|
|
result = _trim_strings(result)
|
|
return JSONResponse(content=jsonable_encoder(result))
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=str(e)) |