diff --git a/database.py b/database.py new file mode 100644 index 0000000..ba88138 --- /dev/null +++ b/database.py @@ -0,0 +1,15 @@ +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine +from sqlalchemy.orm import sessionmaker + +DATABASE_URL = "sqlite+aiosqlite:///./test.db" + +engine= create_async_engine( + DATABASE_URL, + echo=True +) + +SessionLocal = sessionmaker( + bind=engine, + class_=AsyncSession, + expire_on_commit=False +) \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..1a6e02d --- /dev/null +++ b/main.py @@ -0,0 +1,55 @@ +from fastapi import FastAPI, Depends, HTTPException +from sqlalchemy.ext.asyncio import AsyncSession +from sqlalchemy.future import select +from pydantic import BaseModel +from typing import List + +from models import Base, Item as ItemModel +from database import engine, SessionLocal + +app = FastAPI() + +# Create tables +@app.on_event("startup") +async def on_startup(): + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + +class ItemCreate(BaseModel): + name: str + description: str = None + +class ItemRead(ItemCreate): + id: int + + class Config: + orm_mode = True + +async def get_session() -> AsyncSession: + async with SessionLocal() as session: + yield session + +@app.get("/") +def read_root(): + return "TODO app" + +@app.post("/items/", response_model=ItemRead) +async def create_item(item: ItemCreate, session: AsyncSession = Depends(get_session)): + return "todo" + +@app.get("/items/", response_model=List[ItemRead]) +async def read_items(session: AsyncSession = Depends(get_session)): + result = await session.execute(select(ItemModel)) + return result.scalars().all() + +@app.get("/items/{item_id}", response_model=ItemRead) +async def read_item(item_id: int, session: AsyncSession = Depends(get_session)): + return "todo" + +@app.put("/items/{item_id}", response_model=ItemRead) +async def update_item(item_id: int, item: ItemCreate, session: AsyncSession = Depends(get_session)): + return "todo" + +@app.delete("/items/{item_id}") +async def delete_item(item_id: int, session: AsyncSession = Depends(get_session)): + return "todo" \ No newline at end of file diff --git a/models.py b/models.py new file mode 100644 index 0000000..21bb708 --- /dev/null +++ b/models.py @@ -0,0 +1,10 @@ +from sqlalchemy import Column, Integer, String +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() + +class Item(Base): + __tablename__ = "items" + id = Column(Integer, primary_key=True, index=True) + name = Column(String, index=True) + description = Column(String, nullable=True) \ No newline at end of file diff --git a/test.db b/test.db new file mode 100644 index 0000000..0d4a1bb Binary files /dev/null and b/test.db differ