Implement Task Manager API with FastAPI and SQLite
- Set up project structure - Created Task model with SQLAlchemy - Implemented SQLite database connection - Created Alembic migrations - Added Task CRUD endpoints - Added health endpoint - Updated README with project details generated with BackendIM... (backend.im)
This commit is contained in:
parent
9d38a4ce64
commit
aeab17a8ea
83
README.md
83
README.md
@ -1,3 +1,82 @@
|
||||
# FastAPI Application
|
||||
# Task Manager API
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A RESTful API for managing tasks, built with FastAPI and SQLite.
|
||||
|
||||
## Features
|
||||
|
||||
- Task CRUD operations
|
||||
- Task status and priority management
|
||||
- Task completion tracking
|
||||
- API documentation with Swagger UI and ReDoc
|
||||
- Health endpoint for monitoring
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- FastAPI: Modern, high-performance web framework for building APIs
|
||||
- SQLAlchemy: SQL toolkit and Object-Relational Mapping (ORM)
|
||||
- Alembic: Database migration tool
|
||||
- SQLite: Lightweight relational database
|
||||
- Pydantic: Data validation and settings management
|
||||
- Uvicorn: ASGI server for FastAPI applications
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Task Management
|
||||
|
||||
- `GET /api/v1/tasks`: Get all tasks
|
||||
- `POST /api/v1/tasks`: Create a new task
|
||||
- `GET /api/v1/tasks/{task_id}`: Get a specific task
|
||||
- `PUT /api/v1/tasks/{task_id}`: Update a task
|
||||
- `DELETE /api/v1/tasks/{task_id}`: Delete a task
|
||||
- `POST /api/v1/tasks/{task_id}/complete`: Mark a task as completed
|
||||
|
||||
### Health Check
|
||||
|
||||
- `GET /health`: Application health check
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
taskmanagerapi/
|
||||
├── alembic/ # Database migrations
|
||||
│ └── versions/ # Migration scripts
|
||||
├── app/
|
||||
│ ├── api/ # API endpoints
|
||||
│ │ └── routers/ # API route definitions
|
||||
│ ├── core/ # Core application code
|
||||
│ ├── crud/ # CRUD operations
|
||||
│ ├── db/ # Database setup and models
|
||||
│ ├── models/ # SQLAlchemy models
|
||||
│ └── schemas/ # Pydantic schemas/models
|
||||
├── main.py # Application entry point
|
||||
└── requirements.txt # Project dependencies
|
||||
```
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installation
|
||||
|
||||
1. Clone the repository
|
||||
2. Install dependencies:
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### Running Migrations
|
||||
|
||||
```
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
### Starting the Application
|
||||
|
||||
```
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The API will be available at http://localhost:8000
|
||||
|
||||
### API Documentation
|
||||
|
||||
- Swagger UI: http://localhost:8000/docs
|
||||
- ReDoc: http://localhost:8000/redoc
|
84
alembic.ini
Normal file
84
alembic.ini
Normal file
@ -0,0 +1,84 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = alembic
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# 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 alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
76
alembic/env.py
Normal file
76
alembic/env.py
Normal file
@ -0,0 +1,76 @@
|
||||
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.
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
from app.db.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():
|
||||
"""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():
|
||||
"""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:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
alembic/script.py.mako
Normal file
24
alembic/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():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
38
alembic/versions/0001_create_tasks_table.py
Normal file
38
alembic/versions/0001_create_tasks_table.py
Normal file
@ -0,0 +1,38 @@
|
||||
"""create tasks table
|
||||
|
||||
Revision ID: 0001
|
||||
Revises:
|
||||
Create Date: 2025-05-14
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import sqlite
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'task',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(length=100), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', name='taskpriority'), default='MEDIUM'),
|
||||
sa.Column('status', sa.Enum('TODO', 'IN_PROGRESS', 'DONE', name='taskstatus'), default='TODO'),
|
||||
sa.Column('due_date', sa.DateTime(), nullable=True),
|
||||
sa.Column('completed', sa.Boolean(), default=False),
|
||||
sa.Column('created_at', sa.DateTime(), default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), default=sa.func.now(), onupdate=sa.func.now()),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_task_id'), 'task', ['id'], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_task_id'), table_name='task')
|
||||
op.drop_table('task')
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# App package
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# API package
|
11
app/api/deps.py
Normal file
11
app/api/deps.py
Normal file
@ -0,0 +1,11 @@
|
||||
from typing import Generator
|
||||
|
||||
from app.db.session import SessionLocal
|
||||
|
||||
|
||||
def get_db() -> Generator:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
6
app/api/routers/__init__.py
Normal file
6
app/api/routers/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.routers import tasks
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
116
app/api/routers/tasks.py
Normal file
116
app/api/routers/tasks.py
Normal file
@ -0,0 +1,116 @@
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import crud
|
||||
from app.api.deps import get_db
|
||||
from app.models.task import TaskStatus
|
||||
from app.schemas.task import Task, TaskCreate, TaskUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/", response_model=List[Task])
|
||||
def read_tasks(
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
status: Optional[TaskStatus] = None,
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve tasks.
|
||||
"""
|
||||
if status:
|
||||
tasks = crud.task.get_by_status(db, status=status)
|
||||
else:
|
||||
tasks = crud.task.get_multi(db, skip=skip, limit=limit)
|
||||
return tasks
|
||||
|
||||
|
||||
@router.post("/", response_model=Task, status_code=status.HTTP_201_CREATED)
|
||||
def create_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_in: TaskCreate,
|
||||
) -> Any:
|
||||
"""
|
||||
Create new task.
|
||||
"""
|
||||
task = crud.task.create(db, obj_in=task_in)
|
||||
return task
|
||||
|
||||
|
||||
@router.get("/{task_id}", response_model=Task)
|
||||
def read_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
) -> Any:
|
||||
"""
|
||||
Get task by ID.
|
||||
"""
|
||||
task = crud.task.get(db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
@router.put("/{task_id}", response_model=Task)
|
||||
def update_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
task_in: TaskUpdate,
|
||||
) -> Any:
|
||||
"""
|
||||
Update a task.
|
||||
"""
|
||||
task = crud.task.get(db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
task = crud.task.update(db, db_obj=task, obj_in=task_in)
|
||||
return task
|
||||
|
||||
|
||||
@router.delete("/{task_id}", response_model=Task)
|
||||
def delete_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
) -> Any:
|
||||
"""
|
||||
Delete a task.
|
||||
"""
|
||||
task = crud.task.get(db, id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
task = crud.task.remove(db, id=task_id)
|
||||
return task
|
||||
|
||||
|
||||
@router.post("/{task_id}/complete", response_model=Task)
|
||||
def complete_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
) -> Any:
|
||||
"""
|
||||
Mark a task as completed.
|
||||
"""
|
||||
task = crud.task.mark_completed(db, task_id=task_id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
return task
|
36
app/core/config.py
Normal file
36
app/core/config.py
Normal file
@ -0,0 +1,36 @@
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
|
||||
from pydantic import AnyHttpUrl, field_validator
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
DB_DIR = Path("/app") / "storage" / "db"
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
class Settings(BaseSettings):
|
||||
PROJECT_NAME: str = "Task Manager API"
|
||||
API_V1_STR: str = "/api/v1"
|
||||
SECRET_KEY: str = secrets.token_urlsafe(32)
|
||||
# 60 minutes * 24 hours * 8 days = 8 days
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
|
||||
|
||||
# CORS Configuration
|
||||
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||
|
||||
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
|
||||
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
|
||||
if isinstance(v, str) and not v.startswith("["):
|
||||
return [i.strip() for i in v.split(",")]
|
||||
elif isinstance(v, (list, str)):
|
||||
return v
|
||||
raise ValueError(v)
|
||||
|
||||
# Database configuration
|
||||
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
class Config:
|
||||
case_sensitive = True
|
||||
|
||||
|
||||
settings = Settings()
|
1
app/crud/__init__.py
Normal file
1
app/crud/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
from app.crud.task import task
|
61
app/crud/base.py
Normal file
61
app/crud/base.py
Normal file
@ -0,0 +1,61 @@
|
||||
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.db.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).
|
||||
"""
|
||||
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.model_dump(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
|
27
app/crud/task.py
Normal file
27
app/crud/task.py
Normal file
@ -0,0 +1,27 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
from app.crud.base import CRUDBase
|
||||
from app.models.task import Task, TaskStatus
|
||||
from app.schemas.task import TaskCreate, TaskUpdate
|
||||
|
||||
|
||||
class CRUDTask(CRUDBase[Task, TaskCreate, TaskUpdate]):
|
||||
def get_by_status(self, db: Session, *, status: TaskStatus) -> List[Task]:
|
||||
return db.query(self.model).filter(Task.status == status).all()
|
||||
|
||||
def get_completed(self, db: Session) -> List[Task]:
|
||||
return db.query(self.model).filter(Task.completed == True).all()
|
||||
|
||||
def mark_completed(self, db: Session, *, task_id: int) -> Optional[Task]:
|
||||
task = self.get(db, id=task_id)
|
||||
if not task:
|
||||
return None
|
||||
task_in = TaskUpdate(
|
||||
status=TaskStatus.DONE,
|
||||
completed=True
|
||||
)
|
||||
return self.update(db, db_obj=task, obj_in=task_in)
|
||||
|
||||
|
||||
task = CRUDTask(Task)
|
4
app/db/base.py
Normal file
4
app/db/base.py
Normal file
@ -0,0 +1,4 @@
|
||||
# Import all the models, so that Base has them before being
|
||||
# imported by Alembic
|
||||
from app.db.base_class import Base # noqa
|
||||
from app.models.task import Task # noqa
|
14
app/db/base_class.py
Normal file
14
app/db/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 based on class name
|
||||
@declared_attr
|
||||
def __tablename__(cls) -> str:
|
||||
return cls.__name__.lower()
|
18
app/db/session.py
Normal file
18
app/db/session.py
Normal file
@ -0,0 +1,18 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_engine(
|
||||
settings.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()
|
31
app/models/task.py
Normal file
31
app/models/task.py
Normal file
@ -0,0 +1,31 @@
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, Enum as SQLEnum
|
||||
|
||||
from app.db.base_class import Base
|
||||
|
||||
|
||||
class TaskPriority(str, Enum):
|
||||
LOW = "low"
|
||||
MEDIUM = "medium"
|
||||
HIGH = "high"
|
||||
|
||||
|
||||
class TaskStatus(str, Enum):
|
||||
TODO = "todo"
|
||||
IN_PROGRESS = "in_progress"
|
||||
DONE = "done"
|
||||
|
||||
|
||||
class Task(Base):
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String(100), nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
priority = Column(SQLEnum(TaskPriority), default=TaskPriority.MEDIUM)
|
||||
status = Column(SQLEnum(TaskStatus), default=TaskStatus.TODO)
|
||||
due_date = Column(DateTime, nullable=True)
|
||||
completed = Column(Boolean, default=False)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
41
app/schemas/task.py
Normal file
41
app/schemas/task.py
Normal file
@ -0,0 +1,41 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.models.task import TaskPriority, TaskStatus
|
||||
|
||||
|
||||
class TaskBase(BaseModel):
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
priority: TaskPriority = TaskPriority.MEDIUM
|
||||
status: TaskStatus = TaskStatus.TODO
|
||||
due_date: Optional[datetime] = None
|
||||
completed: bool = False
|
||||
|
||||
|
||||
class TaskCreate(TaskBase):
|
||||
pass
|
||||
|
||||
|
||||
class TaskUpdate(BaseModel):
|
||||
title: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
priority: Optional[TaskPriority] = None
|
||||
status: Optional[TaskStatus] = None
|
||||
due_date: Optional[datetime] = None
|
||||
completed: Optional[bool] = None
|
||||
|
||||
|
||||
class TaskInDBBase(TaskBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class Task(TaskInDBBase):
|
||||
pass
|
27
main.py
Normal file
27
main.py
Normal file
@ -0,0 +1,27 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.routers import api_router
|
||||
from app.core.config import settings
|
||||
|
||||
app = FastAPI(title=settings.PROJECT_NAME)
|
||||
|
||||
# Set all CORS enabled origins
|
||||
if settings.BACKEND_CORS_ORIGINS:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(api_router)
|
||||
|
||||
|
||||
@app.get("/health", tags=["health"])
|
||||
def health_check():
|
||||
"""
|
||||
Health check endpoint to verify the application is running correctly
|
||||
"""
|
||||
return {"status": "ok"}
|
8
requirements.txt
Normal file
8
requirements.txt
Normal file
@ -0,0 +1,8 @@
|
||||
fastapi>=0.104.0
|
||||
uvicorn>=0.24.0
|
||||
sqlalchemy>=2.0.22
|
||||
alembic>=1.12.0
|
||||
pydantic>=2.4.2
|
||||
pydantic-settings>=2.0.3
|
||||
python-multipart>=0.0.6
|
||||
ruff>=0.1.3
|
Loading…
x
Reference in New Issue
Block a user