Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
__pycache__
*.pyc
*.pyo
*.pyd
*.db
.env
.env.*
.venv
venv
.git
.gitignore
Dockerfile
**/__pycache__
**/*.py[cod]
**/*.log
alembic/versions/*.pyc
28 changes: 28 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: CI

on:
push:
branches: [ main ]
pull_request:

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Lint
run: |
ruff check .
black --check .
- name: Test
env:
DATABASE_URL: sqlite:///./test.db
run: |
pytest -q
84 changes: 84 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Virtual environments
.env
.venv
venv/
ENV/

# PyInstaller
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
pytest_cache/
.pytest_cache/

# MyPy / Ruff / Pylint
.mypy_cache/
.ruff_cache/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# dotenv
*.env
.env.*

# VS Code
.vscode/

# MacOS
.DS_Store

# Logs
logs/
*.log

# SQLite databases
*.db
app.db

docker-data/
29 changes: 29 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# syntax=docker/dockerfile:1.7-labs
FROM python:3.11-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1

WORKDIR /app

# Install system deps
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libpq-dev && rm -rf /var/lib/apt/lists/*

COPY requirements.txt ./
RUN pip install -r requirements.txt

COPY app ./app
COPY alembic.ini ./alembic.ini
COPY alembic ./alembic

# Non-root user
RUN useradd -u 10001 -r -s /sbin/nologin appuser && chown -R appuser:appuser /app
USER appuser

EXPOSE 8000

ENV PORT=8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
39 changes: 39 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
PYTHON ?= python3
PIP ?= $(PYTHON) -m pip
VENV ?= .venv
ACTIVATE = . $(VENV)/bin/activate

.PHONY: venv install dev run fmt lint test migrate revision alembic-upgrade

venv:
$(PYTHON) -m venv $(VENV)
$(ACTIVATE); $(PIP) install --upgrade pip

install: venv
$(ACTIVATE); $(PIP) install -r requirements.txt

dev: venv
$(ACTIVATE); $(PIP) install -r requirements-dev.txt

run:
$(ACTIVATE); UVICORN_WORKERS=$${UVICORN_WORKERS:-2} uvicorn app.main:app --host 0.0.0.0 --port $${PORT:-8000}

fmt:
$(ACTIVATE); ruff check --fix .
$(ACTIVATE); black .

lint:
$(ACTIVATE); ruff check .
$(ACTIVATE); black --check .

test:
DATABASE_URL=sqlite:///./test.db $(ACTIVATE); pytest

revision:
$(ACTIVATE); alembic revision --autogenerate -m "auto"

migrate:
$(ACTIVATE); alembic upgrade head

alembic-upgrade:
$(ACTIVATE); alembic upgrade head
84 changes: 72 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,72 @@
- 👋 Hi, I’m @Qomserver
- 👀 I’m interested in ...
- 🌱 I’m currently learning ...
- 💞️ I’m looking to collaborate on ...
- 📫 How to reach me ...
- 😄 Pronouns: ...
- ⚡ Fun fact: ...

<!---
Qomserver/Qomserver is a ✨ special ✨ repository because its `README.md` (this file) appears on your GitHub profile.
You can click the Preview link to take a look at your changes.
--->
# Production-Ready FastAPI Service

A secure, scalable, and production-ready FastAPI service with JWT auth, SQLAlchemy, Alembic migrations, rate limiting, metrics, Docker, CI, and Kubernetes manifests.

## Features
- FastAPI with pydantic v2
- JWT authentication (access tokens)
- SQLAlchemy 2.0 ORM + Alembic migrations
- Rate limiting (slowapi)
- Prometheus metrics at `/metrics`
- Health probes at `/health/live` and `/health/ready`
- Dockerfile and docker-compose for local Postgres
- CI (lint + tests) via GitHub Actions
- Kubernetes manifests

## Quickstart (local)
1. Python 3.11+
2. Create virtualenv and install deps:
```bash
make dev
```
3. Run API (SQLite by default):
```bash
make run
```
4. Open docs: `http://localhost:8000/docs`

## Environment
Copy `.env.example` to `.env` and adjust as needed. Key vars:
- `SECRET_KEY` (required in production)
- `DATABASE_URL` (Postgres in prod; SQLite default for dev/tests)
- `FIRST_SUPERUSER_EMAIL`, `FIRST_SUPERUSER_PASSWORD` (optional bootstrap)
- `ALLOW_USER_REGISTRATION` (default: true)

## Docker (local with Postgres)
```bash
docker compose up --build
```

## Migrations
```bash
make migrate # apply
make revision # create new from models
```

## Tests
```bash
make test
```

## Deploy
- Build container image with `Dockerfile`
- Use `k8s/` manifests or integrate into your platform (ECS, GKE, etc.)
- Configure probes and resources as shown in `k8s/deployment.yaml`

## Security
- Set strong `SECRET_KEY`
- Run behind HTTPS (ingress/ALB)
- Review CORS settings in `app/main.py`
- Rotate tokens, limit exposure

## Structure
```
app/
api/ routes, deps
core/ config, security
db/ engine, base
models/
schemas/
middleware/
utils/
```
35 changes: 35 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
[alembic]
script_location = alembic
sqlalchemy.url = %(DATABASE_URL)s

[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console

[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
50 changes: 50 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config, pool

from alembic import context
from app import models # noqa: F401 - ensure models loaded
from app.core.config import settings
from app.db.base import Base

config = context.config

if config.config_file_name is not None:
fileConfig(config.config_file_name)

config.set_main_option("sqlalchemy.url", settings.database_url)

target_metadata = Base.metadata


def run_migrations_offline() -> None:
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online() -> None:
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
Loading
Loading