Build task manager API with FastAPI and SQLite
- Set up project structure with FastAPI - Implement SQLAlchemy models for User and Task - Create Alembic migrations - Implement authentication with JWT - Add CRUD operations for tasks - Add task filtering and prioritization - Configure health check endpoint - Update README with project documentation
This commit is contained in:
parent
32eec478d8
commit
28f6914da1
138
README.md
138
README.md
@ -1,3 +1,137 @@
|
|||||||
# 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
|
||||||
|
|
||||||
|
- User registration and authentication with JWT tokens
|
||||||
|
- CRUD operations for tasks
|
||||||
|
- Task filtering by status
|
||||||
|
- Task prioritization
|
||||||
|
- Due dates and completion tracking
|
||||||
|
- Health check endpoint
|
||||||
|
- OpenAPI documentation
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8+
|
||||||
|
- pip (Python package manager)
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone this repository:
|
||||||
|
```bash
|
||||||
|
git clone <repository-url>
|
||||||
|
cd taskmanagerapi-oyn0px
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Set up environment variables (optional):
|
||||||
|
```bash
|
||||||
|
# For production, you should change these values
|
||||||
|
export SECRET_KEY="CHANGE_ME_IN_PRODUCTION"
|
||||||
|
export ACCESS_TOKEN_EXPIRE_MINUTES=10080 # 7 days
|
||||||
|
```
|
||||||
|
|
||||||
|
4. Apply database migrations:
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
5. Start the server:
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000
|
||||||
|
|
||||||
|
## API Documentation
|
||||||
|
|
||||||
|
Once the server is running, you can access the interactive API documentation at:
|
||||||
|
|
||||||
|
- Swagger UI: http://localhost:8000/docs
|
||||||
|
- ReDoc: http://localhost:8000/redoc
|
||||||
|
|
||||||
|
## 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 information
|
||||||
|
- `PATCH /api/v1/users/me` - Update current user information
|
||||||
|
|
||||||
|
### Tasks
|
||||||
|
|
||||||
|
- `GET /api/v1/tasks` - List all tasks for the current user
|
||||||
|
- `POST /api/v1/tasks` - Create a new task
|
||||||
|
- `GET /api/v1/tasks/{task_id}` - Get a specific task
|
||||||
|
- `PATCH /api/v1/tasks/{task_id}` - Update a task
|
||||||
|
- `DELETE /api/v1/tasks/{task_id}` - Delete a task
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
|
||||||
|
- `GET /health` - Check API health status
|
||||||
|
|
||||||
|
## Task Model
|
||||||
|
|
||||||
|
Tasks have the following properties:
|
||||||
|
|
||||||
|
- `id`: Unique identifier (string)
|
||||||
|
- `title`: Task title (string, required)
|
||||||
|
- `description`: Task description (string, optional)
|
||||||
|
- `status`: Task status (enum: todo, in_progress, done)
|
||||||
|
- `priority`: Task priority (enum: low, medium, high)
|
||||||
|
- `due_date`: Due date for the task (datetime, optional)
|
||||||
|
- `completed_at`: When the task was completed (datetime, set automatically when status changes to "done")
|
||||||
|
- `created_at`: When the task was created (datetime, automatic)
|
||||||
|
- `updated_at`: When the task was last updated (datetime, automatic)
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The API uses SQLite as the database. The database file is stored at `/app/storage/db/db.sqlite`.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
|
||||||
|
To run the tests (when implemented):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest
|
||||||
|
```
|
||||||
|
|
||||||
|
### Linting
|
||||||
|
|
||||||
|
To run linting:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
```
|
||||||
|
|
||||||
|
To automatically fix linting issues:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check --fix .
|
||||||
|
```
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
1. Fork the repository
|
||||||
|
2. Create your feature branch: `git checkout -b feature/my-new-feature`
|
||||||
|
3. Commit your changes: `git commit -am 'Add some feature'`
|
||||||
|
4. Push to the branch: `git push origin feature/my-new-feature`
|
||||||
|
5. Submit a pull request
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the MIT License - see the LICENSE file for details.
|
116
alembic.ini
Normal file
116
alembic.ini
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||||
|
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
1
app/api/__init__.py
Normal file
1
app/api/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
1
app/api/api_v1/__init__.py
Normal file
1
app/api/api_v1/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
8
app/api/api_v1/api.py
Normal file
8
app/api/api_v1/api.py
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.api_v1.endpoints import auth, tasks, users
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
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"])
|
49
app/api/api_v1/deps.py
Normal file
49
app/api/api_v1/deps.py
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
|
from jose import jwt, JWTError
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.db.session import SessionLocal
|
||||||
|
|
||||||
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.API_V1_STR}/auth/login")
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Generator:
|
||||||
|
try:
|
||||||
|
db = SessionLocal()
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
||||||
|
) -> models.User:
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(
|
||||||
|
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
||||||
|
)
|
||||||
|
token_data = schemas.TokenPayload(**payload)
|
||||||
|
except (JWTError, ValidationError):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Could not validate credentials",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
user = crud.user.get(db, id=token_data.sub)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_active_user(
|
||||||
|
current_user: models.User = Depends(get_current_user),
|
||||||
|
) -> models.User:
|
||||||
|
if not crud.user.is_active(current_user):
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
return current_user
|
1
app/api/api_v1/endpoints/__init__.py
Normal file
1
app/api/api_v1/endpoints/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
55
app/api/api_v1/endpoints/auth.py
Normal file
55
app/api/api_v1/endpoints/auth.py
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, schemas
|
||||||
|
from app.api.api_v1 import deps
|
||||||
|
from app.core import security
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=schemas.Token)
|
||||||
|
async def login_access_token(
|
||||||
|
db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends()
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
OAuth2 compatible token login, get an access token for future requests
|
||||||
|
"""
|
||||||
|
user = crud.user.authenticate(
|
||||||
|
db, email=form_data.username, password=form_data.password
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=400, detail="Incorrect email or password")
|
||||||
|
elif not crud.user.is_active(user):
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
return {
|
||||||
|
"access_token": security.create_access_token(
|
||||||
|
user.id, expires_delta=access_token_expires
|
||||||
|
),
|
||||||
|
"token_type": "bearer",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", response_model=schemas.User)
|
||||||
|
async def register_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_in: schemas.UserCreate,
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Register a new user
|
||||||
|
"""
|
||||||
|
user = crud.user.get_by_email(db, email=user_in.email)
|
||||||
|
if user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="A user with this email already exists",
|
||||||
|
)
|
||||||
|
user = crud.user.create(db, obj_in=user_in)
|
||||||
|
return user
|
111
app/api/api_v1/endpoints/tasks.py
Normal file
111
app/api/api_v1/endpoints/tasks.py
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.api.api_v1 import deps
|
||||||
|
from app.models.task import TaskStatus
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.Task])
|
||||||
|
async def read_tasks(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
status: Optional[TaskStatus] = None,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve tasks.
|
||||||
|
"""
|
||||||
|
if status:
|
||||||
|
tasks = crud.task.get_by_status(
|
||||||
|
db, owner_id=current_user.id, status=status, skip=skip, limit=limit
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
tasks = crud.task.get_multi_by_owner(
|
||||||
|
db, owner_id=current_user.id, skip=skip, limit=limit
|
||||||
|
)
|
||||||
|
return tasks
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.Task)
|
||||||
|
async def create_task(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
task_in: schemas.TaskCreate,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new task.
|
||||||
|
"""
|
||||||
|
task = crud.task.create_with_owner(db=db, obj_in=task_in, owner_id=current_user.id)
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{task_id}", response_model=schemas.Task)
|
||||||
|
async def read_task(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
task_id: str,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get task by ID.
|
||||||
|
"""
|
||||||
|
task = crud.task.get(db=db, id=task_id)
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
if task.owner_id != current_user.id:
|
||||||
|
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{task_id}", response_model=schemas.Task)
|
||||||
|
async def update_task(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
task_id: str,
|
||||||
|
task_in: schemas.TaskUpdate,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a task.
|
||||||
|
"""
|
||||||
|
task = crud.task.get(db=db, id=task_id)
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
if task.owner_id != current_user.id:
|
||||||
|
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||||
|
|
||||||
|
# Auto-update completed_at when status is changed to DONE
|
||||||
|
if task_in.status == TaskStatus.DONE and task.status != TaskStatus.DONE:
|
||||||
|
from datetime import datetime
|
||||||
|
task_in.completed_at = datetime.utcnow()
|
||||||
|
elif task_in.status is not None and task_in.status != TaskStatus.DONE and task.status == TaskStatus.DONE:
|
||||||
|
task_in.completed_at = None
|
||||||
|
|
||||||
|
task = crud.task.update(db=db, db_obj=task, obj_in=task_in)
|
||||||
|
return task
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{task_id}", status_code=204, response_model=None)
|
||||||
|
async def delete_task(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
task_id: str,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete a task.
|
||||||
|
"""
|
||||||
|
task = crud.task.get(db=db, id=task_id)
|
||||||
|
if not task:
|
||||||
|
raise HTTPException(status_code=404, detail="Task not found")
|
||||||
|
if task.owner_id != current_user.id:
|
||||||
|
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||||
|
crud.task.remove(db=db, id=task_id)
|
||||||
|
return None
|
33
app/api/api_v1/endpoints/users.py
Normal file
33
app/api/api_v1/endpoints/users.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.api.api_v1 import deps
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=schemas.User)
|
||||||
|
async def read_user_me(
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get current user.
|
||||||
|
"""
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/me", response_model=schemas.User)
|
||||||
|
async def update_user_me(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_in: schemas.UserUpdate,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update current user.
|
||||||
|
"""
|
||||||
|
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
|
||||||
|
return user
|
1
app/core/__init__.py
Normal file
1
app/core/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
41
app/core/config.py
Normal file
41
app/core/config.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
from typing import List
|
||||||
|
from pathlib import Path
|
||||||
|
from pydantic import AnyHttpUrl, validator
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
PROJECT_NAME: str = "Task Manager API"
|
||||||
|
PROJECT_DESCRIPTION: str = "A REST API for managing tasks"
|
||||||
|
|
||||||
|
# CORS settings
|
||||||
|
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||||
|
|
||||||
|
@validator("BACKEND_CORS_ORIGINS", pre=True)
|
||||||
|
def assemble_cors_origins(cls, v: str | List[str]) -> List[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 settings
|
||||||
|
SECRET_KEY: str = "CHANGE_ME_IN_PRODUCTION"
|
||||||
|
ALGORITHM: str = "HS256"
|
||||||
|
# 60 minutes * 24 hours * 7 days = 7 days
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 7
|
||||||
|
|
||||||
|
# Database settings
|
||||||
|
DB_DIR: Path = Path("/app") / "storage" / "db"
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env",
|
||||||
|
case_sensitive=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
settings = Settings()
|
29
app/core/security.py
Normal file
29
app/core/security.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
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)
|
3
app/crud/__init__.py
Normal file
3
app/crud/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# flake8: noqa
|
||||||
|
from app.crud.crud_user import user
|
||||||
|
from app.crud.crud_task import task
|
65
app/crud/base.py
Normal file
65
app/crud/base.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
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).
|
||||||
|
**Parameters**
|
||||||
|
* `model`: A SQLAlchemy model class
|
||||||
|
* `schema`: A Pydantic model (schema) class
|
||||||
|
"""
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def get(self, db: Session, id: Any) -> Optional[ModelType]:
|
||||||
|
return db.query(self.model).filter(self.model.id == id).first()
|
||||||
|
|
||||||
|
def get_multi(
|
||||||
|
self, db: Session, *, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[ModelType]:
|
||||||
|
return db.query(self.model).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
def create(self, db: Session, *, obj_in: CreateSchemaType, **kwargs) -> ModelType:
|
||||||
|
obj_in_data = jsonable_encoder(obj_in)
|
||||||
|
db_obj = self.model(**obj_in_data, **kwargs, id=str(uuid4()))
|
||||||
|
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: Any) -> ModelType:
|
||||||
|
obj = db.query(self.model).get(id)
|
||||||
|
db.delete(obj)
|
||||||
|
db.commit()
|
||||||
|
return obj
|
37
app/crud/crud_task.py
Normal file
37
app/crud/crud_task.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
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 create_with_owner(self, db: Session, *, obj_in: TaskCreate, owner_id: str) -> Task:
|
||||||
|
return super().create(db, obj_in=obj_in, owner_id=owner_id)
|
||||||
|
|
||||||
|
def get_multi_by_owner(
|
||||||
|
self, db: Session, *, owner_id: str, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[Task]:
|
||||||
|
return (
|
||||||
|
db.query(self.model)
|
||||||
|
.filter(Task.owner_id == owner_id)
|
||||||
|
.offset(skip)
|
||||||
|
.limit(limit)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_by_status(
|
||||||
|
self, db: Session, *, owner_id: str, status: TaskStatus, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[Task]:
|
||||||
|
return (
|
||||||
|
db.query(self.model)
|
||||||
|
.filter(Task.owner_id == owner_id, Task.status == status)
|
||||||
|
.offset(skip)
|
||||||
|
.limit(limit)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
task = CRUDTask(Task)
|
51
app/crud/crud_user.py
Normal file
51
app/crud/crud_user.py
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
from typing import Any, Dict, Optional, Union
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.user import UserCreate, UserUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
|
||||||
|
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
|
||||||
|
return db.query(User).filter(User.email == email).first()
|
||||||
|
|
||||||
|
def create(self, db: Session, *, obj_in: UserCreate) -> User:
|
||||||
|
db_obj = User(
|
||||||
|
email=obj_in.email,
|
||||||
|
hashed_password=get_password_hash(obj_in.password),
|
||||||
|
is_active=obj_in.is_active,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
|
||||||
|
) -> User:
|
||||||
|
if isinstance(obj_in, dict):
|
||||||
|
update_data = obj_in
|
||||||
|
else:
|
||||||
|
update_data = obj_in.model_dump(exclude_unset=True)
|
||||||
|
if update_data.get("password"):
|
||||||
|
hashed_password = get_password_hash(update_data["password"])
|
||||||
|
del update_data["password"]
|
||||||
|
update_data["hashed_password"] = hashed_password
|
||||||
|
return super().update(db, db_obj=db_obj, obj_in=update_data)
|
||||||
|
|
||||||
|
def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
|
||||||
|
user = self.get_by_email(db, email=email)
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, user.hashed_password):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
|
||||||
|
def is_active(self, user: User) -> bool:
|
||||||
|
return user.is_active
|
||||||
|
|
||||||
|
|
||||||
|
user = CRUDUser(User)
|
1
app/db/__init__.py
Normal file
1
app/db/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# flake8: noqa
|
5
app/db/base.py
Normal file
5
app/db/base.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
# 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.user import User # noqa
|
||||||
|
from app.models.task import Task # noqa
|
13
app/db/base_class.py
Normal file
13
app/db/base_class.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
from typing import Any
|
||||||
|
from sqlalchemy.ext.declarative import declared_attr
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
id: Any
|
||||||
|
__name__: str
|
||||||
|
|
||||||
|
# Generate __tablename__ automatically
|
||||||
|
@declared_attr
|
||||||
|
def __tablename__(cls) -> str:
|
||||||
|
return cls.__name__.lower()
|
10
app/db/session.py
Normal file
10
app/db/session.py
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
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)
|
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
# flake8: noqa
|
||||||
|
from app.models.user import User
|
||||||
|
from app.models.task import Task, TaskStatus, TaskPriority
|
36
app/models/task.py
Normal file
36
app/models/task.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
from sqlalchemy import Column, ForeignKey, String, Text, DateTime, Enum
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
import enum
|
||||||
|
|
||||||
|
from app.db.base_class 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):
|
||||||
|
id = Column(String, primary_key=True, index=True)
|
||||||
|
title = Column(String, index=True, nullable=False)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
status = Column(Enum(TaskStatus), default=TaskStatus.TODO, nullable=False)
|
||||||
|
priority = Column(Enum(TaskPriority), default=TaskPriority.MEDIUM, nullable=False)
|
||||||
|
due_date = Column(DateTime, nullable=True)
|
||||||
|
completed_at = Column(DateTime, nullable=True)
|
||||||
|
created_at = Column(DateTime, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
owner_id = Column(String, ForeignKey("user.id", ondelete="CASCADE"), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
owner = relationship("User", back_populates="tasks")
|
17
app/models/user.py
Normal file
17
app/models/user.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
from sqlalchemy import Boolean, Column, String, DateTime
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
id = Column(String, primary_key=True, index=True)
|
||||||
|
email = Column(String, unique=True, index=True, nullable=False)
|
||||||
|
hashed_password = Column(String, nullable=False)
|
||||||
|
is_active = Column(Boolean(), default=True)
|
||||||
|
created_at = Column(DateTime, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
tasks = relationship("Task", back_populates="owner", cascade="all, delete-orphan")
|
4
app/schemas/__init__.py
Normal file
4
app/schemas/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
# flake8: noqa
|
||||||
|
from app.schemas.token import Token, TokenPayload
|
||||||
|
from app.schemas.user import User, UserCreate, UserInDB, UserUpdate
|
||||||
|
from app.schemas.task import Task, TaskCreate, TaskInDB, TaskUpdate
|
44
app/schemas/task.py
Normal file
44
app/schemas/task.py
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, Field, ConfigDict
|
||||||
|
|
||||||
|
from app.models.task import TaskPriority, TaskStatus
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class TaskBase(BaseModel):
|
||||||
|
title: str = Field(..., min_length=1, max_length=100)
|
||||||
|
description: Optional[str] = None
|
||||||
|
status: TaskStatus = TaskStatus.TODO
|
||||||
|
priority: TaskPriority = TaskPriority.MEDIUM
|
||||||
|
due_date: Optional[datetime] = None
|
||||||
|
|
||||||
|
# Properties to receive on task creation
|
||||||
|
class TaskCreate(TaskBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Properties to receive on task update
|
||||||
|
class TaskUpdate(BaseModel):
|
||||||
|
title: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||||
|
description: Optional[str] = None
|
||||||
|
status: Optional[TaskStatus] = None
|
||||||
|
priority: Optional[TaskPriority] = None
|
||||||
|
due_date: Optional[datetime] = None
|
||||||
|
completed_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
# Properties shared by models stored in DB
|
||||||
|
class TaskInDBBase(TaskBase):
|
||||||
|
id: str
|
||||||
|
owner_id: str
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
completed_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
model_config = ConfigDict(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
|
34
app/schemas/user.py
Normal file
34
app/schemas/user.py
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, EmailStr, Field, ConfigDict
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class UserBase(BaseModel):
|
||||||
|
email: EmailStr
|
||||||
|
is_active: bool = True
|
||||||
|
|
||||||
|
# Properties to receive on user creation
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
password: str = Field(..., min_length=8)
|
||||||
|
|
||||||
|
# Properties to receive on user update
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
password: Optional[str] = Field(None, min_length=8)
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
|
||||||
|
# Properties shared by models stored in DB
|
||||||
|
class UserInDBBase(UserBase):
|
||||||
|
id: str
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
# Properties to return to client
|
||||||
|
class User(UserInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Properties stored in DB
|
||||||
|
class UserInDB(UserInDBBase):
|
||||||
|
hashed_password: str
|
41
main.py
Normal file
41
main.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
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,
|
||||||
|
description=settings.PROJECT_DESCRIPTION,
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set up CORS
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"], # Allow all origins
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"], # Allow all methods
|
||||||
|
allow_headers=["*"], # Allow all headers
|
||||||
|
)
|
||||||
|
|
||||||
|
# Include API router
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/", tags=["Root"])
|
||||||
|
async def root():
|
||||||
|
return {
|
||||||
|
"title": settings.PROJECT_NAME,
|
||||||
|
"docs": "/docs",
|
||||||
|
"health": "/health"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", tags=["Health"])
|
||||||
|
async def health_check():
|
||||||
|
return {"status": "healthy"}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
23
migrations/README
Normal file
23
migrations/README
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
# Alembic Migrations
|
||||||
|
|
||||||
|
This directory contains database migration files for the Task Manager API.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
To apply migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
To generate a new migration:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic revision --autogenerate -m "description of changes"
|
||||||
|
```
|
||||||
|
|
||||||
|
To downgrade to a specific version:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic downgrade <revision>
|
||||||
|
```
|
85
migrations/env.py
Normal file
85
migrations/env.py
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
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() -> 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, # Important for SQLite migrations
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""
|
||||||
|
Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
is_sqlite = connection.dialect.name == "sqlite"
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
render_as_batch=is_sqlite, # Important for SQLite migrations
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
26
migrations/script.py.mako
Normal file
26
migrations/script.py.mako
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
76
migrations/versions/initial_migration.py
Normal file
76
migrations/versions/initial_migration.py
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 01_initial
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-07-16 00:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
import enum
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = '01_initial'
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Create Enum types
|
||||||
|
class TaskStatusEnum(enum.Enum):
|
||||||
|
TODO = "todo"
|
||||||
|
IN_PROGRESS = "in_progress"
|
||||||
|
DONE = "done"
|
||||||
|
|
||||||
|
|
||||||
|
class TaskPriorityEnum(enum.Enum):
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create user table
|
||||||
|
op.create_table(
|
||||||
|
'user',
|
||||||
|
sa.Column('id', sa.String(), nullable=False),
|
||||||
|
sa.Column('email', 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(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
|
||||||
|
op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False)
|
||||||
|
|
||||||
|
# Create task table
|
||||||
|
op.create_table(
|
||||||
|
'task',
|
||||||
|
sa.Column('id', sa.String(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('status', sa.Enum('todo', 'in_progress', 'done', name='taskstatus'), nullable=False),
|
||||||
|
sa.Column('priority', sa.Enum('low', 'medium', 'high', name='taskpriority'), nullable=False),
|
||||||
|
sa.Column('due_date', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('completed_at', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=True),
|
||||||
|
sa.Column('owner_id', sa.String(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['owner_id'], ['user.id'], ondelete='CASCADE'),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_task_id'), 'task', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_task_title'), 'task', ['title'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f('ix_task_title'), table_name='task')
|
||||||
|
op.drop_index(op.f('ix_task_id'), table_name='task')
|
||||||
|
op.drop_table('task')
|
||||||
|
op.drop_index(op.f('ix_user_id'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_email'), table_name='user')
|
||||||
|
op.drop_table('user')
|
11
requirements.txt
Normal file
11
requirements.txt
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
fastapi>=0.100.0,<0.101.0
|
||||||
|
uvicorn>=0.23.0,<0.24.0
|
||||||
|
pydantic>=2.0.0,<3.0.0
|
||||||
|
pydantic-settings>=2.0.0,<3.0.0
|
||||||
|
python-multipart>=0.0.6,<0.1.0
|
||||||
|
python-jose[cryptography]>=3.3.0,<4.0.0
|
||||||
|
passlib[bcrypt]>=1.7.4,<2.0.0
|
||||||
|
sqlalchemy>=2.0.0,<3.0.0
|
||||||
|
alembic>=1.11.0,<2.0.0
|
||||||
|
python-dotenv>=1.0.0,<2.0.0
|
||||||
|
ruff>=0.1.0,<0.2.0
|
Loading…
x
Reference in New Issue
Block a user