feat: project scaffold (FastAPI backend, React frontend, aiogram bot, docker-compose, CI/CD)
This commit is contained in:
1 parent
066deaca47
commit
71460ab56a
37 files changed
+936
No files matched your search
@@ -0,0 +1,20 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential libpq-dev curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["gunicorn", "app.main:app", "-k", "uvicorn.workers.UvicornWorker", \
|
||||
"-w", "4", "-b", "0.0.0.0:8000"]
|
||||
@@ -0,0 +1,38 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
sqlalchemy.url =
|
||||
|
||||
[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
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Окружение Alembic."""
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
from app.core.config import settings
|
||||
from app.db.session import Base
|
||||
import app.models # noqa: F401 — регистрация моделей
|
||||
|
||||
config = context.config
|
||||
config.set_main_option("sqlalchemy.url", settings.database_url)
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
context.configure(
|
||||
url=settings.database_url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
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()
|
||||
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,9 @@
|
||||
"""Служебные эндпоинты."""
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/ping")
|
||||
def ping() -> dict:
|
||||
return {"pong": True}
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Корневой роутер API v1."""
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1 import health
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router, tags=["system"])
|
||||
Whitespace-only changes.
@@ -0,0 +1,45 @@
|
||||
"""Конфигурация приложения (переменные окружения)."""
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
# Общие
|
||||
app_name: str = "opora"
|
||||
environment: str = "dev"
|
||||
debug: bool = False
|
||||
|
||||
# База данных
|
||||
database_url: str = "postgresql+psycopg://opora:opora@postgres:5432/opora"
|
||||
|
||||
# Redis / Celery
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
celery_broker_url: str = "redis://redis:6379/1"
|
||||
celery_result_backend: str = "redis://redis:6379/2"
|
||||
|
||||
# JWT
|
||||
jwt_secret: str = "change-me"
|
||||
jwt_algorithm: str = "HS256"
|
||||
access_token_ttl_days: int = 30
|
||||
refresh_token_ttl_days: int = 30
|
||||
|
||||
# CORS
|
||||
cors_origins: list[str] = ["https://opora.my-dpr.ru"]
|
||||
|
||||
# MinIO / S3
|
||||
s3_endpoint: str = "http://minio:9000"
|
||||
s3_access_key: str = "minio"
|
||||
s3_secret_key: str = "minio123"
|
||||
s3_bucket: str = "artifacts"
|
||||
|
||||
# Мессенджеры
|
||||
telegram_bot_token: str = ""
|
||||
max_bot_token: str = ""
|
||||
|
||||
# LLM
|
||||
openrouter_api_key: str = ""
|
||||
llm_model: str = "deepseek/deepseek-chat"
|
||||
|
||||
|
||||
settings = Settings()
|
||||
Whitespace-only changes.
@@ -0,0 +1,23 @@
|
||||
"""Подключение к БД и сессии SQLAlchemy."""
|
||||
from collections.abc import Generator
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True, future=True)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Базовый класс моделей."""
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""Зависимость FastAPI: сессия БД."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Точка входа FastAPI-приложения АС «Платформа ОПОРА РОССИИ»."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.v1.router import api_router
|
||||
from app.core.config import settings
|
||||
|
||||
app = FastAPI(
|
||||
title="АС «Платформа ОПОРА РОССИИ»",
|
||||
version="0.1.0",
|
||||
docs_url="/api/docs",
|
||||
openapi_url="/api/openapi.json",
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.get("/health", tags=["system"])
|
||||
def health() -> dict:
|
||||
"""Проверка работоспособности."""
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1,4 @@
|
||||
"""Модели данных."""
|
||||
from app.models.region import FederalDistrict, Region
|
||||
|
||||
__all__ = ["FederalDistrict", "Region"]
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Модели справочников: федеральные округа и регионы."""
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, String, func
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.db.session import Base
|
||||
|
||||
|
||||
class FederalDistrict(Base):
|
||||
__tablename__ = "federal_districts"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
code: Mapped[str | None] = mapped_column(String(20), unique=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
regions: Mapped[list["Region"]] = relationship(back_populates="district")
|
||||
|
||||
|
||||
class Region(Base):
|
||||
__tablename__ = "regions"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(200), unique=True)
|
||||
federal_district_id: Mapped[int] = mapped_column(ForeignKey("federal_districts.id"))
|
||||
status: Mapped[str] = mapped_column(String(20), default="active")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
|
||||
)
|
||||
|
||||
district: Mapped[FederalDistrict] = relationship(back_populates="regions")
|
||||
@@ -0,0 +1,17 @@
|
||||
# Backend — АС «Платформа ОПОРА РОССИИ»
|
||||
fastapi==0.115.0
|
||||
uvicorn[standard]==0.30.6
|
||||
gunicorn==22.0.0
|
||||
sqlalchemy==2.0.35
|
||||
alembic==1.13.2
|
||||
psycopg[binary]==3.2.3
|
||||
pydantic==2.9.2
|
||||
pydantic-settings==2.5.2
|
||||
python-jose[cryptography]==3.3.0
|
||||
passlib[bcrypt]==1.7.4
|
||||
celery==5.4.0
|
||||
redis==5.0.8
|
||||
aiogram==3.13.1
|
||||
httpx==0.27.2
|
||||
python-multipart==0.0.12
|
||||
boto3==1.35.36
|
||||
Reference in new issue
Block a user