-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
51 lines (40 loc) · 1.62 KB
/
main.py
File metadata and controls
51 lines (40 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
import pandas as pd
from sqlalchemy import create_engine, MetaData, Table, Column, Integer
from sqlalchemy.types import JSON as SAJSON
from sqlalchemy import select
app = FastAPI(title="Excel API")
engine = create_engine("sqlite:///data.db", connect_args={"check_same_thread": False})
metadata = MetaData()
records = Table(
"records", metadata,
Column("id", Integer, primary_key=True, autoincrement=True),
Column("data", SAJSON, nullable=False)
)
metadata.create_all(engine)
from io import BytesIO
from fastapi import HTTPException
@app.post("/import")
async def import_excel(file: UploadFile = File(...)):
# Fayl formatını yoxla
if not (file.filename.endswith(".xls") or file.filename.endswith(".xlsx")):
raise HTTPException(status_code=400, detail="Excel formatı olmalıdır")
try:
# Faylı BytesIO ilə oxumaq — ən stabil üsuldur
contents = await file.read()
df = pd.read_excel(BytesIO(contents))
except Exception as e:
raise HTTPException(status_code=500, detail=f"Excel faylını oxumaqda səhv: {e}")
# NaN-ləri None elə
df = df.where(pd.notnull(df), None)
# Database-ə yaz
with engine.begin() as conn:
for row in df.to_dict(orient="records"):
conn.execute(records.insert().values(data=row))
return {"ok": True, "rows": len(df)}
@app.get("/records")
def get_all():
with engine.connect() as conn:
rows = conn.execute(select(records)).fetchall()
return {"records":[{"id":r.id,"data":r.data} for r in rows]}