This project is being usend as a boilerplate for creating new services in the company. It is including a set of features that are common for most of the services, such as authentication, authorization, session management, user data management, role-based access control, team management, visibility group.
- FastAPI with Python 3.12, totally asynchronous
- VUE.JS
- Postgres
- Airflow
- Redis (PubSub and TimeSeries)
- SQLAlchemy with Alembic for migrations and asynchronous I/O (asyncio) support
- Poetry
- Tests on
pytestwith automatic rollback after each test case - Database session stored in python's
context variable - Configs for
pyright,ruff,isortandblackin pyproject.toml alembicfor database migrations- CI/CD with GitLab
├── api
├── endpoints
├── v1
├── v2
├── app
├── module-name
├── crud.py
├── model.py
├── schema.py
├── service.py
├── admin.py
├── crud.py
├── main.py
├── model.py
├── core
├── base
├── cache
├── constants.py
├── context.py
├── errors.py
├── exceptions.py
├── logger.py
├── middleware.py
├── mixin.py
├── report.py
├── sdui.py
├── security.py
├── settings.py
├── sso.py
├── utils.py
├── dags
├── data
├── docker
├── integration
├── jobs
├── microservices
├── authoriser
├── redis-event-relay
├── migrations
├── observability
├── pipelines
├── terraform.yml
├── terraform
├── tests
├── api
├── test_module-name
├── integration
├── unit
├── wiki
Базая структура выглядит следующим образом:
api— presentation layerapp— предметная область приложения, ключевая часть приложения, где сосредоточеная вся бизнес-логика и взаимодействие с даннымиmodel.py— доменные сущности: таблицы в БДcrud.py— коллекции данных, некий стандартизированный интерфейс работы с сущностями, тут не сосредоточена логика, тут есть только относительно тривиальные операции ввода/выводаschema.py— pydantic-схемы, валидацияservice.py— содержит бизнес-логика, где происходит работа с сущностями/репозиториями.
core— ядро, системные вызовы, коннекторы, настройки, не предметно-ориентированный код, а уровень инфраструктурыdagsdata- SQL scripts for database populationdocker- Dockerfilesintegration- интеграции с внешними сервисами и/или инструментами (Postgres, Redis, Airflow, etc.)jobs- задачи, которые выполняются по расписаниюmicroservices- микросервисы, которые деплоятся в отдельные контейнеры, а именно auythorizer (авторизация и аутентификация) и redis-event-relay (для работы с pub/sub в Redis)migrations- миграции базы данных, которые создаются с помощью Alembicobservability- инструменты для мониторинга и логирования, такие как Prometheus, Grafana, Sentrypipelines- пайплайны для CI/CD, такие как Terraformterraform- Terraform конфигурации для инфраструктурыtests- тесты, которые делятся на:api- тесты для APIintegration- интеграционные тестыunit- юнит-тесты
wiki- документация по проекту, в которой описаны основные моменты, такие как архитектура, схемы баз данных, API и т.д.
В итоге, получается такая схема:
apiвзаимодействует сserviceserviceреализуют логику и взаимодействуют сcrudпо контрактам изschemascrudвзаимодействует с хранилищами (postgres/redis) по контрактам изschemas, используяmodelsи возвращают данные
- /openapi.json - Openapi
- /auth/admin - Admin panel
- /docs - Swagger documentation
- /redoc - ReDoc documentation
- /mkdocs - MkDocs documentation
-
Branching: for naming use task id
- Example: KTN-28127219
-
Merge request naming:
- Draft: feat(entity-name): short-description
- Use
Draftstatus as an indicator if MR not ready for merge - Use
featkeyword if MR includes new feature - Example - Draft: feat(product): add new fields
- Use
- feat(entity-name): short-description
- Remove Draft if MR is ready for MR
- fix(entity-name): short-description
- Use
fixkeyword if MR includes bug fixies
- Use
- Draft: feat(entity-name): short-description
- Master: деплой в окружения Production, Staging, Development Merge to Master: Team Lead Deploy: Team Lead
- Stage: деплой в окружение Staging, Development Merge to Stable: Team Lead Deploy: Team Lead
- Other: деплой в окружение Development Merge: Anyone Deploy: Anyone
После merge stage to production нужно обновить ветку stage из master Локально сделать git branch -D stage git checkout master git pull origin master git checkout -b stage git push origin stage --force
- В корне проекта alembic revision --autogenerate -m "name" создаем миграцию make create migrations name=init
- alembic upgrade head применить миграцию
- Создать симлинки
cp .env.example .env.development && ln -sf .env.development .env- Загрузить .env в окружение
source .env-
Install pyenv https://github.com/pyenv/pyenv#installation
-
Install poetry
curl -sSL https://install.python-poetry.org | python3 -- Install python
pyenv install 3.11.5 && pyenv global 3.11.5- Set interpreter
poetry env use 3.11.5- Check Poetry’s Python Environment
poetry env info- Install dependencies.
poetry lock --no-update && poetry install --no-root- Run project
poetry run python3 app/main.py- Setup pre-commit hooks
pre-commit installcore.hooksPath should be deleted
- Kill service on specific port
fuser -k 8000/tcp- Test API via curl
curl -X POST -d '' http://0.0.0.0:8000/api/v1/auth/-
Install
pre-commit(if you haven't already):pip install pre-commit
-
Install the pre-commit hooks specified in your
.pre-commit-config.yamlfile by running:pre-commit install
This command sets up pre-commit to automatically run the hooks defined in your configuration before each commit.
-
Run the hooks manually (optional): If you want to run the hooks on all files (instead of just the staged files), you can use:
pre-commit run --all-files
Once installed, each time you make a commit, pre-commit will automatically run isort, black, ruff, and mypy to format and lint your code as specified.
wrk -c30 -t3 -d10s -H "Authorization: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhcnRlbS5rdXN0aWtvdkBnbWFpbC5jb20iLCJ1aWQiOjUsImZuIjpudWxsLCJsbiI6bnVsbCwicGVybWlzc2lvbnMiOiJ1c2VyIiwiZXhwIjoxNjU0MDIxODg2fQ.439CjqvKtBMvIXBEmH0FLW98Te51ur-VBlTsaS7AkhI" http://localhost:8888/api/users/me --timeout 5
Running 10s test @ http://localhost:8888/api/users/me
3 threads and 30 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 49.86ms 23.51ms 167.93ms 67.88%
Req/Sec 201.13 28.65 343.00 71.00%
6013 requests in 10.01s, 1.18MB read
Requests/sec: 600.77
Transfer/sec: 121.03KB