From 1d9fa011a389b95e0ad418da6b1bcabd42ad6056 Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Mon, 27 Feb 2023 19:05:04 +0400 Subject: [PATCH] More comments in code --- app/common.py | 5 +++-- app/main.py | 8 ++++++++ app/paths/errors.py | 6 ++++++ app/sql/crud.py | 3 +++ app/sql/db.py | 8 ++++++++ app/sql/schemas.py | 4 ++++ 6 files changed, 32 insertions(+), 2 deletions(-) diff --git a/app/common.py b/app/common.py index 11b46b1..2adf0f8 100644 --- a/app/common.py +++ b/app/common.py @@ -2,12 +2,11 @@ import os import secrets from pathlib import Path -from dotenv import load_dotenv - from fastapi.templating import Jinja2Templates from pydantic import BaseSettings +# Directories file_dir = Path(__file__).parent templates_dir = str( file_dir.parent / 'templates' @@ -17,6 +16,7 @@ static_dir = str( ) +# Main configuration class Settings(BaseSettings): debug: bool = False session_key: str = secrets.token_hex(32) @@ -25,6 +25,7 @@ class Settings(BaseSettings): settings = Settings() +# Jinja templates handler templates = Jinja2Templates( directory=templates_dir, ) diff --git a/app/main.py b/app/main.py index 65764ba..f409f7d 100644 --- a/app/main.py +++ b/app/main.py @@ -22,16 +22,24 @@ paths: List[Type[Paths]] = [ ] +# Initialize SQL database db.Base.metadata.create_all(bind=db.engine) + +# Create app app = FastAPI() + +# Mount static files server app.mount( '/static', StaticFiles(directory=common.static_dir), name='static', ) + +# Add paths for p in paths: p(app).add_paths() +# Add WTForms CSRF protection middlewares app.add_middleware( SessionMiddleware, secret_key=common.settings.session_key, diff --git a/app/paths/errors.py b/app/paths/errors.py index 9c1a354..8acad5a 100644 --- a/app/paths/errors.py +++ b/app/paths/errors.py @@ -20,6 +20,7 @@ class ErrorsPaths(Paths): def add_paths(self) -> None: + # For each HTTP code specified above for code in codes: self.add_handler(code) @@ -31,14 +32,19 @@ class ErrorsPaths(Paths): code (int): HTTP error code """ + # Jinja template file name + # e.g. 404.html for 404 code file = Path(common.templates_dir) / f'{code}.html' + # Exit from the function + # if the template does not exist if not file.exists(): return @self.app.exception_handler(code) async def handler(req: Request, exc: HTTPException) -> Response: + # Respond with the template return respond.with_tmpl( f'{code}.html', code=code, diff --git a/app/sql/crud.py b/app/sql/crud.py index 96e7420..e0ea5e3 100644 --- a/app/sql/crud.py +++ b/app/sql/crud.py @@ -6,6 +6,7 @@ from . import models from . import schemas +# SELECT * from users LIMIT 1 def get_user( db: Session, user_id: int) -> Optional[models.User]: @@ -16,6 +17,7 @@ def get_user( .first() +# SELECT * from users def get_users( db: Session, skip: int = 0, @@ -28,6 +30,7 @@ def get_users( .all() +# INSERT INTO users def create_user( db: Session, user: schemas.UserCreate) -> models.User: diff --git a/app/sql/db.py b/app/sql/db.py index 32a32b3..5e78972 100644 --- a/app/sql/db.py +++ b/app/sql/db.py @@ -9,6 +9,7 @@ from sqlalchemy.orm import Session, sessionmaker from sqlalchemy.ext.declarative import declarative_base +# Database configuration class SqlSettings(BaseSettings): db_host: str = '${REPO_NAME_SNAKE}_db' db_port: int = 3306 @@ -18,24 +19,31 @@ class SqlSettings(BaseSettings): sql_settings = SqlSettings() +# DB connection URL db_url = ( 'mysql://{db_user}:{db_password}@' '{db_host}:{db_port}/{db_database}' ).format(**sql_settings.dict()) +# SQLAlchemy engine object engine = create_engine(db_url) + +# Create DB if not exists if not database_exists(db_url): create_database(db_url) +# SQLAlchemy Session object SessionLocal = sessionmaker( autoflush=False, bind=engine, ) +# SQLAlchemy Base object Base = declarative_base() +# FastAPI dependency async def get_db() -> AsyncGenerator[Session, None]: """FastAPI dependency returning database Session object. diff --git a/app/sql/schemas.py b/app/sql/schemas.py index 1d48d51..c15dcb2 100644 --- a/app/sql/schemas.py +++ b/app/sql/schemas.py @@ -1,12 +1,16 @@ from pydantic import BaseModel +# Pydantic class for +# INSERT queries on a User model class UserCreate(BaseModel): email: str name: str age: int +# Pydantic class for +# SELECT responses with User model(-s) class User(UserCreate): id: int