More comments in code
This commit is contained in:
parent
3698d46649
commit
1d9fa011a3
6 changed files with 32 additions and 2 deletions
|
@ -2,12 +2,11 @@ import os
|
||||||
import secrets
|
import secrets
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
|
||||||
|
|
||||||
from fastapi.templating import Jinja2Templates
|
from fastapi.templating import Jinja2Templates
|
||||||
from pydantic import BaseSettings
|
from pydantic import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
# Directories
|
||||||
file_dir = Path(__file__).parent
|
file_dir = Path(__file__).parent
|
||||||
templates_dir = str(
|
templates_dir = str(
|
||||||
file_dir.parent / 'templates'
|
file_dir.parent / 'templates'
|
||||||
|
@ -17,6 +16,7 @@ static_dir = str(
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Main configuration
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
debug: bool = False
|
debug: bool = False
|
||||||
session_key: str = secrets.token_hex(32)
|
session_key: str = secrets.token_hex(32)
|
||||||
|
@ -25,6 +25,7 @@ class Settings(BaseSettings):
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
|
|
||||||
|
|
||||||
|
# Jinja templates handler
|
||||||
templates = Jinja2Templates(
|
templates = Jinja2Templates(
|
||||||
directory=templates_dir,
|
directory=templates_dir,
|
||||||
)
|
)
|
||||||
|
|
|
@ -22,16 +22,24 @@ paths: List[Type[Paths]] = [
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# Initialize SQL database
|
||||||
db.Base.metadata.create_all(bind=db.engine)
|
db.Base.metadata.create_all(bind=db.engine)
|
||||||
|
|
||||||
|
# Create app
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
# Mount static files server
|
||||||
app.mount(
|
app.mount(
|
||||||
'/static',
|
'/static',
|
||||||
StaticFiles(directory=common.static_dir),
|
StaticFiles(directory=common.static_dir),
|
||||||
name='static',
|
name='static',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Add paths
|
||||||
for p in paths:
|
for p in paths:
|
||||||
p(app).add_paths()
|
p(app).add_paths()
|
||||||
|
|
||||||
|
# Add WTForms CSRF protection middlewares
|
||||||
app.add_middleware(
|
app.add_middleware(
|
||||||
SessionMiddleware,
|
SessionMiddleware,
|
||||||
secret_key=common.settings.session_key,
|
secret_key=common.settings.session_key,
|
||||||
|
|
|
@ -20,6 +20,7 @@ class ErrorsPaths(Paths):
|
||||||
|
|
||||||
def add_paths(self) -> None:
|
def add_paths(self) -> None:
|
||||||
|
|
||||||
|
# For each HTTP code specified above
|
||||||
for code in codes:
|
for code in codes:
|
||||||
self.add_handler(code)
|
self.add_handler(code)
|
||||||
|
|
||||||
|
@ -31,14 +32,19 @@ class ErrorsPaths(Paths):
|
||||||
code (int): HTTP error code
|
code (int): HTTP error code
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# Jinja template file name
|
||||||
|
# e.g. 404.html for 404 code
|
||||||
file = Path(common.templates_dir) / f'{code}.html'
|
file = Path(common.templates_dir) / f'{code}.html'
|
||||||
|
|
||||||
|
# Exit from the function
|
||||||
|
# if the template does not exist
|
||||||
if not file.exists():
|
if not file.exists():
|
||||||
return
|
return
|
||||||
|
|
||||||
@self.app.exception_handler(code)
|
@self.app.exception_handler(code)
|
||||||
async def handler(req: Request, exc: HTTPException) -> Response:
|
async def handler(req: Request, exc: HTTPException) -> Response:
|
||||||
|
|
||||||
|
# Respond with the template
|
||||||
return respond.with_tmpl(
|
return respond.with_tmpl(
|
||||||
f'{code}.html',
|
f'{code}.html',
|
||||||
code=code,
|
code=code,
|
||||||
|
|
|
@ -6,6 +6,7 @@ from . import models
|
||||||
from . import schemas
|
from . import schemas
|
||||||
|
|
||||||
|
|
||||||
|
# SELECT * from users LIMIT 1
|
||||||
def get_user(
|
def get_user(
|
||||||
db: Session,
|
db: Session,
|
||||||
user_id: int) -> Optional[models.User]:
|
user_id: int) -> Optional[models.User]:
|
||||||
|
@ -16,6 +17,7 @@ def get_user(
|
||||||
.first()
|
.first()
|
||||||
|
|
||||||
|
|
||||||
|
# SELECT * from users
|
||||||
def get_users(
|
def get_users(
|
||||||
db: Session,
|
db: Session,
|
||||||
skip: int = 0,
|
skip: int = 0,
|
||||||
|
@ -28,6 +30,7 @@ def get_users(
|
||||||
.all()
|
.all()
|
||||||
|
|
||||||
|
|
||||||
|
# INSERT INTO users
|
||||||
def create_user(
|
def create_user(
|
||||||
db: Session,
|
db: Session,
|
||||||
user: schemas.UserCreate) -> models.User:
|
user: schemas.UserCreate) -> models.User:
|
||||||
|
|
|
@ -9,6 +9,7 @@ from sqlalchemy.orm import Session, sessionmaker
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
|
||||||
|
|
||||||
|
# Database configuration
|
||||||
class SqlSettings(BaseSettings):
|
class SqlSettings(BaseSettings):
|
||||||
db_host: str = '${REPO_NAME_SNAKE}_db'
|
db_host: str = '${REPO_NAME_SNAKE}_db'
|
||||||
db_port: int = 3306
|
db_port: int = 3306
|
||||||
|
@ -18,24 +19,31 @@ class SqlSettings(BaseSettings):
|
||||||
|
|
||||||
sql_settings = SqlSettings()
|
sql_settings = SqlSettings()
|
||||||
|
|
||||||
|
# DB connection URL
|
||||||
db_url = (
|
db_url = (
|
||||||
'mysql://{db_user}:{db_password}@'
|
'mysql://{db_user}:{db_password}@'
|
||||||
'{db_host}:{db_port}/{db_database}'
|
'{db_host}:{db_port}/{db_database}'
|
||||||
).format(**sql_settings.dict())
|
).format(**sql_settings.dict())
|
||||||
|
|
||||||
|
|
||||||
|
# SQLAlchemy engine object
|
||||||
engine = create_engine(db_url)
|
engine = create_engine(db_url)
|
||||||
|
|
||||||
|
# Create DB if not exists
|
||||||
if not database_exists(db_url):
|
if not database_exists(db_url):
|
||||||
create_database(db_url)
|
create_database(db_url)
|
||||||
|
|
||||||
|
# SQLAlchemy Session object
|
||||||
SessionLocal = sessionmaker(
|
SessionLocal = sessionmaker(
|
||||||
autoflush=False,
|
autoflush=False,
|
||||||
bind=engine,
|
bind=engine,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# SQLAlchemy Base object
|
||||||
Base = declarative_base()
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
# FastAPI dependency
|
||||||
async def get_db() -> AsyncGenerator[Session, None]:
|
async def get_db() -> AsyncGenerator[Session, None]:
|
||||||
"""FastAPI dependency
|
"""FastAPI dependency
|
||||||
returning database Session object.
|
returning database Session object.
|
||||||
|
|
|
@ -1,12 +1,16 @@
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
# Pydantic class for
|
||||||
|
# INSERT queries on a User model
|
||||||
class UserCreate(BaseModel):
|
class UserCreate(BaseModel):
|
||||||
email: str
|
email: str
|
||||||
name: str
|
name: str
|
||||||
age: int
|
age: int
|
||||||
|
|
||||||
|
|
||||||
|
# Pydantic class for
|
||||||
|
# SELECT responses with User model(-s)
|
||||||
class User(UserCreate):
|
class User(UserCreate):
|
||||||
id: int
|
id: int
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue