51 lines
1.3 KiB
Python
51 lines
1.3 KiB
Python
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI, Depends
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from database import engine, get_db, Base
|
|
from models import Counter
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
yield
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["http://localhost:3000"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
async def get_or_create_counter(db: AsyncSession) -> Counter:
|
|
result = await db.execute(select(Counter).where(Counter.id == 1))
|
|
counter = result.scalar_one_or_none()
|
|
if not counter:
|
|
counter = Counter(id=1, value=0)
|
|
db.add(counter)
|
|
await db.commit()
|
|
await db.refresh(counter)
|
|
return counter
|
|
|
|
|
|
@app.get("/api/counter")
|
|
async def get_counter(db: AsyncSession = Depends(get_db)):
|
|
counter = await get_or_create_counter(db)
|
|
return {"value": counter.value}
|
|
|
|
|
|
@app.post("/api/counter/increment")
|
|
async def increment_counter(db: AsyncSession = Depends(get_db)):
|
|
counter = await get_or_create_counter(db)
|
|
counter.value += 1
|
|
await db.commit()
|
|
return {"value": counter.value}
|
|
|