Initial commit

This commit is contained in:
pptx704
2025-08-03 03:48:31 +03:00
commit 5a0e23cea8
23 changed files with 2551 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

12
.env.example Normal file
View File

@ -0,0 +1,12 @@
POSTGRES_USER=
POSTGRES_PASSWORD=
POSTGRES_DB=
JWT_SECRET=
JWT_ALGORITHM=
JWT_EXPIRE_MINUTES=
MONGO_USER=
MONGO_PASSWORD=
MONGO_DATABASE=
MONGO_HOST=

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

25
Dockerfile Normal file
View File

@ -0,0 +1,25 @@
FROM python:3.12-slim
# Turns off buffering for easier container logging
ENV PYTHONUNBUFFERED=1
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 poetry run alembic upgrade head; poetry run fastapi run

61
README.md Normal file
View File

@ -0,0 +1,61 @@
# Omukk FastAPI Template
Template repository for all FastAPI backend projects developed by Omukk.
## Components
- Basic FastAPI dependencies
- MongoDB with Beanie ODM for database operations
- Docker and Docker Compose for easier testing
- 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. **Set up environment variables**:
Create a `.env` file using the `.env.example` file as a reference.
3. **Run database server**:
```bash
docker compose up db -d
```
4. **Run Dev Server**:
```bash
docker compose up backend --build
```
5. **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.

0
app/__init__.py Normal file
View File

0
app/const.py Normal file
View File

25
app/database.py Normal file
View File

@ -0,0 +1,25 @@
from pymongo import AsyncMongoClient
from beanie import init_beanie
from app.models import User
from app.settings import settings
async def init_db():
"""Initialize database connection and Beanie ODM"""
try:
client = AsyncMongoClient(settings.MONGODB_URL)
await client.admin.command('ping')
await init_beanie(
database=client[settings.MONGODB_DATABASE],
document_models=[User]
)
except Exception as e:
raise
async def close_db():
"""Close database connection"""
client = AsyncMongoClient(settings.MONGODB_URL)
await client.close()

22
app/models.py Normal file
View File

@ -0,0 +1,22 @@
import uuid
from datetime import datetime, UTC
from beanie import Document, Indexed
from pydantic import Field
class User(Document):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
username: str = Indexed(unique=True)
hashed_password: str
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
class Settings:
name = "users"
class Config:
json_encoders = {
datetime: lambda v: v.isoformat(),
uuid.UUID: lambda v: str(v),
}

View File

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

@ -0,0 +1,6 @@
from fastapi import HTTPException, status
from beanie import PydanticObjectId
from app import schemas
from app.models import User
from app.security import create_jwt_token, get_password_hash, verify_password

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

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

@ -0,0 +1,8 @@
from fastapi import APIRouter, Depends, HTTPException, status
from app import schemas
from app.repositories import auth
from app.security import create_jwt_token
from app.settings import settings
router = APIRouter(prefix="", tags=["auth"])

14
app/schemas.py Normal file
View File

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

65
app/security.py Normal file
View File

@ -0,0 +1,65 @@
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.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)

18
app/settings.py Normal file
View File

@ -0,0 +1,18 @@
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
MONGODB_URL: str
MONGODB_DATABASE: str
settings = Settings()

0
app/utils.py Normal file
View File

37
docker-compose.prod.yml Normal file
View File

@ -0,0 +1,37 @@
services:
backend:
image: fastapi
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- JWT_SECRET=${JWT_SECRET}
- JWT_ALGORITHM=${JWT_ALGORITHM}
- JWT_EXPIRE_MINUTES=${JWT_EXPIRE_MINUTES}
- MONGODB_URL=mongodb://${MONGODB_USER}:${MONGODB_PASSWORD}@${MONGODB_HOST}:27017
- MONGODB_DATABASE=${MONGODB_DATABASE}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
env_file:
- .env
db:
image: mongo:7.0
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGODB_USER}
- MONGO_INITDB_ROOT_PASSWORD=${MONGODB_PASSWORD}
- MONGO_INITDB_DATABASE=${MONGODB_DATABASE}
volumes:
- ./docker-data/mongo:/data/db
restart: unless-stopped
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 5s
timeout: 5s
retries: 5
env_file:
- .env

40
docker-compose.yml Normal file
View File

@ -0,0 +1,40 @@
services:
backend:
image: fastapi
build:
context: .
dockerfile: Dockerfile
ports:
- "8000:8000"
environment:
- JWT_SECRET=${JWT_SECRET}
- JWT_ALGORITHM=${JWT_ALGORITHM}
- JWT_EXPIRE_MINUTES=${JWT_EXPIRE_MINUTES}
- MONGODB_URL=mongodb://${MONGODB_USER}:${MONGODB_PASSWORD}@db:27017
- MONGODB_DATABASE=${MONGODB_DATABASE}
depends_on:
db:
condition: service_healthy
restart: unless-stopped
env_file:
- .env
command: fastapi dev --host 0.0.0.0
volumes:
- ./app:/app/app
db:
image: mongo:7.0
environment:
- MONGO_INITDB_ROOT_USERNAME=${MONGODB_USER}
- MONGO_INITDB_ROOT_PASSWORD=${MONGODB_PASSWORD}
- MONGO_INITDB_DATABASE=${MONGODB_DATABASE}
ports:
- "27017:27017"
restart: unless-stopped
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 5s
timeout: 5s
retries: 5
env_file:
- .env

32
main.py Normal file
View File

@ -0,0 +1,32 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.database import init_db, close_db
from app.routers import auth
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize database connection on startup"""
await init_db()
yield
await close_db()
app = FastAPI(lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def index() -> dict[str, str]:
return {"version": "0.1.0"}
app.include_router(auth.router)

1844
poetry.lock generated Normal file

File diff suppressed because it is too large Load Diff

37
pyproject.toml Normal file
View File

@ -0,0 +1,37 @@
[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"
beanie = "^1.25.0"
pyjwt = "^2.10.1"
python-dotenv = "^1.1.0"
[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