with some tests
This commit is contained in:
parent
a764c92a0b
commit
0995e1cc77
18 changed files with 3020 additions and 16 deletions
|
|
@ -1,7 +1,21 @@
|
|||
from fastapi import FastAPI
|
||||
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
|
||||
|
||||
app = FastAPI()
|
||||
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,
|
||||
|
|
@ -11,7 +25,27 @@ app.add_middleware(
|
|||
)
|
||||
|
||||
|
||||
@app.get("/api/hello")
|
||||
def hello():
|
||||
return {"message": "Hello from FastAPI"}
|
||||
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}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue