A modern web application built with FastAPI, featuring secure authentication with email verification, asynchronous PostgreSQL database integration using Tortoise ORM, database migrations managed by Aerich, asynchronous email sending via Celery with Redis as a message broker, and a comprehensive testing suite with Pytest.
- π High-Performance API: Built with FastAPI for rapid development and high performance.
- π Asynchronous PostgreSQL Integration: Utilizes
asyncpg
via Tortoise ORM for non-blocking database operations. - π’ ORM with Tortoise ORM: Leverages Tortoise ORM for intuitive asynchronous database interaction.
βοΈ Database Migrations with Aerich: Manages database schema changes using Aerich, a migration tool for Tortoise ORM.- π‘οΈ Secure Authentication:
- User registration with email verification (users are inactive until email is confirmed).
- OAuth2 Password Flow for token-based authentication.
- JWT (JSON Web Tokens) for access and refresh tokens using
PyJWT
, includingjti
claim for enhanced uniqueness. - Refresh Token rotation and server-side session management for enhanced security.
- Password hashing using
passlib
(bcrypt). - Logout functionality.
- Task Processing with Celery:
- π§ Asynchronous Email Sending: Email notifications (e.g., verification emails) are sent via Celery tasks, preventing blocking of API responses.
- π Scalable Background Workers: Celery workers can be scaled independently to handle varying loads of background tasks.
- Reliable Message Queuing with Redis: Uses Redis as a robust message broker for Celery.
- π§ Email Integration with
fastapi-mail
: Sends HTML templated emails for verification (now processed by Celery). - π§ͺ Testing with Pytest:
- Comprehensive unit and integration tests using
pytest
andpytest-asyncio
. - Test environment configured to use a dedicated PostgreSQL test database.
- Automated creation and teardown of the test database instance and schemas.
- Comprehensive unit and integration tests using
- π Standardized API Responses: Uses a
BaseResponse
model for consistent success and error responses. - π Pagination, Filtering & Sorting: Robust support for paginating, filtering, and sorting list results.
- π³ Dockerized Environment: Easy setup and deployment using Docker and Docker Compose for the main application, database, Redis, and Celery workers.
- π§ Development & Debugging:
- Live reload for development.
debugpy
support for debugging within Docker containers.
- βοΈ Configuration Management: Uses
pydantic-settings
for managing configurations via environment variables and.env
files. - π Custom Exception Handling: Centralized handlers for various exception types.
βοΈ CORS & GZip Middleware: Configured for Cross-Origin Resource Sharing and GZip compression.
- Python 3.13 or higher
- Docker and Docker Compose
- PostgreSQL server (if running locally without Docker, or for the test database)
- Redis server (if running locally without Docker for Celery broker)
-
Clone the repository:
git clone <repository-url> cd <project-directory>
-
Environment Variables (
.env
):- Copy
.env.example
(if one exists) to.env
. - Update the
.env
file with your settings. Key variables include:POSTGRES_USER
,POSTGRES_PASSWORD
,POSTGRES_DB
,POSTGRES_SERVER
,POSTGRES_PORT
.DATABASE_DSN
(e.g.,asyncpg://user:password@db:5432/dbname
).SECRET_KEY
(a strong, random key for JWTs).ACCESS_TOKEN_EXPIRE_MINUTES
,REFRESH_TOKEN_EXPIRE_MINUTES
.- Mail server settings (
MAIL_USERNAME
,MAIL_PASSWORD
, etc.). BASE_URL
(e.g.,http://localhost:8000
) for email verification links.- Celery Settings:
CELERY_BROKER_URL
(e.g.,redis://redis:6379/0
)CELERY_RESULT_BACKEND
(e.g.,redis://redis:6379/0
)
- For Testing (if running tests locally against a non-Dockerized PostgreSQL test DB):
TEST_POSTGRES_USER
,TEST_POSTGRES_PASSWORD
,TEST_POSTGRES_SERVER
,TEST_POSTGRES_PORT
,TEST_POSTGRES_DB
.TEST_DATABASE_DSN
(e.g.,asyncpg://test_user:test_password@localhost:5432/mydatabase_test
).
- The
app/core/config.py
file loads these settings.
- Copy
-
Build and run the application using Docker Compose:
docker-compose up --build -d
This will start the FastAPI application, PostgreSQL database, Redis, and Celery worker(s). The application will typically be available at
http://localhost:8000
. -
Database Migrations (Aerich): To generate a new migration:
docker-compose exec app aerich migrate --name <your_migration_name>
To apply migrations:
docker-compose exec app aerich upgrade
(The
app
service indocker-compose.yml
is also configured to attemptaerich upgrade
on startup).
-
Create a virtual environment and install dependencies:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate pip install -r requirements.txt
Ensure
requirements.txt
includescelery[redis]
. -
Set up environment variables (as described in the Docker section).
-
PostgreSQL & Redis Setup:
- Ensure your PostgreSQL and Redis servers are running and accessible.
- Create databases and users as needed.
-
Initialize Aerich and run migrations (as described in the Docker section, but run commands locally).
-
Run the FastAPI Application (Uvicorn):
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
-
Run the Celery Worker (Locally): In a separate terminal, navigate to the project root (where
PYTHONPATH
can see theapp
module) and run:celery -A app.worker.celery_app worker -l info --concurrency=1
(Adjust concurrency as needed).
This project uses pytest
. Tests are configured to run against a dedicated PostgreSQL test database.
-
Configure Test Database:
- Ensure environment variables for the test database are set in
.env
. - The PostgreSQL user (
TEST_POSTGRES_USER
) should ideally haveCREATEDB
privileges. - Test setup is in
tests/conftest.py
.
- Ensure environment variables for the test database are set in
-
Run Tests:
pytest
debugpy
is configured for debugging the FastAPI application within Docker.- For debugging Celery tasks, you can run the worker with a single concurrency (
--concurrency=1
) and usepdb
or other Python debugging tools within the task code. You can also execute tasks eagerly for debugging by configuring Celery for testing (task_always_eager = True
), but this bypasses the broker.
- Swagger UI:
http://localhost:8000/docs
- ReDoc:
http://localhost:8000/redoc
.
βββ app/
β βββ api/
β β βββ v1/
β β βββ endpoints/
β β β βββ auth.py
β β β βββ users.py
β β βββ routers.py
β βββ core/ # Config, security, dependencies, exceptions
β βββ db/ # Database setup (tortoise_config.py)
β βββ models/ # Tortoise ORM models
β βββ schemas/ # Pydantic schemas
β βββ services/ # Business logic
β βββ tasks/ # Celery tasks (e.g., email_tasks.py)
β βββ templates/ # Email templates
β β βββ email/
β β βββ verification_email.html
β βββ migrations/ # Aerich migration files
β βββ worker.py # Celery application instance setup
β βββ main.py # FastAPI app instantiation
β βββ settings.py # FastAPI app configuration settings
βββ tests/ # Pytest tests
β βββ conftest.py
β βββ api/
β βββ v1/
β βββ test_auth.py
β βββ test_users.py
βββ .env # Environment variables
βββ .vscode/ # VSCode specific settings
β βββ launch.json
β βββ settings.json
βββ Dockerfile
βββ docker-compose.yml
βββ requirements.txt
βββ aerich.ini
βββ pytest.ini
βββ README.md
This project is licensed under the terms of the Apache 2.0 license.
Contributions are welcome! Please follow standard fork, branch, commit, push, and Pull Request procedures.