🎉 Initialize FastAPI boilerplate

This commit is contained in:
Finn Christiansen 2023-08-10 22:46:36 +02:00
parent 06ffc42ec6
commit 248d73806f
21 changed files with 638 additions and 0 deletions

0
app/__init__.py Normal file
View file

108
app/alembic.ini Normal file
View file

@ -0,0 +1,108 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = driver://user:pass@localhost/dbname
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

14
app/config.py Normal file
View file

@ -0,0 +1,14 @@
import os
from dotenv import load_dotenv
from pathlib import Path
env_path = Path('..') / '.env'
load_dotenv(dotenv_path=env_path)
class Settings:
app_name: str = "Awesome API"
admin_email: str
items_per_user: int = 50
DATABASE_URL: str = os.getenv("DATABASE_URL")

1
app/crud/__init__.py Normal file
View file

@ -0,0 +1 @@
from .item import item

70
app/crud/base.py Normal file
View file

@ -0,0 +1,70 @@
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from fastapi import HTTPException
from database import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: Type[ModelType]):
"""
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
* `schema`: A Pydantic model (schema) class
"""
self.model = model
def get(self, db: Session, id: Any) -> Optional[ModelType]:
result = db.query(self.model).filter(self.model.id == id).first()
if not result:
raise HTTPException(status_code=404, detail="Item not found")
return result
def get_multi(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data) # type: ignore
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self,
db: Session,
*,
db_obj: ModelType,
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
) -> ModelType:
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

40
app/crud/item.py Normal file
View file

@ -0,0 +1,40 @@
from fastapi import HTTPException
from sqlalchemy.orm import Session
from models import Item
from schemas.schemas import ItemCreate, ItemUpdate
from crud.base import CRUDBase
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
pass
# def get_item(self, db: Session, item_id: int):
# item = db.query(Item).filter(Item.id == item_id).first()
# if not item:
# raise HTTPException(status_code=404, detail="Item not found")
# return item
# def get_items(self, db: Session, skip: int = 0, limit: int = 100):
# return db.query(Item).offset(skip).limit(limit).all()
# def create_item(self, db: Session, item: ItemCreate):
# db_item = Item(title=item.title, description=item.description)
# db.add(db_item)
# db.commit()
# db.refresh(db_item)
# return db_item
# def update_item(self, db: Session, item: ItemUpdate):
# db_item = Item(title=item.title, description=item.description)
# db.add(db_item)
# db.commit()
# db.refresh(db_item)
# return db_item
# def delete_item(self, db: Session, item_id: int):
# db.query(Item).filter(Item.id == item_id).first().delete()
# db.commit()
# return
item = CRUDItem(Item)

15
app/database.py Normal file
View file

@ -0,0 +1,15 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import config
SQLALCHEMY_DATABASE_URL = config.Settings.DATABASE_URL
# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db"
print(SQLALCHEMY_DATABASE_URL)
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

51
app/main.py Normal file
View file

@ -0,0 +1,51 @@
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from schemas import schemas
import database
import crud
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"]
)
# Dependency
def get_db():
db = database.SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}", response_model=schemas.Item)
async def get_item(*, db: Session = Depends(get_db), item_id: int):
return crud.item.get(db, item_id)
@app.get("/items/", response_model=list[schemas.Item])
async def get_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
return crud.item.get_multi(db, skip=skip, limit=limit)
@app.post("/items/", response_model=schemas.Item)
async def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)):
return crud.item.create(db=db, item=item)
@app.put("/items/{item_id}", response_model=schemas.ItemUpdate)
async def update_item(item: schemas.ItemUpdate, db: Session = Depends(get_db)):
return crud.item.update(db=db, item=item)
@app.delete("/items/{item_id}")
async def delete_item(*, item: schemas.ItemUpdate, db: Session = Depends(get_db), item_id: int):
return crud.remove(item_id)

1
app/models/__init__.py Normal file
View file

@ -0,0 +1 @@
from .item import Item

11
app/models/item.py Normal file
View file

@ -0,0 +1,11 @@
from sqlalchemy import Boolean, Column, Integer, String
from database import Base
class Item(Base):
__tablename__ = "item"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String, index=True)

18
app/requirements.txt Normal file
View file

@ -0,0 +1,18 @@
alembic==1.11.2
annotated-types==0.5.0
anyio==3.7.1
click==8.1.6
fastapi==0.101.0
greenlet==2.0.2
h11==0.14.0
idna==3.4
Mako==1.2.4
MarkupSafe==2.1.3
pydantic==2.1.1
pydantic_core==2.4.0
python-dotenv==1.0.0
sniffio==1.3.0
SQLAlchemy==2.0.19
starlette==0.27.0
typing_extensions==4.7.1
uvicorn==0.23.2

0
app/schemas/__init__.py Normal file
View file

21
app/schemas/schemas.py Normal file
View file

@ -0,0 +1,21 @@
from pydantic import BaseModel
class ItemBase(BaseModel):
title: str
description: str | None = None
class Item(ItemBase):
id: int
class Config:
from_attributes = True
class ItemCreate(ItemBase):
pass
class ItemUpdate(ItemBase):
pass

BIN
app/sql_app.db Normal file

Binary file not shown.