init
This commit is contained in:
commit
0dd23f6de0
33 changed files with 881 additions and 0 deletions
1
.alembic/README
Normal file
1
.alembic/README
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
Generic single-database configuration.
|
||||||
77
.alembic/env.py
Normal file
77
.alembic/env.py
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
from src.config import SQLALCHEMY_DATABASE_URI
|
||||||
|
|
||||||
|
from src.database import Base
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# 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
|
||||||
|
target_metadata = 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 = create_engine(SQLALCHEMY_DATABASE_URI.get_secret_value())
|
||||||
|
|
||||||
|
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()
|
||||||
28
.alembic/script.py.mako
Normal file
28
.alembic/script.py.mako
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Upgrade schema."""
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Downgrade schema."""
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
209
.gitignore
vendored
Normal file
209
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[codz]
|
||||||
|
*$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
|
||||||
|
#poetry.toml
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
||||||
|
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
||||||
|
#pdm.lock
|
||||||
|
#pdm.toml
|
||||||
|
.pdm-python
|
||||||
|
.pdm-build/
|
||||||
|
|
||||||
|
# pixi
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
||||||
|
#pixi.lock
|
||||||
|
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
||||||
|
# in the .venv directory. It is recommended not to include this directory in version control.
|
||||||
|
.pixi
|
||||||
|
|
||||||
|
# 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
|
||||||
|
.envrc
|
||||||
|
.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/
|
||||||
|
|
||||||
|
# Abstra
|
||||||
|
# Abstra is an AI-powered process automation framework.
|
||||||
|
# Ignore directories containing user credentials, local state, and settings.
|
||||||
|
# Learn more at https://abstra.io/docs
|
||||||
|
.abstra/
|
||||||
|
|
||||||
|
# Visual Studio Code
|
||||||
|
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
||||||
|
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
||||||
|
# you could uncomment the following to ignore the entire vscode folder
|
||||||
|
# .vscode/
|
||||||
|
|
||||||
|
# Ruff stuff:
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# PyPI configuration file
|
||||||
|
.pypirc
|
||||||
|
|
||||||
|
# Cursor
|
||||||
|
# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
|
||||||
|
# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
|
||||||
|
# refer to https://docs.cursor.com/context/ignore-files
|
||||||
|
.cursorignore
|
||||||
|
.cursorindexingignore
|
||||||
|
|
||||||
|
# Marimo
|
||||||
|
marimo/_static/
|
||||||
|
marimo/_lsp/
|
||||||
|
__marimo__/
|
||||||
|
|
||||||
|
temp_files/
|
||||||
149
alembic.ini
Normal file
149
alembic.ini
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts.
|
||||||
|
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||||
|
# format, relative to the token %(here)s which refers to the location of this
|
||||||
|
# ini file
|
||||||
|
script_location = %(here)s/.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
|
||||||
|
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||||
|
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory. for multiple paths, the path separator
|
||||||
|
# is defined by "path_separator" below.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the tzdata library which can be installed by adding
|
||||||
|
# `alembic[tz]` to the pip requirements.
|
||||||
|
# string value is passed to ZoneInfo()
|
||||||
|
# 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 <script_location>/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 "path_separator"
|
||||||
|
# below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||||
|
|
||||||
|
# path_separator; This indicates what character is used to split lists of file
|
||||||
|
# paths, including version_locations and prepend_sys_path within configparser
|
||||||
|
# files such as alembic.ini.
|
||||||
|
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||||
|
# to provide os-dependent path splitting.
|
||||||
|
#
|
||||||
|
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||||
|
# take place if path_separator is not present in alembic.ini. If this
|
||||||
|
# option is omitted entirely, fallback logic is as follows:
|
||||||
|
#
|
||||||
|
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||||
|
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||||
|
# behavior of splitting on spaces and/or commas.
|
||||||
|
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||||
|
# behavior of splitting on spaces, commas, or colons.
|
||||||
|
#
|
||||||
|
# Valid values for path_separator are:
|
||||||
|
#
|
||||||
|
# path_separator = :
|
||||||
|
# path_separator = ;
|
||||||
|
# path_separator = space
|
||||||
|
# path_separator = newline
|
||||||
|
#
|
||||||
|
# Use os.pathsep. Default configuration used for new projects.
|
||||||
|
path_separator = os
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
# database URL. This is consumed by the user-maintained env.py script only.
|
||||||
|
# other means of configuring database URLs may be customized within the env.py
|
||||||
|
# file.
|
||||||
|
sqlalchemy.url = none
|
||||||
|
|
||||||
|
|
||||||
|
[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
|
||||||
|
|
||||||
|
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = module
|
||||||
|
# ruff.module = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||||
|
# hooks = ruff
|
||||||
|
# ruff.type = exec
|
||||||
|
# ruff.executable = ruff
|
||||||
|
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration. This is also consumed by the user-maintained
|
||||||
|
# env.py script only.
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
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
|
||||||
21
requirements.txt
Normal file
21
requirements.txt
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
fastapi
|
||||||
|
pydantic
|
||||||
|
uvicorn
|
||||||
|
jinja2
|
||||||
|
python-dotenv
|
||||||
|
requests
|
||||||
|
itsdangerous
|
||||||
|
starlette
|
||||||
|
pydantic-settings
|
||||||
|
authlib
|
||||||
|
joserfc
|
||||||
|
httpx
|
||||||
|
types-authlib
|
||||||
|
python-jose
|
||||||
|
pytest
|
||||||
|
uvloop; sys_platform != 'win32'
|
||||||
|
sqlalchemy
|
||||||
|
httptools
|
||||||
|
psycopg
|
||||||
|
alembic
|
||||||
|
prometheus-client
|
||||||
5
src/_module_template/config.py
Normal file
5
src/_module_template/config.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Configurations for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/constants.py
Normal file
5
src/_module_template/constants.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Constants and error codes for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/dependencies.py
Normal file
5
src/_module_template/dependencies.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Router dependencies for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/exceptions.py
Normal file
5
src/_module_template/exceptions.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Module specific exceptions for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/models.py
Normal file
5
src/_module_template/models.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Database models for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
11
src/_module_template/router.py
Normal file
11
src/_module_template/router.py
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
"""
|
||||||
|
Router endpoints for the _____ module
|
||||||
|
|
||||||
|
Endpoints:
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
tags=[""],
|
||||||
|
)
|
||||||
5
src/_module_template/schemas.py
Normal file
5
src/_module_template/schemas.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Pydantic models for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/service.py
Normal file
5
src/_module_template/service.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Module specific business logic for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/_module_template/utils.py
Normal file
5
src/_module_template/utils.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Non-business logic reusable functions and classes for the _____ module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
17
src/api.py
Normal file
17
src/api.py
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
"""
|
||||||
|
This module hooks the routers for the main endpoints into a single router for importing to the app.
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from src.auth.router import router as auth_router
|
||||||
|
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
|
||||||
|
api_router.include_router(auth_router)
|
||||||
|
|
||||||
|
|
||||||
|
@api_router.get("/healthcheck", include_in_schema=False)
|
||||||
|
def healthcheck():
|
||||||
|
"""Simple health check endpoint."""
|
||||||
|
return {"status": "ok"}
|
||||||
16
src/auth/config.py
Normal file
16
src/auth/config.py
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
"""
|
||||||
|
Configurations for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- auth_settings: Configs for auth loaded from environment variables
|
||||||
|
"""
|
||||||
|
from src.config import CustomBaseSettings
|
||||||
|
|
||||||
|
class AuthConfig(CustomBaseSettings):
|
||||||
|
OIDC_CONFIG: str = ""
|
||||||
|
OIDC_ISSUER: str = ""
|
||||||
|
OIDC_AUDIENCE: str = ""
|
||||||
|
CLIENT_ID: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
auth_settings = AuthConfig()
|
||||||
5
src/auth/constants.py
Normal file
5
src/auth/constants.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Constants and error codes for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/auth/dependencies.py
Normal file
5
src/auth/dependencies.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Router dependencies for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/auth/exceptions.py
Normal file
5
src/auth/exceptions.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Module specific exceptions for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
5
src/auth/models.py
Normal file
5
src/auth/models.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Database models for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
20
src/auth/router.py
Normal file
20
src/auth/router.py
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
"""
|
||||||
|
Router endpoints for auth module
|
||||||
|
Contains oauth registration
|
||||||
|
|
||||||
|
Endpoints:
|
||||||
|
- /auth/me/claims: Test endpoint returning user claims
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from src.auth.service import claims_dependency
|
||||||
|
|
||||||
|
router = APIRouter(
|
||||||
|
tags=["auth"],
|
||||||
|
prefix="/auth",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me/claims")
|
||||||
|
async def current_user_claims(user: claims_dependency):
|
||||||
|
return user
|
||||||
5
src/auth/schemas.py
Normal file
5
src/auth/schemas.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Pydantic models for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
50
src/auth/service.py
Normal file
50
src/auth/service.py
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
"""
|
||||||
|
Module specific business logic for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- claims_dependency
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from typing import Annotated, Any
|
||||||
|
from joserfc import jwt
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
|
from fastapi import Depends
|
||||||
|
from fastapi.security import OpenIdConnect
|
||||||
|
from joserfc.jwk import KeySet
|
||||||
|
|
||||||
|
from src.auth.config import auth_settings
|
||||||
|
|
||||||
|
|
||||||
|
oidc = OpenIdConnect(openIdConnectUrl=auth_settings.OIDC_CONFIG)
|
||||||
|
oidc_dependency = Annotated[str, Depends(oidc)]
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(oidc_auth_string: oidc_dependency) -> dict[str, Any]:
|
||||||
|
config_url = urlopen(auth_settings.OIDC_CONFIG)
|
||||||
|
config = json.loads(config_url.read())
|
||||||
|
jwks_uri = config["jwks_uri"]
|
||||||
|
key_response = requests.get(jwks_uri)
|
||||||
|
jwk_keys = KeySet.import_key_set(key_response.json())
|
||||||
|
|
||||||
|
claims_options = {
|
||||||
|
"exp": {"essential": True},
|
||||||
|
"aud": {"essential": True, "value": "account"},
|
||||||
|
"iss": {"essential": True, "value": auth_settings.OIDC_ISSUER},
|
||||||
|
}
|
||||||
|
|
||||||
|
token = jwt.decode(
|
||||||
|
oidc_auth_string.replace("Bearer ", ""),
|
||||||
|
jwk_keys
|
||||||
|
)
|
||||||
|
|
||||||
|
claims_requests = jwt.JWTClaimsRegistry(**claims_options)
|
||||||
|
|
||||||
|
claims_requests.validate(token.claims)
|
||||||
|
|
||||||
|
return token.claims
|
||||||
|
|
||||||
|
|
||||||
|
claims_dependency = Annotated[dict[str, Any], Depends(get_current_user)]
|
||||||
5
src/auth/utils.py
Normal file
5
src/auth/utils.py
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
"""
|
||||||
|
Non-business logic reusable functions and classes for auth module
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
"""
|
||||||
54
src/config.py
Normal file
54
src/config.py
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
"""
|
||||||
|
Global configurations
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- settings: Global configs loaded from environment variables
|
||||||
|
- CustomBaseSettings - Base class to be used by all modules for loading configs
|
||||||
|
"""
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
from urllib import parse
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
from pydantic import SecretStr
|
||||||
|
|
||||||
|
from src.constants import Environment
|
||||||
|
|
||||||
|
|
||||||
|
class CustomBaseSettings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(
|
||||||
|
env_file=".env", env_file_encoding="utf-8", extra="ignore"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Config(CustomBaseSettings):
|
||||||
|
APP_VERSION: str = "0.1"
|
||||||
|
ENVIRONMENT: Environment = Environment.PRODUCTION
|
||||||
|
SECRET_KEY: SecretStr = ""
|
||||||
|
|
||||||
|
CORS_ORIGINS: list[str] = ["*"]
|
||||||
|
CORS_ORIGINS_REGEX: str | None = None
|
||||||
|
CORS_HEADERS: list[str] = ["*"]
|
||||||
|
|
||||||
|
DATABASE_NAME: str = "fastapi-exp"
|
||||||
|
DATABASE_PORT: str = "5432"
|
||||||
|
DATABASE_HOSTNAME: str = "localhost"
|
||||||
|
DATABASE_CREDENTIALS: SecretStr = ""
|
||||||
|
|
||||||
|
settings = Config()
|
||||||
|
|
||||||
|
DATABASE_NAME = settings.DATABASE_NAME
|
||||||
|
DATABASE_PORT = settings.DATABASE_PORT
|
||||||
|
DATABASE_HOSTNAME = settings.DATABASE_HOSTNAME
|
||||||
|
DATABASE_CREDENTIALS = settings.DATABASE_CREDENTIALS.get_secret_value()
|
||||||
|
# this will support special chars for credentials
|
||||||
|
_DATABASE_CREDENTIAL_USER, _DATABASE_CREDENTIAL_PASSWORD = str(DATABASE_CREDENTIALS).split(":")
|
||||||
|
_QUOTED_DATABASE_PASSWORD = parse.quote_plus(str(_DATABASE_CREDENTIAL_PASSWORD))
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URI = SecretStr(f"postgresql+psycopg://{_DATABASE_CREDENTIAL_USER}:{_QUOTED_DATABASE_PASSWORD}@{DATABASE_HOSTNAME}:{DATABASE_PORT}/{DATABASE_NAME}")
|
||||||
|
|
||||||
|
app_configs: dict[str, Any] = {"title": "App API"}
|
||||||
|
if settings.ENVIRONMENT.is_deployed:
|
||||||
|
app_configs["root_path"] = f"/v{settings.APP_VERSION}"
|
||||||
|
|
||||||
|
if not settings.ENVIRONMENT.is_debug:
|
||||||
|
app_configs["openapi_url"] = None # hide docs
|
||||||
36
src/constants.py
Normal file
36
src/constants.py
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
"""
|
||||||
|
Global constants
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- Environment(StrEnum): LOCAL, TESTING, STAGING, PRODUCTION
|
||||||
|
"""
|
||||||
|
from enum import StrEnum, auto
|
||||||
|
|
||||||
|
|
||||||
|
class Environment(StrEnum):
|
||||||
|
"""
|
||||||
|
Enumeration of environments.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
LOCAL (str): Application is running locally
|
||||||
|
TESTING (str): Application is running in testing mode
|
||||||
|
STAGING (str): Application is running in staging mode (ie not testing)
|
||||||
|
PRODUCTION (str): Application is running in production mode
|
||||||
|
"""
|
||||||
|
|
||||||
|
LOCAL = auto()
|
||||||
|
TESTING = auto()
|
||||||
|
STAGING = auto()
|
||||||
|
PRODUCTION = auto()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_debug(self):
|
||||||
|
return self in (self.LOCAL, self.STAGING, self.TESTING)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_testing(self):
|
||||||
|
return self == self.TESTING
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_deployed(self) -> bool:
|
||||||
|
return self in (self.STAGING, self.PRODUCTION)
|
||||||
32
src/database.py
Normal file
32
src/database.py
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
"""
|
||||||
|
Database connections and init
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- db_dependency
|
||||||
|
- Base (sqlalchemy base model)
|
||||||
|
"""
|
||||||
|
from typing import Annotated
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import declarative_base, sessionmaker, Session
|
||||||
|
|
||||||
|
from fastapi import Depends
|
||||||
|
|
||||||
|
from src.config import SQLALCHEMY_DATABASE_URI
|
||||||
|
|
||||||
|
engine = create_engine(SQLALCHEMY_DATABASE_URI.get_secret_value())
|
||||||
|
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
except:
|
||||||
|
db.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
db_dependency = Annotated[Session, Depends(get_db)]
|
||||||
|
Base = declarative_base()
|
||||||
3
src/exceptions.py
Normal file
3
src/exceptions.py
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
"""
|
||||||
|
Global exceptions
|
||||||
|
"""
|
||||||
61
src/main.py
Normal file
61
src/main.py
Normal file
|
|
@ -0,0 +1,61 @@
|
||||||
|
"""
|
||||||
|
Application root file: Inits the FastAPI application
|
||||||
|
|
||||||
|
Prometheus client mounted at /metrics endpoint
|
||||||
|
Middleware: Session, CORS
|
||||||
|
"""
|
||||||
|
from contextlib import asynccontextmanager
|
||||||
|
from typing import AsyncGenerator
|
||||||
|
from prometheus_client import make_asgi_app
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from starlette.middleware.sessions import SessionMiddleware
|
||||||
|
from starlette.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from src.config import settings, app_configs
|
||||||
|
from src.api import api_router
|
||||||
|
|
||||||
|
from src.auth.config import auth_settings
|
||||||
|
|
||||||
|
|
||||||
|
@asynccontextmanager
|
||||||
|
async def lifespan(_application: FastAPI) -> AsyncGenerator:
|
||||||
|
# Startup
|
||||||
|
yield
|
||||||
|
# Shutdown
|
||||||
|
|
||||||
|
|
||||||
|
if settings.ENVIRONMENT.is_deployed:
|
||||||
|
# Do this only on prod
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
swagger_ui_init_oauth={
|
||||||
|
"clientId": auth_settings.CLIENT_ID,
|
||||||
|
"usePkceWithAuthorizationCodeGrant": True,
|
||||||
|
"scopes": "openid profile email",
|
||||||
|
},
|
||||||
|
**app_configs
|
||||||
|
)
|
||||||
|
|
||||||
|
metrics_app = make_asgi_app()
|
||||||
|
app.mount("/metrics", metrics_app)
|
||||||
|
|
||||||
|
# Type inspection disabled for middleware injection.
|
||||||
|
# Known bug in FastAPI type checking: https://github.com/astral-sh/ty/issues/1635
|
||||||
|
# noinspection PyTypeChecker
|
||||||
|
app.add_middleware(SessionMiddleware, secret_key=settings.SECRET_KEY.get_secret_value())
|
||||||
|
# noinspection PyTypeChecker
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=settings.CORS_ORIGINS,
|
||||||
|
allow_origin_regex=settings.CORS_ORIGINS_REGEX,
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"),
|
||||||
|
allow_headers=settings.CORS_HEADERS,
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(api_router)
|
||||||
|
|
||||||
|
print(f"Running in environment: {settings.ENVIRONMENT}")
|
||||||
4
src/models.py
Normal file
4
src/models.py
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
"""
|
||||||
|
Global database models
|
||||||
|
"""
|
||||||
|
|
||||||
12
src/schemas.py
Normal file
12
src/schemas.py
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
"""
|
||||||
|
Global Pydantic models
|
||||||
|
|
||||||
|
Exports:
|
||||||
|
- CustomBaseModel: Pydantic BaseModel with extra parameters
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class CustomBaseModel(BaseModel):
|
||||||
|
pass
|
||||||
10
template.env
Normal file
10
template.env
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
SECRET_KEY=""
|
||||||
|
OIDC_CONFIG=""
|
||||||
|
OIDC_ISSUER=""
|
||||||
|
OIDC_AUDIENCE=""
|
||||||
|
CLIENT_ID=""
|
||||||
|
|
||||||
|
DATABASE_NAME=""
|
||||||
|
DATABASE_PORT=""
|
||||||
|
DATABASE_HOSTNAME=""
|
||||||
|
DATABASE_CREDENTIALS=""
|
||||||
Loading…
Add table
Add a link
Reference in a new issue