Create FastAPI REST API with SQLite database and CRUD operations
- Set up project structure with FastAPI, SQLAlchemy, and Alembic - Create database models for User and Item - Implement CRUD operations for all models - Create API endpoints with validation - Add health check endpoint - Configure CORS middleware - Set up database migrations - Add comprehensive documentation in README
This commit is contained in:
parent
8a17446722
commit
7fdb11e728
141
README.md
141
README.md
@ -1,3 +1,140 @@
|
|||||||
# FastAPI Application
|
# Generic REST API Service
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A RESTful API built with FastAPI and SQLite, providing endpoints for user and item management.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- User management (create, read, update, delete)
|
||||||
|
- Item management (create, read, update, delete)
|
||||||
|
- SQLite database with SQLAlchemy ORM
|
||||||
|
- Alembic migrations
|
||||||
|
- OpenAPI documentation (Swagger UI)
|
||||||
|
- Password hashing with bcrypt
|
||||||
|
- Health check endpoint
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.8+
|
||||||
|
- FastAPI
|
||||||
|
- SQLAlchemy
|
||||||
|
- Alembic
|
||||||
|
- Uvicorn
|
||||||
|
- Pydantic
|
||||||
|
- Other dependencies as listed in requirements.txt
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
.
|
||||||
|
├── app/
|
||||||
|
│ ├── api/
|
||||||
|
│ │ ├── endpoints/
|
||||||
|
│ │ │ ├── items.py
|
||||||
|
│ │ │ └── users.py
|
||||||
|
│ │ ├── api.py
|
||||||
|
│ │ └── deps.py
|
||||||
|
│ ├── core/
|
||||||
|
│ │ ├── config.py
|
||||||
|
│ │ └── security.py
|
||||||
|
│ ├── crud/
|
||||||
|
│ │ ├── base.py
|
||||||
|
│ │ ├── crud_item.py
|
||||||
|
│ │ └── crud_user.py
|
||||||
|
│ ├── database/
|
||||||
|
│ │ ├── base.py
|
||||||
|
│ │ ├── base_class.py
|
||||||
|
│ │ └── session.py
|
||||||
|
│ ├── models/
|
||||||
|
│ │ ├── item.py
|
||||||
|
│ │ └── user.py
|
||||||
|
│ └── schemas/
|
||||||
|
│ ├── item.py
|
||||||
|
│ └── user.py
|
||||||
|
├── migrations/
|
||||||
|
│ └── versions/
|
||||||
|
│ └── 20240520_initial.py
|
||||||
|
├── storage/
|
||||||
|
│ └── db/
|
||||||
|
│ └── db.sqlite
|
||||||
|
├── alembic.ini
|
||||||
|
├── main.py
|
||||||
|
└── requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Clone the repository:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd genericrestapiservice
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Install dependencies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run database migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the Application
|
||||||
|
|
||||||
|
Start the application using Uvicorn:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000.
|
||||||
|
|
||||||
|
## API Documentation
|
||||||
|
|
||||||
|
- Swagger UI: http://localhost:8000/docs
|
||||||
|
- ReDoc: http://localhost:8000/redoc
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
- `GET /health` - Check the API health status
|
||||||
|
|
||||||
|
### Users
|
||||||
|
- `GET /api/v1/users/` - List all users
|
||||||
|
- `POST /api/v1/users/` - Create a new user
|
||||||
|
- `GET /api/v1/users/{user_id}` - Get user details
|
||||||
|
- `PUT /api/v1/users/{user_id}` - Update user information
|
||||||
|
- `DELETE /api/v1/users/{user_id}` - Delete a user
|
||||||
|
|
||||||
|
### Items
|
||||||
|
- `GET /api/v1/items/` - List all items
|
||||||
|
- `POST /api/v1/items/` - Create a new item
|
||||||
|
- `GET /api/v1/items/{id}` - Get item details
|
||||||
|
- `PUT /api/v1/items/{id}` - Update item information
|
||||||
|
- `DELETE /api/v1/items/{id}` - Delete an item
|
||||||
|
- `GET /api/v1/items/user/{owner_id}` - List all items owned by a specific user
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Database Migrations
|
||||||
|
|
||||||
|
Generate a new migration:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic revision -m "description"
|
||||||
|
```
|
||||||
|
|
||||||
|
Apply migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
Revert migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic downgrade -1
|
||||||
|
```
|
||||||
|
99
alembic.ini
Normal file
99
alembic.ini
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = migrations
|
||||||
|
|
||||||
|
# template used to generate migration files
|
||||||
|
# file_template = %%(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"
|
||||||
|
# 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. Valid values are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
version_path_separator = os # default: use os.pathsep
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
[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
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# App package initialization
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# API package initialization
|
7
app/api/api.py
Normal file
7
app/api/api.py
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.endpoints import items, users
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||||
|
api_router.include_router(items.router, prefix="/items", tags=["items"])
|
12
app/api/deps.py
Normal file
12
app/api/deps.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
|
||||||
|
from app.database.session import SessionLocal
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator:
|
||||||
|
try:
|
||||||
|
db = SessionLocal()
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
1
app/api/endpoints/__init__.py
Normal file
1
app/api/endpoints/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# API endpoints package initialization
|
112
app/api/endpoints/items.py
Normal file
112
app/api/endpoints/items.py
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
from typing import Any, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import schemas
|
||||||
|
from app.api import deps
|
||||||
|
from app.crud.crud_item import item
|
||||||
|
from app.crud.crud_user import user
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.Item])
|
||||||
|
def read_items(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve items.
|
||||||
|
"""
|
||||||
|
items = item.get_multi(db, skip=skip, limit=limit)
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.Item)
|
||||||
|
def create_item(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
item_in: schemas.ItemCreate,
|
||||||
|
owner_id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new item.
|
||||||
|
"""
|
||||||
|
owner = user.get(db, id=owner_id)
|
||||||
|
if not owner:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="Owner not found",
|
||||||
|
)
|
||||||
|
item_obj = item.create_with_owner(db=db, obj_in=item_in, owner_id=owner_id)
|
||||||
|
return item_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{id}", response_model=schemas.Item)
|
||||||
|
def read_item(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get item by ID.
|
||||||
|
"""
|
||||||
|
item_obj = item.get(db=db, id=id)
|
||||||
|
if not item_obj:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
return item_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{id}", response_model=schemas.Item)
|
||||||
|
def update_item(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
id: int,
|
||||||
|
item_in: schemas.ItemUpdate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update an item.
|
||||||
|
"""
|
||||||
|
item_obj = item.get(db=db, id=id)
|
||||||
|
if not item_obj:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
item_obj = item.update(db=db, db_obj=item_obj, obj_in=item_in)
|
||||||
|
return item_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{id}", response_model=schemas.Item)
|
||||||
|
def delete_item(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete an item.
|
||||||
|
"""
|
||||||
|
item_obj = item.get(db=db, id=id)
|
||||||
|
if not item_obj:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
item_obj = item.remove(db=db, id=id)
|
||||||
|
return item_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/user/{owner_id}", response_model=List[schemas.Item])
|
||||||
|
def read_items_by_owner(
|
||||||
|
owner_id: int,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve items by owner.
|
||||||
|
"""
|
||||||
|
owner = user.get(db, id=owner_id)
|
||||||
|
if not owner:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="Owner not found",
|
||||||
|
)
|
||||||
|
items = item.get_multi_by_owner(db=db, owner_id=owner_id, skip=skip, limit=limit)
|
||||||
|
return items
|
98
app/api/endpoints/users.py
Normal file
98
app/api/endpoints/users.py
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
from typing import Any, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import schemas
|
||||||
|
from app.api import deps
|
||||||
|
from app.crud.crud_user import user
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.User])
|
||||||
|
def read_users(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve users.
|
||||||
|
"""
|
||||||
|
users = user.get_multi(db, skip=skip, limit=limit)
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.User)
|
||||||
|
def create_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_in: schemas.UserCreate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new user.
|
||||||
|
"""
|
||||||
|
user_obj = user.get_by_email(db, email=user_in.email)
|
||||||
|
if user_obj:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The user with this email already exists in the system.",
|
||||||
|
)
|
||||||
|
user_obj = user.create(db, obj_in=user_in)
|
||||||
|
return user_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}", response_model=schemas.User)
|
||||||
|
def read_user_by_id(
|
||||||
|
user_id: int,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get a specific user by id.
|
||||||
|
"""
|
||||||
|
user_obj = user.get(db, id=user_id)
|
||||||
|
if not user_obj:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="User not found",
|
||||||
|
)
|
||||||
|
return user_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}", response_model=schemas.User)
|
||||||
|
def update_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_id: int,
|
||||||
|
user_in: schemas.UserUpdate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a user.
|
||||||
|
"""
|
||||||
|
user_obj = user.get(db, id=user_id)
|
||||||
|
if not user_obj:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="User not found",
|
||||||
|
)
|
||||||
|
user_obj = user.update(db, db_obj=user_obj, obj_in=user_in)
|
||||||
|
return user_obj
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}", response_model=schemas.User)
|
||||||
|
def delete_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_id: int,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete a user.
|
||||||
|
"""
|
||||||
|
user_obj = user.get(db, id=user_id)
|
||||||
|
if not user_obj:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="User not found",
|
||||||
|
)
|
||||||
|
user_obj = user.remove(db, id=user_id)
|
||||||
|
return user_obj
|
1
app/core/__init__.py
Normal file
1
app/core/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Core package initialization
|
16
app/core/config.py
Normal file
16
app/core/config.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
PROJECT_NAME: str = "Generic REST API Service"
|
||||||
|
ALLOWED_ORIGINS: List[str] = ["*"]
|
||||||
|
DATABASE_URL: str = "sqlite:////app/storage/db/db.sqlite"
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
env_file = ".env"
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
12
app/core/security.py
Normal file
12
app/core/security.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
|
return pwd_context.verify(plain_password, hashed_password)
|
||||||
|
|
||||||
|
|
||||||
|
def get_password_hash(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
1
app/crud/__init__.py
Normal file
1
app/crud/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# CRUD package initialization
|
66
app/crud/base.py
Normal file
66
app/crud/base.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
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 app.database.base_class 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]:
|
||||||
|
return db.query(self.model).filter(self.model.id == id).first()
|
||||||
|
|
||||||
|
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)
|
||||||
|
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
|
34
app/crud/crud_item.py
Normal file
34
app/crud/crud_item.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.item import Item
|
||||||
|
from app.schemas.item import ItemCreate, ItemUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]):
|
||||||
|
def create_with_owner(
|
||||||
|
self, db: Session, *, obj_in: ItemCreate, owner_id: int
|
||||||
|
) -> Item:
|
||||||
|
obj_in_data = jsonable_encoder(obj_in)
|
||||||
|
db_obj = self.model(**obj_in_data, owner_id=owner_id)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def get_multi_by_owner(
|
||||||
|
self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[Item]:
|
||||||
|
return (
|
||||||
|
db.query(self.model)
|
||||||
|
.filter(Item.owner_id == owner_id)
|
||||||
|
.offset(skip)
|
||||||
|
.limit(limit)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
item = CRUDItem(Item)
|
52
app/crud/crud_user.py
Normal file
52
app/crud/crud_user.py
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
from typing import Any, Dict, Optional, Union
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.user import UserCreate, UserUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
|
||||||
|
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
|
||||||
|
return db.query(User).filter(User.email == email).first()
|
||||||
|
|
||||||
|
def create(self, db: Session, *, obj_in: UserCreate) -> User:
|
||||||
|
db_obj = User(
|
||||||
|
email=obj_in.email,
|
||||||
|
hashed_password=get_password_hash(obj_in.password),
|
||||||
|
full_name=obj_in.full_name,
|
||||||
|
is_active=obj_in.is_active,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
|
||||||
|
) -> User:
|
||||||
|
if isinstance(obj_in, dict):
|
||||||
|
update_data = obj_in
|
||||||
|
else:
|
||||||
|
update_data = obj_in.model_dump(exclude_unset=True)
|
||||||
|
if update_data.get("password"):
|
||||||
|
hashed_password = get_password_hash(update_data["password"])
|
||||||
|
del update_data["password"]
|
||||||
|
update_data["hashed_password"] = hashed_password
|
||||||
|
return super().update(db, db_obj=db_obj, obj_in=update_data)
|
||||||
|
|
||||||
|
def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
|
||||||
|
user = self.get_by_email(db, email=email)
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, user.hashed_password):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
|
||||||
|
def is_active(self, user: User) -> bool:
|
||||||
|
return user.is_active
|
||||||
|
|
||||||
|
|
||||||
|
user = CRUDUser(User)
|
1
app/database/__init__.py
Normal file
1
app/database/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Database package initialization
|
4
app/database/base.py
Normal file
4
app/database/base.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# Import all models here for Alembic autogenerate
|
||||||
|
from app.database.base_class import Base # noqa
|
||||||
|
from app.models.item import Item # noqa
|
||||||
|
from app.models.user import User # noqa
|
14
app/database/base_class.py
Normal file
14
app/database/base_class.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy.ext.declarative import as_declarative, declared_attr
|
||||||
|
|
||||||
|
|
||||||
|
@as_declarative()
|
||||||
|
class Base:
|
||||||
|
id: Any
|
||||||
|
__name__: str
|
||||||
|
|
||||||
|
# Generate __tablename__ automatically
|
||||||
|
@declared_attr
|
||||||
|
def __tablename__(cls) -> str:
|
||||||
|
return cls.__name__.lower()
|
23
app/database/session.py
Normal file
23
app/database/session.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
DB_DIR = Path("/app") / "storage" / "db"
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
engine = create_engine(
|
||||||
|
SQLALCHEMY_DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
1
app/models/__init__.py
Normal file
1
app/models/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Models package initialization
|
17
app/models/item.py
Normal file
17
app/models/item.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
from sqlalchemy import Column, ForeignKey, Integer, String, Text
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql.sqltypes import DateTime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.database.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Item(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
title = Column(String, index=True)
|
||||||
|
description = Column(Text)
|
||||||
|
owner_id = Column(Integer, ForeignKey("user.id"))
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
owner = relationship("User", back_populates="items")
|
18
app/models/user.py
Normal file
18
app/models/user.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from sqlalchemy import Boolean, Column, Integer, String
|
||||||
|
from sqlalchemy.sql.sqltypes import DateTime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.database.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
email = Column(String, unique=True, index=True, nullable=False)
|
||||||
|
hashed_password = Column(String, nullable=False)
|
||||||
|
full_name = Column(String, index=True)
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||||
|
|
||||||
|
items = relationship("Item", back_populates="owner")
|
1
app/schemas/__init__.py
Normal file
1
app/schemas/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Schemas package initialization
|
42
app/schemas/item.py
Normal file
42
app/schemas/item.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class ItemBase(BaseModel):
|
||||||
|
title: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item creation
|
||||||
|
class ItemCreate(ItemBase):
|
||||||
|
title: str
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on item update
|
||||||
|
class ItemUpdate(ItemBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Properties shared by models stored in DB
|
||||||
|
class ItemInDBBase(ItemBase):
|
||||||
|
id: int
|
||||||
|
title: str
|
||||||
|
owner_id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to return to client
|
||||||
|
class Item(ItemInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Properties stored in DB but not returned to client
|
||||||
|
class ItemInDB(ItemInDBBase):
|
||||||
|
pass
|
41
app/schemas/user.py
Normal file
41
app/schemas/user.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class UserBase(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
full_name: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = True
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on user creation
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str = Field(..., min_length=8)
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive on user update
|
||||||
|
class UserUpdate(UserBase):
|
||||||
|
password: Optional[str] = Field(None, min_length=8)
|
||||||
|
|
||||||
|
|
||||||
|
# Properties shared by models stored in DB
|
||||||
|
class UserInDBBase(UserBase):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to return to client
|
||||||
|
class User(UserInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Properties stored in DB but not returned to client
|
||||||
|
class UserInDB(UserInDBBase):
|
||||||
|
hashed_password: str
|
33
main.py
Normal file
33
main.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import uvicorn
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.api.api import api_router
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
||||||
|
description="Generic REST API Service",
|
||||||
|
version="0.1.0",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set up CORS middleware
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.ALLOWED_ORIGINS,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Include API router
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
# Add health check endpoint
|
||||||
|
@app.get("/health", status_code=200)
|
||||||
|
async def health_check():
|
||||||
|
return {"status": "healthy"}
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
1
migrations/__init__.py
Normal file
1
migrations/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Migrations package initialization
|
81
migrations/env.py
Normal file
81
migrations/env.py
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
from app.database.base import Base # noqa
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
is_sqlite = connection.dialect.name == 'sqlite'
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
render_as_batch=is_sqlite, # Use batch mode for SQLite
|
||||||
|
compare_type=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
59
migrations/versions/20240520_initial.py
Normal file
59
migrations/versions/20240520_initial.py
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 20240520_initial
|
||||||
|
Revises:
|
||||||
|
Create Date: 2024-05-20
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '20240520_initial'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create user table
|
||||||
|
op.create_table(
|
||||||
|
'user',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(), nullable=False),
|
||||||
|
sa.Column('hashed_password', sa.String(), nullable=False),
|
||||||
|
sa.Column('full_name', sa.String(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
|
||||||
|
op.create_index(op.f('ix_user_full_name'), 'user', ['full_name'], unique=False)
|
||||||
|
op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False)
|
||||||
|
|
||||||
|
# Create item table
|
||||||
|
op.create_table(
|
||||||
|
'item',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(), nullable=True),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('owner_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['owner_id'], ['user.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f('ix_item_title'), table_name='item')
|
||||||
|
op.drop_index(op.f('ix_item_id'), table_name='item')
|
||||||
|
op.drop_table('item')
|
||||||
|
op.drop_index(op.f('ix_user_id'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_full_name'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_email'), table_name='user')
|
||||||
|
op.drop_table('user')
|
1
migrations/versions/__init__.py
Normal file
1
migrations/versions/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Migrations versions package initialization
|
12
requirements.txt
Normal file
12
requirements.txt
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
fastapi>=0.95.0
|
||||||
|
uvicorn>=0.21.1
|
||||||
|
sqlalchemy>=2.0.0
|
||||||
|
pydantic>=2.0.0
|
||||||
|
pydantic-settings>=2.0.0
|
||||||
|
alembic>=1.11.0
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
ruff>=0.0.270
|
||||||
|
python-multipart>=0.0.6
|
||||||
|
email-validator>=2.0.0
|
||||||
|
passlib>=1.7.4
|
||||||
|
bcrypt>=4.0.1
|
Loading…
x
Reference in New Issue
Block a user