Implement task management tool with FastAPI and SQLite
This commit includes: - Project structure and configuration - Database models for tasks, users, and categories - Authentication system with JWT - CRUD endpoints for tasks and categories - Search, filter, and sorting functionality - Health check endpoint - Alembic migration setup - Documentation
This commit is contained in:
parent
8e089d3b77
commit
6f269066a5
135
README.md
135
README.md
@ -1,3 +1,134 @@
|
||||
# FastAPI Application
|
||||
# Task Management Tool
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A robust task management application built with FastAPI and SQLite. The application allows users to create, organize, and track tasks with categories, priorities, and due dates.
|
||||
|
||||
## Features
|
||||
|
||||
- 🔐 User authentication (register, login)
|
||||
- ✅ Task management (create, read, update, delete)
|
||||
- 🏷️ Categories for organizing tasks
|
||||
- 🔍 Search, filter, and sorting functionality
|
||||
- 🎯 Priority levels for tasks
|
||||
- 📅 Due dates for tasks
|
||||
- 🔄 Task completion status tracking
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **Backend**: FastAPI
|
||||
- **Database**: SQLite with SQLAlchemy ORM
|
||||
- **Authentication**: JWT with OAuth2
|
||||
- **Migration**: Alembic
|
||||
- **Validation**: Pydantic
|
||||
- **Code Quality**: Ruff
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Python 3.8 or higher
|
||||
- pip (Python package manager)
|
||||
|
||||
### Installation
|
||||
|
||||
1. Clone the repository:
|
||||
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd taskmanagementtool
|
||||
```
|
||||
|
||||
2. Create a virtual environment and activate it:
|
||||
|
||||
```bash
|
||||
python -m venv venv
|
||||
source venv/bin/activate # On Windows: venv\Scripts\activate
|
||||
```
|
||||
|
||||
3. Install dependencies:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. Create a .env file based on .env.example:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
5. Run database migrations:
|
||||
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
### Running the Application
|
||||
|
||||
Start the server with uvicorn:
|
||||
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The API will be available at http://localhost:8000
|
||||
|
||||
### API Documentation
|
||||
|
||||
Once the server is running, you can access:
|
||||
|
||||
- Interactive API documentation: http://localhost:8000/docs
|
||||
- Alternative API documentation: http://localhost:8000/redoc
|
||||
- OpenAPI schema: http://localhost:8000/openapi.json
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Authentication
|
||||
|
||||
- `POST /api/v1/auth/register` - Register a new user
|
||||
- `POST /api/v1/auth/login` - Login and get access token
|
||||
|
||||
### Users
|
||||
|
||||
- `GET /api/v1/users/me` - Get current user info
|
||||
- `PUT /api/v1/users/me` - Update current user info
|
||||
|
||||
### Tasks
|
||||
|
||||
- `GET /api/v1/tasks` - List 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
|
||||
|
||||
### Categories
|
||||
|
||||
- `GET /api/v1/categories` - List all categories
|
||||
- `POST /api/v1/categories` - Create a new category
|
||||
- `GET /api/v1/categories/{category_id}` - Get a specific category
|
||||
- `PUT /api/v1/categories/{category_id}` - Update a category
|
||||
- `DELETE /api/v1/categories/{category_id}` - Delete a category
|
||||
|
||||
### Health Check
|
||||
|
||||
- `GET /health` - Check application health status
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Description | Default |
|
||||
|----------|-------------|---------|
|
||||
| SECRET_KEY | Secret key for JWT token generation | (See .env.example) |
|
||||
| ALGORITHM | Algorithm used for JWT | HS256 |
|
||||
| ACCESS_TOKEN_EXPIRE_MINUTES | Token expiration time in minutes | 30 |
|
||||
| BACKEND_CORS_ORIGINS | List of allowed CORS origins | [] |
|
||||
|
||||
## Database Structure
|
||||
|
||||
The application uses three main database models:
|
||||
|
||||
1. **User** - Stores user information
|
||||
2. **Task** - Stores task details with references to users and categories
|
||||
3. **Category** - Stores category information with references to users
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the LICENSE file for details.
|
110
alembic.ini
Normal file
110
alembic.ini
Normal file
@ -0,0 +1,110 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python-dateutil library that can be
|
||||
# installed by adding `alembic[tz]` to the pip requirements
|
||||
# string value is passed to dateutil.tz.gettz()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to migrations/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
sqlalchemy.url = 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
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
13
app/api/v1/api.py
Normal file
13
app/api/v1/api.py
Normal file
@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1.endpoints import auth, categories, tasks, users
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
# Include all router endpoints
|
||||
api_router.include_router(auth.router, prefix="/auth", tags=["authentication"])
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||
api_router.include_router(tasks.router, prefix="/tasks", tags=["tasks"])
|
||||
api_router.include_router(
|
||||
categories.router, prefix="/categories", tags=["categories"]
|
||||
)
|
0
app/api/v1/endpoints/__init__.py
Normal file
0
app/api/v1/endpoints/__init__.py
Normal file
75
app/api/v1/endpoints/auth.py
Normal file
75
app/api/v1/endpoints/auth.py
Normal file
@ -0,0 +1,75 @@
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.core.security import create_access_token
|
||||
from app.crud.user import (
|
||||
authenticate_user,
|
||||
create_user,
|
||||
get_user_by_email,
|
||||
get_user_by_username,
|
||||
)
|
||||
from app.schemas.token import Token
|
||||
from app.schemas.user import User, UserCreate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/register", response_model=User)
|
||||
def register(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_in: UserCreate,
|
||||
) -> Any:
|
||||
"""
|
||||
Register a new user.
|
||||
"""
|
||||
# Check if user with this email already exists
|
||||
user = get_user_by_email(db, email=user_in.email)
|
||||
if user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="A user with this email already exists",
|
||||
)
|
||||
|
||||
# Check if user with this username already exists
|
||||
user = get_user_by_username(db, username=user_in.username)
|
||||
if user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="A user with this username already exists",
|
||||
)
|
||||
|
||||
# Create new user
|
||||
user = create_user(db, user_in=user_in)
|
||||
return user
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
def login_access_token(
|
||||
db: Session = Depends(get_db),
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
) -> Any:
|
||||
"""
|
||||
OAuth2 compatible token login, get an access token for future requests.
|
||||
"""
|
||||
user = authenticate_user(db, email=form_data.username, password=form_data.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
return {
|
||||
"access_token": create_access_token(
|
||||
subject=str(user.id), expires_delta=access_token_expires
|
||||
),
|
||||
"token_type": "bearer",
|
||||
}
|
123
app/api/v1/endpoints/categories.py
Normal file
123
app/api/v1/endpoints/categories.py
Normal file
@ -0,0 +1,123 @@
|
||||
from typing import Any, List
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user
|
||||
from app.crud.category import (
|
||||
create_category,
|
||||
delete_category,
|
||||
get_categories,
|
||||
get_category_by_user,
|
||||
update_category,
|
||||
)
|
||||
from app.models.user import User
|
||||
from app.schemas.category import Category, CategoryCreate, CategoryUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("", response_model=List[Category])
|
||||
def read_categories(
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve categories for the current user.
|
||||
"""
|
||||
categories = get_categories(
|
||||
db=db, user_id=current_user.id, skip=skip, limit=limit
|
||||
)
|
||||
return categories
|
||||
|
||||
|
||||
@router.post("", response_model=Category)
|
||||
def create_category_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
category_in: CategoryCreate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Create new category.
|
||||
"""
|
||||
category = create_category(
|
||||
db=db, category_in=category_in, user_id=current_user.id
|
||||
)
|
||||
return category
|
||||
|
||||
|
||||
@router.get("/{category_id}", response_model=Category)
|
||||
def read_category(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
category_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Get specific category by ID.
|
||||
"""
|
||||
category = get_category_by_user(
|
||||
db=db, category_id=category_id, user_id=current_user.id
|
||||
)
|
||||
if not category:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Category not found",
|
||||
)
|
||||
return category
|
||||
|
||||
|
||||
@router.put("/{category_id}", response_model=Category)
|
||||
def update_category_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
category_id: int,
|
||||
category_in: CategoryUpdate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Update a category.
|
||||
"""
|
||||
category = get_category_by_user(
|
||||
db=db, category_id=category_id, user_id=current_user.id
|
||||
)
|
||||
if not category:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Category not found",
|
||||
)
|
||||
category = update_category(
|
||||
db=db,
|
||||
category_id=category_id,
|
||||
category_in=category_in,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
return category
|
||||
|
||||
|
||||
@router.delete("/{category_id}", response_model=Category)
|
||||
def delete_category_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
category_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Delete a category.
|
||||
"""
|
||||
category = get_category_by_user(
|
||||
db=db, category_id=category_id, user_id=current_user.id
|
||||
)
|
||||
if not category:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Category not found",
|
||||
)
|
||||
category = delete_category(
|
||||
db=db, category_id=category_id, user_id=current_user.id
|
||||
)
|
||||
return category
|
121
app/api/v1/endpoints/tasks.py
Normal file
121
app/api/v1/endpoints/tasks.py
Normal file
@ -0,0 +1,121 @@
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user
|
||||
from app.crud.task import (
|
||||
create_task,
|
||||
delete_task,
|
||||
get_task_by_user,
|
||||
get_tasks,
|
||||
update_task,
|
||||
)
|
||||
from app.models.user import User
|
||||
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,
|
||||
completed: Optional[bool] = None,
|
||||
category_id: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
priority: Optional[str] = None,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve tasks for the current user.
|
||||
"""
|
||||
tasks = get_tasks(
|
||||
db=db,
|
||||
user_id=current_user.id,
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
completed=completed,
|
||||
category_id=category_id,
|
||||
search=search,
|
||||
priority=priority,
|
||||
)
|
||||
return tasks
|
||||
|
||||
|
||||
@router.post("", response_model=Task)
|
||||
def create_task_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_in: TaskCreate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Create new task.
|
||||
"""
|
||||
task = create_task(db=db, task_in=task_in, user_id=current_user.id)
|
||||
return task
|
||||
|
||||
|
||||
@router.get("/{task_id}", response_model=Task)
|
||||
def read_task(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Get specific task by ID.
|
||||
"""
|
||||
task = get_task_by_user(db=db, task_id=task_id, user_id=current_user.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_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
task_in: TaskUpdate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Update a task.
|
||||
"""
|
||||
task = get_task_by_user(db=db, task_id=task_id, user_id=current_user.id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
task = update_task(
|
||||
db=db, task_id=task_id, task_in=task_in, user_id=current_user.id
|
||||
)
|
||||
return task
|
||||
|
||||
|
||||
@router.delete("/{task_id}", response_model=Task)
|
||||
def delete_task_endpoint(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
task_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Delete a task.
|
||||
"""
|
||||
task = get_task_by_user(db=db, task_id=task_id, user_id=current_user.id)
|
||||
if not task:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Task not found",
|
||||
)
|
||||
task = delete_task(db=db, task_id=task_id, user_id=current_user.id)
|
||||
return task
|
36
app/api/v1/endpoints/users.py
Normal file
36
app/api/v1/endpoints/users.py
Normal file
@ -0,0 +1,36 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user
|
||||
from app.crud.user import update_user
|
||||
from app.models.user import User as UserModel
|
||||
from app.schemas.user import User, UserUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/me", response_model=User)
|
||||
def read_current_user(
|
||||
current_user: UserModel = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Get current user.
|
||||
"""
|
||||
return current_user
|
||||
|
||||
|
||||
@router.put("/me", response_model=User)
|
||||
def update_current_user(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
user_in: UserUpdate,
|
||||
current_user: UserModel = Depends(get_current_active_user),
|
||||
) -> Any:
|
||||
"""
|
||||
Update current user.
|
||||
"""
|
||||
user = update_user(db, user_id=current_user.id, user_in=user_in)
|
||||
return user
|
35
app/core/config.py
Normal file
35
app/core/config.py
Normal file
@ -0,0 +1,35 @@
|
||||
from typing import List, Union
|
||||
|
||||
from pydantic import AnyHttpUrl, Field, validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env", env_file_encoding="utf-8", case_sensitive=True
|
||||
)
|
||||
|
||||
API_V1_STR: str = "/api/v1"
|
||||
PROJECT_NAME: str = "Task Management Tool"
|
||||
|
||||
# SECURITY
|
||||
SECRET_KEY: str = Field(
|
||||
"09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7",
|
||||
description="Secret key for JWT token generation. Should be changed in production.",
|
||||
)
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# CORS
|
||||
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||
|
||||
@validator("BACKEND_CORS_ORIGINS", pre=True)
|
||||
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)
|
||||
|
||||
|
||||
settings = Settings()
|
28
app/core/database.py
Normal file
28
app/core/database.py
Normal file
@ -0,0 +1,28 @@
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
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)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# Dependency to get the database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
51
app/core/deps.py
Normal file
51
app/core/deps.py
Normal file
@ -0,0 +1,51 @@
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.crud.user import get_user
|
||||
from app.models.user import User
|
||||
from app.schemas.token import TokenPayload
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
|
||||
|
||||
|
||||
def get_current_user(
|
||||
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
||||
) -> User:
|
||||
"""
|
||||
Get the current user from the token
|
||||
"""
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
||||
)
|
||||
token_data = TokenPayload(**payload)
|
||||
except JWTError as e:
|
||||
raise credentials_exception from e
|
||||
|
||||
user = get_user(db, user_id=token_data.sub)
|
||||
if not user:
|
||||
raise credentials_exception
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_active_user(
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> User:
|
||||
"""
|
||||
Get the current active user
|
||||
"""
|
||||
if not current_user.is_active:
|
||||
raise HTTPException(status_code=400, detail="Inactive user")
|
||||
|
||||
return current_user
|
42
app/core/security.py
Normal file
42
app/core/security.py
Normal file
@ -0,0 +1,42 @@
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Optional, 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: Optional[timedelta] = None
|
||||
) -> str:
|
||||
"""
|
||||
Create a JWT token for the given subject
|
||||
"""
|
||||
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:
|
||||
"""
|
||||
Verify plain password against hashed password
|
||||
"""
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""
|
||||
Hash a password
|
||||
"""
|
||||
return pwd_context.hash(password)
|
49
app/crud/__init__.py
Normal file
49
app/crud/__init__.py
Normal file
@ -0,0 +1,49 @@
|
||||
from app.crud.category import (
|
||||
create_category,
|
||||
delete_category,
|
||||
get_categories,
|
||||
get_category,
|
||||
get_category_by_user,
|
||||
update_category,
|
||||
)
|
||||
from app.crud.task import (
|
||||
create_task,
|
||||
delete_task,
|
||||
get_task,
|
||||
get_task_by_user,
|
||||
get_tasks,
|
||||
update_task,
|
||||
)
|
||||
from app.crud.user import (
|
||||
authenticate_user,
|
||||
create_user,
|
||||
delete_user,
|
||||
get_user,
|
||||
get_user_by_email,
|
||||
get_user_by_username,
|
||||
get_users,
|
||||
update_user,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"get_user",
|
||||
"get_user_by_email",
|
||||
"get_user_by_username",
|
||||
"get_users",
|
||||
"create_user",
|
||||
"update_user",
|
||||
"delete_user",
|
||||
"authenticate_user",
|
||||
"get_task",
|
||||
"get_task_by_user",
|
||||
"get_tasks",
|
||||
"create_task",
|
||||
"update_task",
|
||||
"delete_task",
|
||||
"get_category",
|
||||
"get_category_by_user",
|
||||
"get_categories",
|
||||
"create_category",
|
||||
"update_category",
|
||||
"delete_category",
|
||||
]
|
86
app/crud/category.py
Normal file
86
app/crud/category.py
Normal file
@ -0,0 +1,86 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.category import Category
|
||||
from app.schemas.category import CategoryCreate, CategoryUpdate
|
||||
|
||||
|
||||
def get_category(db: Session, category_id: int) -> Optional[Category]:
|
||||
"""
|
||||
Get a category by ID
|
||||
"""
|
||||
return db.query(Category).filter(Category.id == category_id).first()
|
||||
|
||||
|
||||
def get_category_by_user(
|
||||
db: Session, category_id: int, user_id: int
|
||||
) -> Optional[Category]:
|
||||
"""
|
||||
Get a category by ID for a specific user
|
||||
"""
|
||||
return db.query(Category).filter(
|
||||
Category.id == category_id, Category.owner_id == user_id
|
||||
).first()
|
||||
|
||||
|
||||
def get_categories(
|
||||
db: Session, user_id: int, skip: int = 0, limit: int = 100
|
||||
) -> List[Category]:
|
||||
"""
|
||||
Get all categories for a user
|
||||
"""
|
||||
return db.query(Category).filter(
|
||||
Category.owner_id == user_id
|
||||
).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def create_category(
|
||||
db: Session, category_in: CategoryCreate, user_id: int
|
||||
) -> Category:
|
||||
"""
|
||||
Create a new category for a user
|
||||
"""
|
||||
db_category = Category(
|
||||
**category_in.dict(),
|
||||
owner_id=user_id,
|
||||
)
|
||||
db.add(db_category)
|
||||
db.commit()
|
||||
db.refresh(db_category)
|
||||
return db_category
|
||||
|
||||
|
||||
def update_category(
|
||||
db: Session, category_id: int, category_in: CategoryUpdate, user_id: int
|
||||
) -> Optional[Category]:
|
||||
"""
|
||||
Update a category
|
||||
"""
|
||||
db_category = get_category_by_user(db, category_id, user_id)
|
||||
if not db_category:
|
||||
return None
|
||||
|
||||
update_data = category_in.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_category, field, value)
|
||||
|
||||
db.add(db_category)
|
||||
db.commit()
|
||||
db.refresh(db_category)
|
||||
return db_category
|
||||
|
||||
|
||||
def delete_category(
|
||||
db: Session, category_id: int, user_id: int
|
||||
) -> Optional[Category]:
|
||||
"""
|
||||
Delete a category
|
||||
"""
|
||||
db_category = get_category_by_user(db, category_id, user_id)
|
||||
if not db_category:
|
||||
return None
|
||||
|
||||
db.delete(db_category)
|
||||
db.commit()
|
||||
return db_category
|
108
app/crud/task.py
Normal file
108
app/crud/task.py
Normal file
@ -0,0 +1,108 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.task import Task
|
||||
from app.schemas.task import TaskCreate, TaskUpdate
|
||||
|
||||
|
||||
def get_task(db: Session, task_id: int) -> Optional[Task]:
|
||||
"""
|
||||
Get a task by ID
|
||||
"""
|
||||
return db.query(Task).filter(Task.id == task_id).first()
|
||||
|
||||
|
||||
def get_task_by_user(db: Session, task_id: int, user_id: int) -> Optional[Task]:
|
||||
"""
|
||||
Get a task by ID for a specific user
|
||||
"""
|
||||
return db.query(Task).filter(
|
||||
Task.id == task_id, Task.owner_id == user_id
|
||||
).first()
|
||||
|
||||
|
||||
def get_tasks(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
completed: Optional[bool] = None,
|
||||
category_id: Optional[int] = None,
|
||||
search: Optional[str] = None,
|
||||
priority: Optional[str] = None,
|
||||
) -> List[Task]:
|
||||
"""
|
||||
Get all tasks for a user with optional filtering
|
||||
"""
|
||||
query = db.query(Task).filter(Task.owner_id == user_id)
|
||||
|
||||
# Apply filters
|
||||
if completed is not None:
|
||||
query = query.filter(Task.is_completed == completed)
|
||||
|
||||
if category_id:
|
||||
query = query.filter(Task.category_id == category_id)
|
||||
|
||||
if search:
|
||||
search_term = f"%{search}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Task.title.ilike(search_term),
|
||||
Task.description.ilike(search_term)
|
||||
)
|
||||
)
|
||||
|
||||
if priority:
|
||||
query = query.filter(Task.priority == priority)
|
||||
|
||||
# Apply pagination and return results
|
||||
return query.order_by(Task.created_at.desc()).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def create_task(db: Session, task_in: TaskCreate, user_id: int) -> Task:
|
||||
"""
|
||||
Create a new task for a user
|
||||
"""
|
||||
db_task = Task(
|
||||
**task_in.dict(),
|
||||
owner_id=user_id,
|
||||
)
|
||||
db.add(db_task)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
|
||||
def update_task(
|
||||
db: Session, task_id: int, task_in: TaskUpdate, user_id: int
|
||||
) -> Optional[Task]:
|
||||
"""
|
||||
Update a task
|
||||
"""
|
||||
db_task = get_task_by_user(db, task_id, user_id)
|
||||
if not db_task:
|
||||
return None
|
||||
|
||||
update_data = task_in.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_task, field, value)
|
||||
|
||||
db.add(db_task)
|
||||
db.commit()
|
||||
db.refresh(db_task)
|
||||
return db_task
|
||||
|
||||
|
||||
def delete_task(db: Session, task_id: int, user_id: int) -> Optional[Task]:
|
||||
"""
|
||||
Delete a task
|
||||
"""
|
||||
db_task = get_task_by_user(db, task_id, user_id)
|
||||
if not db_task:
|
||||
return None
|
||||
|
||||
db.delete(db_task)
|
||||
db.commit()
|
||||
return db_task
|
99
app/crud/user.py
Normal file
99
app/crud/user.py
Normal file
@ -0,0 +1,99 @@
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
|
||||
|
||||
def get_user(db: Session, user_id: int) -> Optional[User]:
|
||||
"""
|
||||
Get a user by ID
|
||||
"""
|
||||
return db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
|
||||
def get_user_by_email(db: Session, email: str) -> Optional[User]:
|
||||
"""
|
||||
Get a user by email
|
||||
"""
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
|
||||
|
||||
def get_user_by_username(db: Session, username: str) -> Optional[User]:
|
||||
"""
|
||||
Get a user by username
|
||||
"""
|
||||
return db.query(User).filter(User.username == username).first()
|
||||
|
||||
|
||||
def get_users(db: Session, skip: int = 0, limit: int = 100):
|
||||
"""
|
||||
Get multiple users with pagination
|
||||
"""
|
||||
return db.query(User).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
"""
|
||||
Create a new user
|
||||
"""
|
||||
db_user = User(
|
||||
email=user_in.email,
|
||||
username=user_in.username,
|
||||
hashed_password=get_password_hash(user_in.password),
|
||||
is_active=True,
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def update_user(db: Session, user_id: int, user_in: UserUpdate) -> Optional[User]:
|
||||
"""
|
||||
Update a user
|
||||
"""
|
||||
db_user = get_user(db, user_id)
|
||||
if not db_user:
|
||||
return None
|
||||
|
||||
update_data = user_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
|
||||
|
||||
for field, value in update_data.items():
|
||||
setattr(db_user, field, value)
|
||||
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int) -> Optional[User]:
|
||||
"""
|
||||
Delete a user
|
||||
"""
|
||||
db_user = get_user(db, user_id)
|
||||
if not db_user:
|
||||
return None
|
||||
|
||||
db.delete(db_user)
|
||||
db.commit()
|
||||
return db_user
|
||||
|
||||
|
||||
def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
|
||||
"""
|
||||
Authenticate a user by email and password
|
||||
"""
|
||||
user = get_user_by_email(db, email=email)
|
||||
if not user:
|
||||
return None
|
||||
if not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
5
app/models/__init__.py
Normal file
5
app/models/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
from app.models.category import Category
|
||||
from app.models.task import Task
|
||||
from app.models.user import User
|
||||
|
||||
__all__ = ["User", "Task", "Category"]
|
22
app/models/category.py
Normal file
22
app/models/category.py
Normal file
@ -0,0 +1,22 @@
|
||||
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class Category(Base):
|
||||
__tablename__ = "categories"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String, nullable=False)
|
||||
color = Column(String, default="#FFFFFF") # Hexadecimal color code
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
# Foreign keys
|
||||
owner_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
|
||||
# Relationships
|
||||
owner = relationship("User", back_populates="categories")
|
||||
tasks = relationship("Task", back_populates="category")
|
34
app/models/task.py
Normal file
34
app/models/task.py
Normal file
@ -0,0 +1,34 @@
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
Column,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
Text,
|
||||
)
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class Task(Base):
|
||||
__tablename__ = "tasks"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String, index=True, nullable=False)
|
||||
description = Column(Text, nullable=True)
|
||||
is_completed = Column(Boolean, default=False)
|
||||
due_date = Column(DateTime(timezone=True), nullable=True)
|
||||
priority = Column(String, default="medium") # low, medium, high
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
||||
|
||||
# Foreign keys
|
||||
owner_id = Column(Integer, ForeignKey("users.id"), nullable=False)
|
||||
category_id = Column(Integer, ForeignKey("categories.id"), nullable=True)
|
||||
|
||||
# Relationships
|
||||
owner = relationship("User", back_populates="tasks")
|
||||
category = relationship("Category", back_populates="tasks")
|
21
app/models/user.py
Normal file
21
app/models/user.py
Normal file
@ -0,0 +1,21 @@
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, String
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.sql import func
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, 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)
|
||||
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())
|
||||
|
||||
# Relationships
|
||||
tasks = relationship("Task", back_populates="owner")
|
||||
categories = relationship("Category", back_populates="owner")
|
18
app/schemas/__init__.py
Normal file
18
app/schemas/__init__.py
Normal file
@ -0,0 +1,18 @@
|
||||
from app.schemas.category import Category, CategoryCreate, CategoryUpdate
|
||||
from app.schemas.task import Task, TaskCreate, TaskUpdate
|
||||
from app.schemas.token import Token, TokenPayload
|
||||
from app.schemas.user import User, UserCreate, UserUpdate
|
||||
|
||||
__all__ = [
|
||||
"User",
|
||||
"UserCreate",
|
||||
"UserUpdate",
|
||||
"Task",
|
||||
"TaskCreate",
|
||||
"TaskUpdate",
|
||||
"Category",
|
||||
"CategoryCreate",
|
||||
"CategoryUpdate",
|
||||
"Token",
|
||||
"TokenPayload",
|
||||
]
|
42
app/schemas/category.py
Normal file
42
app/schemas/category.py
Normal file
@ -0,0 +1,42 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# Shared properties
|
||||
class CategoryBase(BaseModel):
|
||||
name: Optional[str] = None
|
||||
color: Optional[str] = "#FFFFFF"
|
||||
|
||||
|
||||
# Properties to receive on category creation
|
||||
class CategoryCreate(CategoryBase):
|
||||
name: str = Field(..., min_length=1, max_length=50)
|
||||
|
||||
|
||||
# Properties to receive on category update
|
||||
class CategoryUpdate(CategoryBase):
|
||||
pass
|
||||
|
||||
|
||||
# Properties shared by models stored in DB
|
||||
class CategoryInDBBase(CategoryBase):
|
||||
id: int
|
||||
name: str
|
||||
owner_id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
# Properties to return to client
|
||||
class Category(CategoryInDBBase):
|
||||
pass
|
||||
|
||||
|
||||
# Properties stored in DB
|
||||
class CategoryInDB(CategoryInDBBase):
|
||||
pass
|
46
app/schemas/task.py
Normal file
46
app/schemas/task.py
Normal file
@ -0,0 +1,46 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# Shared properties
|
||||
class TaskBase(BaseModel):
|
||||
title: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
is_completed: Optional[bool] = False
|
||||
due_date: Optional[datetime] = None
|
||||
priority: Optional[str] = "medium"
|
||||
category_id: Optional[int] = None
|
||||
|
||||
|
||||
# Properties to receive on task creation
|
||||
class TaskCreate(TaskBase):
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
# Properties to receive on task update
|
||||
class TaskUpdate(TaskBase):
|
||||
pass
|
||||
|
||||
|
||||
# Properties shared by models stored in DB
|
||||
class TaskInDBBase(TaskBase):
|
||||
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 Task(TaskInDBBase):
|
||||
pass
|
||||
|
||||
|
||||
# Properties stored in DB
|
||||
class TaskInDB(TaskInDBBase):
|
||||
pass
|
12
app/schemas/token.py
Normal file
12
app/schemas/token.py
Normal 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
|
46
app/schemas/user.py
Normal file
46
app/schemas/user.py
Normal file
@ -0,0 +1,46 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
|
||||
|
||||
# Shared properties
|
||||
class UserBase(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
username: Optional[str] = None
|
||||
is_active: Optional[bool] = True
|
||||
|
||||
|
||||
# Properties to receive via API on creation
|
||||
class UserCreate(UserBase):
|
||||
email: EmailStr
|
||||
username: str
|
||||
password: str = Field(..., min_length=8)
|
||||
|
||||
|
||||
# Properties to receive via API on update
|
||||
class UserUpdate(UserBase):
|
||||
password: Optional[str] = Field(None, min_length=8)
|
||||
|
||||
|
||||
# Properties shared by models stored in DB
|
||||
class UserInDBBase(UserBase):
|
||||
id: int
|
||||
email: EmailStr
|
||||
username: str
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
# Properties to return via API
|
||||
class User(UserInDBBase):
|
||||
pass
|
||||
|
||||
|
||||
# Properties stored in DB but not returned
|
||||
class UserInDB(UserInDBBase):
|
||||
hashed_password: str
|
37
main.py
Normal file
37
main.py
Normal file
@ -0,0 +1,37 @@
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.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 all CORS enabled origins
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||
|
||||
|
||||
@app.get("/health", tags=["health"])
|
||||
async def health():
|
||||
"""
|
||||
Health check endpoint.
|
||||
Returns status of the application.
|
||||
"""
|
||||
return {"status": "healthy"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
98
migrations/env.py
Normal file
98
migrations/env.py
Normal file
@ -0,0 +1,98 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# 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)
|
||||
|
||||
# Import models for Alembic autogenerate support
|
||||
from app.core.database import Base
|
||||
from app.models import Category, Task, User
|
||||
|
||||
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"},
|
||||
render_as_batch=True,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection):
|
||||
is_sqlite = connection.dialect.name == 'sqlite'
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=is_sqlite,
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""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:
|
||||
do_run_migrations(connection)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
do_run_migrations(connection)
|
||||
|
||||
|
||||
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"}
|
79
migrations/versions/0001_initial_migration.py
Normal file
79
migrations/versions/0001_initial_migration.py
Normal file
@ -0,0 +1,79 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: 0001
|
||||
Revises: None
|
||||
Create Date: 2023-12-15
|
||||
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Create users table
|
||||
op.create_table(
|
||||
'users',
|
||||
sa.Column('id', sa.Integer(), 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('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_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 categories table
|
||||
op.create_table(
|
||||
'categories',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('color', 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.Column('owner_id', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_categories_id'), 'categories', ['id'], unique=False)
|
||||
|
||||
# Create tasks table
|
||||
op.create_table(
|
||||
'tasks',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('is_completed', sa.Boolean(), nullable=True),
|
||||
sa.Column('due_date', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('priority', 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.Column('owner_id', sa.Integer(), nullable=False),
|
||||
sa.Column('category_id', sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['category_id'], ['categories.id'], ),
|
||||
sa.ForeignKeyConstraint(['owner_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() -> None:
|
||||
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')
|
||||
op.drop_index(op.f('ix_categories_id'), table_name='categories')
|
||||
op.drop_table('categories')
|
||||
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')
|
25
pyproject.toml
Normal file
25
pyproject.toml
Normal file
@ -0,0 +1,25 @@
|
||||
[tool.ruff]
|
||||
target-version = "py310"
|
||||
line-length = 88
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = [
|
||||
"E", # pycodestyle errors
|
||||
"W", # pycodestyle warnings
|
||||
"F", # pyflakes
|
||||
"I", # isort
|
||||
"C", # flake8-comprehensions
|
||||
"B", # flake8-bugbear
|
||||
]
|
||||
ignore = [
|
||||
"E501", # line too long, handled by black
|
||||
"B008", # do not perform function calls in argument defaults
|
||||
"C901", # too complex
|
||||
]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
"__init__.py" = ["F401"]
|
||||
"migrations/env.py" = ["E402", "F401"]
|
||||
|
||||
[tool.ruff.lint.isort]
|
||||
known-third-party = ["fastapi", "pydantic", "sqlalchemy"]
|
11
requirements.txt
Normal file
11
requirements.txt
Normal file
@ -0,0 +1,11 @@
|
||||
fastapi>=0.105.0
|
||||
uvicorn>=0.24.0
|
||||
sqlalchemy>=2.0.23
|
||||
alembic>=1.12.1
|
||||
python-jose[cryptography]>=3.3.0
|
||||
passlib[bcrypt]>=1.7.4
|
||||
python-multipart>=0.0.6
|
||||
pydantic>=2.5.2
|
||||
pydantic-settings>=2.1.0
|
||||
python-dotenv>=1.0.0
|
||||
ruff>=0.1.6
|
Loading…
x
Reference in New Issue
Block a user