More comments in code

This commit is contained in:
DarkCat09 2023-02-27 19:05:04 +04:00
parent 3698d46649
commit 1d9fa011a3
6 changed files with 32 additions and 2 deletions

View file

@ -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,
)

View file

@ -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,

View file

@ -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,

View file

@ -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:

View file

@ -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.

View file

@ -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