Skip to content

Commit

Permalink
feat: delete comments and add an env check
Browse files Browse the repository at this point in the history
  • Loading branch information
haxgun authored Nov 28, 2024
1 parent 23860a2 commit c4a4dd6
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 25 deletions.
6 changes: 6 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DEBUG=True

PROJECT_NAME="My app"
VERSION="1.0.0"

DATABASE_URL="postgresql+asyncpg://postgres:postgres@localhost:5432/valory"
5 changes: 2 additions & 3 deletions backend/app/crud/overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
from sqlalchemy.future import select

from app.models.overlay import Overlay
# Импорты для моделей, схем и сессий
from app.schemas.overlay import OverlaySchema, OverlayCreate # Pydantic-схема OverlayCreate
from app.db.session import get_db # Асинхронная сессия базы данных
from app.schemas.overlay import OverlaySchema, OverlayCreate
from app.db.session import get_db

router = APIRouter()

Expand Down
4 changes: 2 additions & 2 deletions backend/app/db/session.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlmodel import SQLModel
from app import settings

DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost:5432/valory"
engine = create_async_engine(DATABASE_URL, echo=True, future=True)
engine = create_async_engine(settings.DATABASE_URL, echo=True, future=True)

AsyncSessionLocal = sessionmaker(
bind=engine,
Expand Down
9 changes: 4 additions & 5 deletions backend/app/schemas/overlay.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ class OverlaySchema(BaseModel):
tag: str

class Config:
orm_mode = True # Включает поддержку ORM для SQLAlchemy моделей
orm_mode = True

# Схема для создания записи
class OverlayCreate(OverlayBase):
pass # Наследует все поля от OverlayBase, используется для валидации входных данных
pass

# Схема для ответа
class OverlayRead(OverlayBase):
uuid: uuid_pkg.UUID # Добавляем поле UUID в схему для ответа
uuid: uuid_pkg.UUID

class Config:
orm_mode = True # Поддержка работы с SQLAlchemy/SQLModel объектами
orm_mode = True
9 changes: 6 additions & 3 deletions backend/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ def str_to_bool(value: str) -> bool:

BASE_DIR = Path(__file__).resolve().parent.parent.parent

print(BASE_DIR)

dotenv_file = BASE_DIR / '.env'
if dotenv_file.is_file():
load_dotenv(dotenv_file)
else:
raise ImportError('⚠ .env was not found')


DEBUG = str_to_bool(environ.get("DEBUG", "False"))

PROJECT_NAME = environ.get('PROJECT_NAME')
VERSION = environ.get('VERSION')
VERSION = environ.get('VERSION')

DATABASE_URL = environ.get('DATABASE_URL')
16 changes: 4 additions & 12 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,32 @@
from app import settings


# Определение lifespan для управления событиями старта и завершения
@asynccontextmanager
async def lifespan(app: FastAPI):
# Выполняется при старте приложения
await init_db()
print("Application startup complete.")
print("Application startup complete.")

yield # Передача управления основному приложению
yield

# Выполняется при завершении приложения
print("Application shutdown complete.")
print("⚠ Application shutdown complete.")


# Создание экземпляра FastAPI с lifespan
app = FastAPI(
title=settings.PROJECT_NAME,
version=settings.VERSION,
lifespan=lifespan
)

# Подключение CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Замените "*" на список доменов в production
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)

# Подключение роутов
app.include_router(api_router, prefix="/api/v1")


# Тестовый маршрут
@app.get("/")
async def read_root():
return {"message": "Welcome to the API!"}

0 comments on commit c4a4dd6

Please sign in to comment.