Implement task management tool with FastAPI and SQLite

- Setup project structure and FastAPI application
- Create SQLite database with SQLAlchemy
- Implement user authentication with JWT
- Create task and user models
- Add CRUD operations for tasks and users
- Configure Alembic for database migrations
- Implement API endpoints for task management
- Add error handling and validation
- Configure CORS middleware
- Create health check endpoint
- Add comprehensive documentation
This commit is contained in:
Automated Action 2025-06-12 12:02:37 +00:00
parent 6de1bc6843
commit 350b445f45
40 changed files with 1289 additions and 2 deletions

128
README.md
View File

@ -1,3 +1,127 @@
# FastAPI Application
# Task Management Tool
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A robust task management API built with FastAPI and SQLite.
## Features
- User authentication with JWT
- Task management (create, read, update, delete)
- Task priority and status tracking
- Role-based access control (admin/regular users)
- Error handling and validation
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
## Requirements
- Python 3.8+
- FastAPI
- SQLAlchemy
- Alembic
- Pydantic
- Python-jose
- Passlib
- Email-validator
- Uvicorn
## Installation
1. Clone the repository
```bash
git clone <repository-url>
cd taskmanagementtool
```
2. Install dependencies
```bash
pip install -r requirements.txt
```
3. Set up environment variables (or use default values for development)
```bash
# JWT Secret Key
export SECRET_KEY="your-secret-key-here"
# JWT Algorithm
export ALGORITHM="HS256"
# JWT Token Expiration (minutes)
export ACCESS_TOKEN_EXPIRE_MINUTES="11520" # 8 days
```
4. Run database migrations
```bash
alembic upgrade head
```
5. Start the server
```bash
uvicorn main:app --reload
```
The API will be available at http://localhost:8000
## API Documentation
API documentation is automatically generated and available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## API Endpoints
### Authentication
- `POST /api/v1/auth/login` - Get access token
- `POST /api/v1/auth/test-token` - Test if token is valid
### Users
- `GET /api/v1/users/` - List all users (admin only)
- `POST /api/v1/users/` - Create a new user
- `GET /api/v1/users/me` - Get current user information
- `PUT /api/v1/users/me` - Update current user information
- `GET /api/v1/users/{user_id}` - Get user by ID
### Tasks
- `GET /api/v1/tasks/` - List tasks (admins see all, users see their own)
- `POST /api/v1/tasks/` - Create a new task
- `GET /api/v1/tasks/{id}` - Get task by ID
- `PUT /api/v1/tasks/{id}` - Update task
- `DELETE /api/v1/tasks/{id}` - Delete task
### Health
- `GET /api/v1/health` - Check if the service is running
## Task Model
Tasks have the following attributes:
- `id`: Unique identifier
- `title`: Task title
- `description`: Detailed description
- `priority`: Priority level (LOW, MEDIUM, HIGH)
- `status`: Current status (TODO, IN_PROGRESS, DONE)
- `due_date`: Optional due date
- `user_id`: Owner of the task
- `created_at`: Creation timestamp
- `updated_at`: Last update timestamp
## Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| SECRET_KEY | JWT Secret Key | "YOUR_SECRET_KEY_HERE" |
| ALGORITHM | JWT Algorithm | "HS256" |
| ACCESS_TOKEN_EXPIRE_MINUTES | JWT Token Expiration (minutes) | 11520 (8 days) |
## License
This project is licensed under the MIT License.

85
alembic.ini Normal file
View File

@ -0,0 +1,85 @@
# 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
# 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 migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# SQLite URL using absolute path
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

0
app/__init__.py Normal file
View File

0
app/api/__init__.py Normal file
View File

View File

9
app/api/api_v1/api.py Normal file
View File

@ -0,0 +1,9 @@
from fastapi import APIRouter
from app.api.api_v1.endpoints import auth, health, tasks, users
api_router = APIRouter()
api_router.include_router(health.router, prefix="/health", tags=["health"])
api_router.include_router(auth.router, prefix="/auth", tags=["auth"])
api_router.include_router(users.router, prefix="/users", tags=["users"])
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])

View File

View File

@ -0,0 +1,47 @@
from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from app.core import auth
from app.core.config import settings
from app.core.exceptions import InactiveUserException, InvalidCredentialsException
from app.core.security import create_access_token
from app.db.session import get_db
from app.schemas.token import Token
from app.schemas.user import User
router = APIRouter()
@router.post("/login", response_model=Token)
async def login_access_token(
db: AsyncSession = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = await auth.authenticate(
db, email=form_data.username, password=form_data.password
)
if not user:
raise InvalidCredentialsException()
if not user.is_active:
raise InactiveUserException()
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
return {
"access_token": create_access_token(
user.id, expires_delta=access_token_expires
),
"token_type": "bearer",
}
@router.post("/test-token", response_model=User)
async def test_token(current_user: User = Depends(auth.get_current_user)) -> Any:
"""
Test access token
"""
return current_user

View File

@ -0,0 +1,13 @@
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
router = APIRouter()
@router.get("")
async def health_check(db: AsyncSession = Depends(get_db)):
"""
Health check endpoint
"""
return {"status": "ok", "message": "Service is running"}

View File

@ -0,0 +1,103 @@
from typing import Any, List
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.core import auth
from app.core.exceptions import ForbiddenException, NotFoundException
from app.crud.crud_task import task
from app.db.session import get_db
from app.models.user import User
from app.schemas.task import Task, TaskCreate, TaskUpdate
router = APIRouter()
@router.get("/", response_model=List[Task])
async def read_tasks(
db: AsyncSession = Depends(get_db),
skip: int = 0,
limit: int = 100,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Retrieve tasks.
"""
if current_user.is_superuser:
tasks = await task.get_multi(db, skip=skip, limit=limit)
else:
tasks = await task.get_multi_by_owner(
db=db, owner_id=current_user.id, skip=skip, limit=limit
)
return tasks
@router.post("/", response_model=Task)
async def create_task(
*,
db: AsyncSession = Depends(get_db),
task_in: TaskCreate,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Create new task.
"""
task_obj = await task.create_with_owner(db=db, obj_in=task_in, owner_id=current_user.id)
return task_obj
@router.put("/{task_id}", response_model=Task)
async def update_task(
*,
db: AsyncSession = Depends(get_db),
task_id: str,
task_in: TaskUpdate,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Update a task.
"""
task_obj = await task.get(db=db, id_=task_id)
if not task_obj:
raise NotFoundException("Task not found")
if not current_user.is_superuser and (task_obj.user_id != current_user.id):
raise ForbiddenException("Not enough permissions")
task_obj = await task.update(db=db, db_obj=task_obj, obj_in=task_in)
return task_obj
@router.get("/{task_id}", response_model=Task)
async def read_task(
*,
db: AsyncSession = Depends(get_db),
task_id: str,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Get task by ID.
"""
task_obj = await task.get(db=db, id_=task_id)
if not task_obj:
raise NotFoundException("Task not found")
if not current_user.is_superuser and (task_obj.user_id != current_user.id):
raise ForbiddenException("Not enough permissions")
return task_obj
@router.delete("/{task_id}", response_model=Task)
async def delete_task(
*,
db: AsyncSession = Depends(get_db),
task_id: str,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Delete a task.
"""
task_obj = await task.get(db=db, id_=task_id)
if not task_obj:
raise NotFoundException("Task not found")
if not current_user.is_superuser and (task_obj.user_id != current_user.id):
raise ForbiddenException("Not enough permissions")
task_obj = await task.remove(db=db, id_=task_id)
return task_obj

View File

@ -0,0 +1,99 @@
from typing import Any, List
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.core import auth
from app.core.exceptions import (
EmailAlreadyExistsException,
ForbiddenException,
NotFoundException,
UsernameAlreadyExistsException,
)
from app.crud.crud_user import user
from app.db.session import get_db
from app.schemas.user import User, UserCreate, UserUpdate
router = APIRouter()
@router.get("/", response_model=List[User])
async def read_users(
db: AsyncSession = Depends(get_db),
skip: int = 0,
limit: int = 100,
current_user: User = Depends(auth.get_current_active_superuser),
) -> Any:
"""
Retrieve users.
"""
users = await user.get_multi(db, skip=skip, limit=limit)
return users
@router.post("/", response_model=User)
async def create_user(
*,
db: AsyncSession = Depends(get_db),
user_in: UserCreate,
) -> Any:
"""
Create new user.
"""
user_obj = await user.get_by_email(db, email=user_in.email)
if user_obj:
raise EmailAlreadyExistsException()
username_obj = await user.get_by_username(db, username=user_in.username)
if username_obj:
raise UsernameAlreadyExistsException()
user_obj = await user.create(db, obj_in=user_in)
return user_obj
@router.put("/me", response_model=User)
async def update_user_me(
*,
db: AsyncSession = Depends(get_db),
user_in: UserUpdate,
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Update own user.
"""
if user_in.email and user_in.email != current_user.email:
user_obj = await user.get_by_email(db, email=user_in.email)
if user_obj:
raise EmailAlreadyExistsException()
if user_in.username and user_in.username != current_user.username:
username_obj = await user.get_by_username(db, username=user_in.username)
if username_obj:
raise UsernameAlreadyExistsException()
user_obj = await user.update(db, db_obj=current_user, obj_in=user_in)
return user_obj
@router.get("/me", response_model=User)
async def read_user_me(
current_user: User = Depends(auth.get_current_active_user),
) -> Any:
"""
Get current user.
"""
return current_user
@router.get("/{user_id}", response_model=User)
async def read_user_by_id(
user_id: str,
current_user: User = Depends(auth.get_current_active_user),
db: AsyncSession = Depends(get_db),
) -> Any:
"""
Get a specific user by id.
"""
user_obj = await user.get(db, id_=user_id)
if not user_obj:
raise NotFoundException("The user with this id does not exist in the system")
if user_obj.id != current_user.id and not current_user.is_superuser:
raise ForbiddenException("The user doesn't have enough privileges")
return user_obj

0
app/core/__init__.py Normal file
View File

70
app/core/auth.py Normal file
View File

@ -0,0 +1,70 @@
from datetime import datetime
from typing import Optional
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.core.exceptions import (
ForbiddenException,
InactiveUserException,
UnauthorizedException,
)
from app.core.security import verify_password
from app.crud.crud_user import user
from app.db.session import get_db
from app.models.user import User
from app.schemas.token import TokenPayload
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/auth/login"
)
async def get_current_user(
db: AsyncSession = Depends(get_db), token: str = Depends(oauth2_scheme)
) -> User:
credentials_exception = UnauthorizedException("Could not validate credentials")
try:
payload = jwt.decode(
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
)
token_data = TokenPayload(**payload)
if datetime.fromtimestamp(token_data.exp) < datetime.now():
raise credentials_exception
except JWTError as e:
raise credentials_exception from e
user_obj = await user.get(db, id_=token_data.sub)
if not user_obj:
raise credentials_exception
return user_obj
async def get_current_active_user(
current_user: User = Depends(get_current_user),
) -> User:
if not current_user.is_active:
raise InactiveUserException()
return current_user
async def get_current_active_superuser(
current_user: User = Depends(get_current_user),
) -> User:
if not current_user.is_superuser:
raise ForbiddenException("The user doesn't have enough privileges")
return current_user
async def authenticate(
db: AsyncSession, *, email: str, password: str
) -> Optional[User]:
user_obj = await user.get_by_email(db, email=email)
if not user_obj:
return None
if not verify_password(password, user_obj.hashed_password):
return None
return user_obj

32
app/core/config.py Normal file
View File

@ -0,0 +1,32 @@
from typing import List
from pydantic import validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Task Management Tool"
# CORS Origins
BACKEND_CORS_ORIGINS: List[str] = ["*"]
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(self, v: str | List[str]) -> List[str] | str:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
if isinstance(v, (list, str)):
return v
raise ValueError(v)
# JWT
SECRET_KEY: str = "YOUR_SECRET_KEY_HERE" # Change in production
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 # 8 days
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()

53
app/core/exceptions.py Normal file
View File

@ -0,0 +1,53 @@
from fastapi import HTTPException, status
class TaskManagementException(HTTPException):
def __init__(
self,
status_code: int,
detail: str = None,
) -> None:
super().__init__(status_code=status_code, detail=detail)
class NotFoundException(TaskManagementException):
def __init__(self, detail: str = "Item not found") -> None:
super().__init__(status_code=status.HTTP_404_NOT_FOUND, detail=detail)
class BadRequestException(TaskManagementException):
def __init__(self, detail: str = "Bad request") -> None:
super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)
class UnauthorizedException(TaskManagementException):
def __init__(self, detail: str = "Not authenticated") -> None:
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
)
class ForbiddenException(TaskManagementException):
def __init__(self, detail: str = "Not enough permissions") -> None:
super().__init__(status_code=status.HTTP_403_FORBIDDEN, detail=detail)
class EmailAlreadyExistsException(BadRequestException):
def __init__(self) -> None:
super().__init__("The user with this email already exists in the system")
class UsernameAlreadyExistsException(BadRequestException):
def __init__(self) -> None:
super().__init__("The username is already taken")
class InvalidCredentialsException(BadRequestException):
def __init__(self) -> None:
super().__init__("Incorrect email or password")
class InactiveUserException(BadRequestException):
def __init__(self) -> None:
super().__init__("Inactive user")

38
app/core/security.py Normal file
View File

@ -0,0 +1,38 @@
import uuid
from datetime import datetime, timedelta
from typing import Any, Union
from jose import jwt
from passlib.context import CryptContext
from app.core.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def create_access_token(
subject: Union[str, Any], expires_delta: timedelta = None
) -> str:
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
)
to_encode = {"exp": expire, "sub": str(subject)}
encoded_jwt = jwt.encode(
to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM
)
return encoded_jwt
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)
def generate_uuid() -> str:
return str(uuid.uuid4())

0
app/crud/__init__.py Normal file
View File

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.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.db.base 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
async def get(self, db: AsyncSession, id_: Any) -> Optional[ModelType]:
result = await db.execute(select(self.model).filter(self.model.id == id_))
return result.scalars().first()
async def get_multi(
self, db: AsyncSession, *, skip: int = 0, limit: int = 100
) -> List[ModelType]:
result = await db.execute(select(self.model).offset(skip).limit(limit))
return result.scalars().all()
async def create(self, db: AsyncSession, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
db.add(db_obj)
await db.commit()
await db.refresh(db_obj)
return db_obj
async def update(
self,
db: AsyncSession,
*,
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)
await db.commit()
await db.refresh(db_obj)
return db_obj
async def remove(self, db: AsyncSession, *, id_: str) -> ModelType:
obj = await db.execute(select(self.model).filter(self.model.id == id_))
obj = obj.scalars().first()
await db.delete(obj)
await db.commit()
return obj

35
app/crud/crud_task.py Normal file
View File

@ -0,0 +1,35 @@
from typing import List
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.core.security import generate_uuid
from app.crud.base import CRUDBase
from app.models.task import Task
from app.schemas.task import TaskCreate, TaskUpdate
class CRUDTask(CRUDBase[Task, TaskCreate, TaskUpdate]):
async def create_with_owner(
self, db: AsyncSession, *, obj_in: TaskCreate, owner_id: str
) -> Task:
obj_in_data = obj_in.dict()
db_obj = Task(**obj_in_data, id=generate_uuid(), user_id=owner_id)
db.add(db_obj)
await db.commit()
await db.refresh(db_obj)
return db_obj
async def get_multi_by_owner(
self, db: AsyncSession, *, owner_id: str, skip: int = 0, limit: int = 100
) -> List[Task]:
result = await db.execute(
select(Task)
.filter(Task.user_id == owner_id)
.offset(skip)
.limit(limit)
)
return result.scalars().all()
task = CRUDTask(Task)

65
app/crud/crud_user.py Normal file
View File

@ -0,0 +1,65 @@
from typing import Any, Dict, Optional, Union
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from app.core.security import generate_uuid, 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]):
async def get_by_email(self, db: AsyncSession, *, email: str) -> Optional[User]:
result = await db.execute(select(User).filter(User.email == email))
return result.scalars().first()
async def get_by_username(self, db: AsyncSession, *, username: str) -> Optional[User]:
result = await db.execute(select(User).filter(User.username == username))
return result.scalars().first()
async def create(self, db: AsyncSession, *, obj_in: UserCreate) -> User:
db_obj = User(
id=generate_uuid(),
email=obj_in.email,
username=obj_in.username,
hashed_password=get_password_hash(obj_in.password),
full_name=obj_in.full_name,
is_superuser=obj_in.is_superuser,
)
db.add(db_obj)
await db.commit()
await db.refresh(db_obj)
return db_obj
async def update(
self, db: AsyncSession, *, 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.dict(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 await super().update(db, db_obj=db_obj, obj_in=update_data)
async def authenticate(self, db: AsyncSession, *, email: str, password: str) -> Optional[User]:
user = await 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
def is_superuser(self, user: User) -> bool:
return user.is_superuser
user = CRUDUser(User)

0
app/db/__init__.py Normal file
View File

3
app/db/base.py Normal file
View File

@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

0
app/db/base_class.py Normal file
View File

41
app/db/session.py Normal file
View File

@ -0,0 +1,41 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
# Ensure the DB directory exists
DB_DIR = Path("/app/storage/db")
DB_DIR.mkdir(parents=True, exist_ok=True)
# Database URLs
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
ASYNC_SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite"
# Create engines
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
async_engine = create_async_engine(
ASYNC_SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False}
)
# Create sessions
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
AsyncSessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=async_engine,
class_=AsyncSession,
)
# Dependency for FastAPI endpoints
async def get_db():
async with AsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()

0
app/models/__init__.py Normal file
View File

36
app/models/task.py Normal file
View File

@ -0,0 +1,36 @@
import enum
from sqlalchemy import Column, DateTime, Enum, ForeignKey, String, Text
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.base import Base
class TaskPriority(str, enum.Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
class TaskStatus(str, enum.Enum):
TODO = "todo"
IN_PROGRESS = "in_progress"
DONE = "done"
class Task(Base):
__tablename__ = "tasks"
id = Column(String, primary_key=True, index=True)
title = Column(String, index=True, nullable=False)
description = Column(Text, nullable=True)
priority = Column(Enum(TaskPriority), default=TaskPriority.MEDIUM)
status = Column(Enum(TaskStatus), default=TaskStatus.TODO)
due_date = Column(DateTime(timezone=True), nullable=True)
user_id = Column(String, ForeignKey("users.id"))
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
# Relationships
owner = relationship("User", back_populates="tasks")

22
app/models/user.py Normal file
View File

@ -0,0 +1,22 @@
from sqlalchemy import Boolean, Column, DateTime, String
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.base import Base
class User(Base):
__tablename__ = "users"
id = Column(String, primary_key=True, index=True)
email = Column(String, unique=True, index=True, nullable=False)
username = Column(String, unique=True, index=True, nullable=False)
hashed_password = Column(String, nullable=False)
full_name = Column(String, nullable=True)
is_active = Column(Boolean, default=True)
is_superuser = Column(Boolean, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
# Relationships
tasks = relationship("Task", back_populates="owner")

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

47
app/schemas/task.py Normal file
View File

@ -0,0 +1,47 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
from app.models.task import TaskPriority, TaskStatus
# Shared properties
class TaskBase(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
priority: Optional[TaskPriority] = TaskPriority.MEDIUM
status: Optional[TaskStatus] = TaskStatus.TODO
due_date: Optional[datetime] = None
# Properties to receive on task creation
class TaskCreate(TaskBase):
title: str
# Properties to receive on task update
class TaskUpdate(TaskBase):
pass
# Properties shared by models stored in DB
class TaskInDBBase(TaskBase):
id: str
title: str
user_id: str
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
# Properties to return to client
class Task(TaskInDBBase):
pass
# Properties stored in DB
class TaskInDB(TaskInDBBase):
pass

12
app/schemas/token.py Normal file
View File

@ -0,0 +1,12 @@
from typing import Optional
from pydantic import BaseModel
class Token(BaseModel):
access_token: str
token_type: str
class TokenPayload(BaseModel):
sub: Optional[str] = None

45
app/schemas/user.py Normal file
View File

@ -0,0 +1,45 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, EmailStr
# Shared properties
class UserBase(BaseModel):
email: Optional[EmailStr] = None
username: Optional[str] = None
is_active: Optional[bool] = True
is_superuser: Optional[bool] = False
full_name: Optional[str] = None
# Properties to receive via API on creation
class UserCreate(UserBase):
email: EmailStr
username: str
password: str
# Properties to receive via API on update
class UserUpdate(UserBase):
password: Optional[str] = None
# Additional properties to return via API
class UserInDBBase(UserBase):
id: str
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True
# Additional properties stored in DB
class UserInDB(UserInDBBase):
hashed_password: str
# Additional properties to return via API
class User(UserInDBBase):
pass

0
app/utils/__init__.py Normal file
View File

38
main.py Normal file
View File

@ -0,0 +1,38 @@
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api.api_v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
docs_url="/docs",
redoc_url="/redoc",
)
# Set up CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API router
app.include_router(api_router, prefix=settings.API_V1_STR)
# Root endpoint
@app.get("/")
async def root():
return {
"title": settings.PROJECT_NAME,
"docs": f"{settings.API_V1_STR}/docs",
"health": f"{settings.API_V1_STR}/health"
}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

0
migrations/__init__.py Normal file
View File

86
migrations/env.py Normal file
View File

@ -0,0 +1,86 @@
import os
# Import Base and models
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.db.base import Base
from app.db.base_class import * # noqa
# 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 myapp import mymodel
# target_metadata = mymodel.Base.metadata
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:
is_sqlite = connection.dialect.name == 'sqlite'
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Key configuration for SQLite
)
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
View 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"}

View File

@ -0,0 +1,66 @@
"""Initial migration
Revision ID: 001
Revises:
Create Date: 2023-10-28
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '001'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# Create users table
op.create_table(
'users',
sa.Column('id', sa.String(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('username', 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('is_superuser', 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_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
# Create tasks table
op.create_table(
'tasks',
sa.Column('id', sa.String(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('priority', sa.Enum('LOW', 'MEDIUM', 'HIGH', name='taskpriority'), nullable=True),
sa.Column('status', sa.Enum('TODO', 'IN_PROGRESS', 'DONE', name='taskstatus'), nullable=True),
sa.Column('due_date', sa.DateTime(timezone=True), nullable=True),
sa.Column('user_id', sa.String(), 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(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_tasks_id'), 'tasks', ['id'], unique=False)
op.create_index(op.f('ix_tasks_title'), 'tasks', ['title'], unique=False)
def downgrade():
# Drop tasks table
op.drop_index(op.f('ix_tasks_title'), table_name='tasks')
op.drop_index(op.f('ix_tasks_id'), table_name='tasks')
op.drop_table('tasks')
# Drop users table
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_id'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')

View File

13
pyproject.toml Normal file
View File

@ -0,0 +1,13 @@
[tool.ruff]
line-length = 88
target-version = "py38"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "N", "B", "A", "C4", "RET", "SIM"]
ignore = ["E203", "E501", "RET504", "B008"]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "starlette"]
[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"

11
requirements.txt Normal file
View File

@ -0,0 +1,11 @@
fastapi>=0.104.0
uvicorn>=0.23.2
sqlalchemy>=2.0.0
alembic>=1.12.0
pydantic>=2.4.2
pydantic-settings>=2.0.3
python-jose[cryptography]>=3.3.0
passlib[bcrypt]>=1.7.4
python-multipart>=0.0.6
email-validator>=2.0.0
ruff>=0.1.3