Initial commit

This commit is contained in:
2025-07-03 05:37:33 +00:00
commit bcb64faf74
27 changed files with 2599 additions and 0 deletions

101
.dockerignore Normal file
View File

@ -0,0 +1,101 @@
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual environments
venv/
env/
ENV/
.venv/
.env/
# Poetry
poetry.lock
# Testing
.pytest_cache/
.coverage
htmlcov/
.tox/
.nox/
coverage.xml
*.cover
.hypothesis/
# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Git
.git/
.gitignore
# Docker
Dockerfile
docker-compose.yml
.dockerignore
# Database
*.db
*.sqlite
*.sqlite3
# Logs
*.log
logs/
# Environment files
.env
.env.local
.env.development
.env.test
.env.production
# Documentation
docs/
# Temporary files
*.tmp
*.temp
.cache/
# Node.js (if any frontend assets)
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Local development
docker-data/
test.db

9
.env.example Normal file
View File

@ -0,0 +1,9 @@
POSTGRES_USER=
POSTGRES_PASSWORD=
POSTGRES_DB=
JWT_SECRET=
JWT_ALGORITHM=
JWT_EXPIRE_MINUTES=
SQLALCHEMY_DATABASE_URL=

177
.gitignore vendored Normal file
View File

@ -0,0 +1,177 @@
# ---> Python
# 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
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
#uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
docker-data/

27
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,27 @@
repos:
- repo: local
hooks:
- id: isort
name: isort
entry: poetry run isort app main.py
language: system
types: [python]
args: ["--profile", "black"]
pass_filenames: false
- id: black
name: black
entry: poetry run black app main.py
language: system
types: [python]
args: ["--line-length", "80"]
pass_filenames: false
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-merge-conflict

27
Dockerfile Normal file
View File

@ -0,0 +1,27 @@
FROM python:3.12-slim
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
COPY --from=ghcr.io/ufoscout/docker-compose-wait:latest /wait /wait
WORKDIR /app
# Install poetry
RUN pip install poetry
# Configure poetry to not create virtual environment in container
RUN poetry config virtualenvs.create false
# Copy poetry files
COPY pyproject.toml poetry.lock* /app/
# Install dependencies
RUN poetry install --only main --no-root --no-directory
COPY . /app
RUN poetry install --only main
EXPOSE 8000
CMD /wait; poetry run alembic upgrade head; poetry run fastapi run

56
README.md Normal file
View File

@ -0,0 +1,56 @@
# Omukk FastAPI Template
Template repository for all FastAPI backend projects developed by Omukk.
## Components
- Basic FastAPI dependencies
- Docker and Docker Compose for easier testing
- Alembic configuration for database migrations
- Initial codebase to start from
## Using this template
1. **Create a new repository from this template**:
- In Omukk Repos, navigate to [this repository](https://git.omukk.dev/pptx704/fastapi-template)
- Click the "Use this template" button at the top of the page
- Choose "Create a new repository"
- Fill in your new repository details and click "Create Repository"
2. **Clone your new repository**:
```bash
git clone git@git.omukk.dev/<username>/<repo>.git
cd <repo>
```
## Development and Testing
1. **Install dependencies**:
```
poetry install
poetry run pre-commit install
```
2. **Run database server**:
```bash
docker compose up db -d
```
3. **Run Dev Server**:
```bash
poetry run fastapi dev
```
4. **Stop Database Server**:
```bash
docker compose down db
```
## Development Rules
- Create a separate branch from `dev` and create a PR to `dev` after making changes
- Branch names must be meaningful. Check [docs](https://docs.omukk.dev/doc/repos-bvFEDvytPz) for more details
- Always run `black` and `isort` to maintain code consistency (this is done automatically using pre-commit hooks)-
```bash
poetry run isort app main.py
poetry run black app main.py
# Make sure to run isort first
```
- Use static type checking using `mypy` if you feel like it (It is recommended but not mandatory). Static type checking might help you to identify critical bugs.

110
alembic.ini Normal file
View File

@ -0,0 +1,110 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# 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 alembic/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:alembic/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 =
[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

1
alembic/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

82
alembic/env.py Normal file
View File

@ -0,0 +1,82 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from app.settings import settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URL)
# 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 import models, database
target_metadata = database.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"},
)
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:
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()

24
alembic/script.py.mako Normal file
View File

@ -0,0 +1,24 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

0
app/__init__.py Normal file
View File

0
app/const.py Normal file
View File

19
app/database.py Normal file
View File

@ -0,0 +1,19 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from .const import SQLALCHEMY_DATABASE_URL
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

17
app/models.py Normal file
View File

@ -0,0 +1,17 @@
import uuid
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
PrimaryKeyConstraint,
String,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from sqlalchemy.schema import Index
from sqlalchemy.sql import func
from app.database import Base

View File

6
app/repositories/auth.py Normal file
View File

@ -0,0 +1,6 @@
from fastapi import HTTPException, status
from sqlalchemy.orm import Session
from .. import schemas
from ..models import User
from ..security import create_jwt_token, get_password_hash, verify_password

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

11
app/routers/auth.py Normal file
View File

@ -0,0 +1,11 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from app import database, schemas
from .. import schemas
from ..database import get_db
from ..repositories import auth
from ..security import get_user
router = APIRouter(prefix="", tags=["auth"])

17
app/schemas.py Normal file
View File

@ -0,0 +1,17 @@
import datetime
import enum
import uuid
from typing import List, Optional
from pydantic import BaseModel, EmailStr
class BaseResponse(BaseModel):
message: str
class User(BaseModel):
id: uuid.UUID
class Config:
orm_mode = True

66
app/security.py Normal file
View File

@ -0,0 +1,66 @@
import os
from datetime import UTC, datetime, timedelta
import jwt
from bcrypt import checkpw, gensalt, hashpw
from fastapi import HTTPException, Security
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from app import schemas
from app.database import SessionLocal
from app.models import User
from app.settings import settings
def get_password_hash(password: str) -> str:
return hashpw(password.encode("utf-8"), gensalt()).decode("utf-8")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return checkpw(
plain_password.encode("utf-8"), hashed_password.encode("utf-8")
)
def create_jwt_token(data: dict) -> str:
_ed = timedelta(minutes=settings.JWT_EXPIRE_MINUTES)
iat = datetime.now(UTC)
exp = datetime.now(UTC) + _ed
token_payload = data
token_payload.update({"iat": iat, "exp": exp})
token = jwt.encode(
token_payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM
)
return token
def get_user_from_token(token: str) -> schemas.User:
try:
payload = jwt.decode(
token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM]
)
except jwt.ExpiredSignatureError:
raise HTTPException(status_code=401, detail="Token has expired")
except jwt.JWTError:
raise HTTPException(
status_code=401, detail="Invalid authentication credentials"
)
user_id = payload.get("user_id")
# Return user from database
...
def get_user(
authorization: HTTPAuthorizationCredentials = Security(HTTPBearer()),
) -> schemas.User:
if authorization.scheme.lower() != "bearer":
raise HTTPException(
status_code=401, detail="Invalid authentication scheme"
)
token = authorization.credentials
return get_user_from_token(token)

16
app/settings.py Normal file
View File

@ -0,0 +1,16 @@
import os
from dotenv import load_dotenv
from pydantic_settings import BaseSettings
load_dotenv()
class Settings(BaseSettings):
JWT_SECRET: str
JWT_ALGORITHM: str
JWT_EXPIRE_MINUTES: int
SQLALCHEMY_DATABASE_URL: str
settings = Settings()

0
app/utils.py Normal file
View File

24
docker-compose.yml Normal file
View File

@ -0,0 +1,24 @@
version: '3.1'
services:
backend:
image: fastapi
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- JWT_SECRET=${JWT_SECRET}
- JWT_ALGORITHM=${JWT_ALGORITHM:-HS256}
- JWT_EXPIRE_MINUTES=${JWT_EXPIRE_MINUTES:-60}
- DATABASE_URL=postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
- WAIT_HOSTS=db:5432
depends_on:
- db
db:
image: postgres:15.3
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB}

21
main.py Normal file
View File

@ -0,0 +1,21 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import auth
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def index() -> str:
return "Version 0.0.1"
app.include_router(auth.router)

1741
poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

39
pyproject.toml Normal file
View File

@ -0,0 +1,39 @@
[project]
name = "app"
version = "0.1.0"
description = "Fastapi Poetry Template"
authors = [
{name = "pptx704"},
]
readme = "README.md"
requires-python = "^3.12"
[build-system]
requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.poetry.dependencies]
bcrypt = "^4.3.0"
fastapi = {extras = ["standard"], version = "^0.115.13"}
pydantic-settings = "^2.10.0"
sqlalchemy = "^2.0.41"
pyjwt = "^2.10.1"
alembic = "^1.16.2"
python-dotenv = "^1.1.0"
psycopg2-binary = "^2.9.10"
[tool.poetry.group.dev.dependencies]
pytest = "^8.4.1"
pytest-asyncio = "^1.0.0"
httpx = "^0.28.1"
black = "^25.1.0"
isort = "^6.0.1"
pre-commit = "^4.2.0"
[tool.black]
line-length = 80
[tool.isort]
profile = "black"
line_length = 80

8
requirements.txt Normal file
View File

@ -0,0 +1,8 @@
bcrypt==4.0.1
fastapi[standard]~=0.115.12
pydantic-settings~=2.9.1
sqlalchemy~=2.0.41
passlib~=1.7.4
pyjwt~=2.10.1
alembic~=1.16.1
python-dotenv~=1.1.0