This commit is contained in:
2025-05-26 21:57:57 +03:00
commit dd0be3e257
7 changed files with 114 additions and 0 deletions

0
app/__init__.py Normal file
View File

16
app/database.py Normal file
View File

@@ -0,0 +1,16 @@
from sqlmodel import create_engine, SQLModel, Session
from dotenv import load_dotenv
import os
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
if not DATABASE_URL:
raise ValueError("DATABASE_URL environment variable is not set")
engine = create_engine(DATABASE_URL, echo=True)
SQLModel.metadata.create_all(engine)
def get_session():
with Session(engine) as session:
yield session

42
app/main.py Normal file
View File

@@ -0,0 +1,42 @@
from fastapi import FastAPI
from sqlmodel import SQLModel, Session, select
from .database import engine
from .models import Author, Book
app = FastAPI()
@app.on_event("startup")
def on_startup():
SQLModel.metadata.create_all(engine)
@app.get("/")
async def read_root():
return {"message": "Hello, FastAPI with SQLModel and PostgreSQL!"}
@app.post("/authors/")
def create_author(author: Author):
with Session(engine) as session:
session.add(author)
session.commit()
session.refresh(author)
return author
@app.get("/authors/")
def read_authors():
with Session(engine) as session:
authors = session.exec(select(Author)).all()
return authors
@app.post("/books/")
def create_book(book: Book):
with Session(engine) as session:
session.add(book)
session.commit()
session.refresh(book)
return book
@app.get("/books/")
def read_books():
with Session(engine) as session:
books = session.exec(select(Book)).all()
return books

18
app/models.py Normal file
View File

@@ -0,0 +1,18 @@
from typing import Optional, List
from sqlmodel import SQLModel, Field, Relationship
class AuthorBookLink(SQLModel, table=True):
author_id: int | None = Field(default=None, foreign_key="author.id", primary_key=True)
book_id: int | None = Field(default=None, foreign_key="book.id", primary_key=True)
class Author(SQLModel, table=True):
id: Optional[int] = Field(primary_key=True, index=True)
name: str
books: List["Book"] = Relationship(back_populates="authors", link_model=AuthorBookLink)
class Book(SQLModel, table=True):
id: Optional[int] = Field(primary_key=True, index=True)
title: str
description: str
authors: List[Author] = Relationship(back_populates="books", link_model=AuthorBookLink)