Initial commit
This commit is contained in:
7
.env.example
Normal file
7
.env.example
Normal file
@ -0,0 +1,7 @@
|
||||
POSTGRES_USER=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_DB=
|
||||
|
||||
JWT_SECRET=
|
||||
JWT_ALGORITHM=
|
||||
JWT_EXPIRE_MINUTES=
|
||||
17
Dockerfile
Normal file
17
Dockerfile
Normal file
@ -0,0 +1,17 @@
|
||||
FROM python:3.14.0a3-slim
|
||||
|
||||
# Turns off buffering for easier container logging
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
COPY --from=ghcr.io/ufoscout/docker-compose-wait:latest /wait /wait
|
||||
|
||||
# Install pip requirements
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
||||
|
||||
WORKDIR /
|
||||
COPY . /
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD /wait; alembic upgrade head; uvicorn main:app --host 0.0.0.0
|
||||
24
README.md
24
README.md
@ -1,3 +1,23 @@
|
||||
# fastapi-template
|
||||
# Omukk FastAPI Template
|
||||
|
||||
Template files for all fastapi projects
|
||||
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>
|
||||
```
|
||||
|
||||
110
alembic.ini
Normal file
110
alembic.ini
Normal 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
1
alembic/README
Normal file
@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
82
alembic/env.py
Normal file
82
alembic/env.py
Normal 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.const import SQLALCHEMY_DATABASE_URL
|
||||
|
||||
# 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", 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
24
alembic/script.py.mako
Normal 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
0
app/__init__.py
Normal file
0
app/const.py
Normal file
0
app/const.py
Normal file
21
app/database.py
Normal file
21
app/database.py
Normal file
@ -0,0 +1,21 @@
|
||||
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()
|
||||
7
app/models.py
Normal file
7
app/models.py
Normal file
@ -0,0 +1,7 @@
|
||||
from app.database import Base
|
||||
from sqlalchemy.sql import func
|
||||
import uuid
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey, PrimaryKeyConstraint
|
||||
from sqlalchemy.orm import relationship
|
||||
from sqlalchemy.schema import Index
|
||||
0
app/repositories/__init__.py
Normal file
0
app/repositories/__init__.py
Normal file
6
app/repositories/auth.py
Normal file
6
app/repositories/auth.py
Normal 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 get_password_hash, verify_password, create_jwt_token
|
||||
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
14
app/routers/auth.py
Normal file
14
app/routers/auth.py
Normal file
@ -0,0 +1,14 @@
|
||||
from app import database, schemas
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..repositories import auth
|
||||
from .. import schemas
|
||||
|
||||
from ..security import get_user
|
||||
from ..database import get_db
|
||||
|
||||
router = APIRouter(
|
||||
prefix = "",
|
||||
tags = ['auth']
|
||||
)
|
||||
14
app/schemas.py
Normal file
14
app/schemas.py
Normal file
@ -0,0 +1,14 @@
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel, EmailStr
|
||||
import uuid
|
||||
import enum
|
||||
import datetime
|
||||
|
||||
class BaseResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
class User(BaseModel):
|
||||
id: uuid.UUID
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
52
app/security.py
Normal file
52
app/security.py
Normal file
@ -0,0 +1,52 @@
|
||||
import os
|
||||
from passlib.context import CryptContext
|
||||
import jwt
|
||||
from datetime import datetime, timedelta, UTC
|
||||
|
||||
from app.models import User
|
||||
|
||||
from fastapi import Security, HTTPException
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from .database import get_db
|
||||
from .models import User
|
||||
from .settings import settings
|
||||
|
||||
from . import schemas
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"])
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
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")
|
||||
|
||||
...
|
||||
|
||||
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)
|
||||
13
app/settings.py
Normal file
13
app/settings.py
Normal file
@ -0,0 +1,13 @@
|
||||
import os
|
||||
from pydantic_settings import BaseSettings
|
||||
from dotenv import load_dotenv
|
||||
|
||||
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
0
app/utils.py
Normal file
24
docker-compose.yml
Normal file
24
docker-compose.yml
Normal 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}
|
||||
20
main.py
Normal file
20
main.py
Normal file
@ -0,0 +1,20 @@
|
||||
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)
|
||||
8
requirements.txt
Normal file
8
requirements.txt
Normal 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
|
||||
Reference in New Issue
Block a user