Moved files related to paths to a separated directory
This commit is contained in:
parent
4c7f07dd05
commit
10a6b6553d
5 changed files with 7 additions and 6 deletions
46
app/paths/errors.py
Normal file
46
app/paths/errors.py
Normal file
|
@ -0,0 +1,46 @@
|
|||
"""Custom error pages for FastAPI app"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import Request, Response
|
||||
from fastapi import HTTPException
|
||||
|
||||
from . import paths
|
||||
from .. import respond
|
||||
from .. import common
|
||||
|
||||
# Add other HTTP error codes
|
||||
codes = [404, 500]
|
||||
|
||||
|
||||
class ErrorsPaths(paths.Paths):
|
||||
"""Sets up custom error pages,
|
||||
inherited from paths.Paths"""
|
||||
|
||||
def add_paths(self) -> None:
|
||||
|
||||
for code in codes:
|
||||
self.add_handler(code)
|
||||
|
||||
def add_handler(self, code: int) -> None:
|
||||
"""Adds an error handler to FastAPI app.
|
||||
Only for internal use!
|
||||
|
||||
Args:
|
||||
code (int): HTTP error code
|
||||
"""
|
||||
|
||||
file = Path(common.templates_dir) / f'{code}.html'
|
||||
|
||||
if not file.exists():
|
||||
return
|
||||
|
||||
@self.app.exception_handler(code)
|
||||
async def handler(req: Request, exc: HTTPException) -> Response:
|
||||
|
||||
return respond.with_tmpl(
|
||||
f'{code}.html',
|
||||
code=code,
|
||||
request=req,
|
||||
exc=exc,
|
||||
)
|
20
app/paths/pages.py
Normal file
20
app/paths/pages.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
"""Main FastAPI paths"""
|
||||
|
||||
from fastapi import Request, Response
|
||||
|
||||
from . import paths
|
||||
from .. import respond
|
||||
|
||||
|
||||
class MainPaths(paths.Paths):
|
||||
"""Main FastAPI app paths,
|
||||
inherits paths.Paths"""
|
||||
|
||||
def add_paths(self) -> None:
|
||||
|
||||
@self.app.get('/')
|
||||
def index(req: Request) -> Response:
|
||||
return respond.with_tmpl(
|
||||
'index.html',
|
||||
request=req,
|
||||
)
|
21
app/paths/paths.py
Normal file
21
app/paths/paths.py
Normal file
|
@ -0,0 +1,21 @@
|
|||
import abc
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
|
||||
class Paths(abc.ABC):
|
||||
"""Abstract class for storing paths for FastAPI app"""
|
||||
|
||||
def __init__(self, app: FastAPI) -> None:
|
||||
"""Abstract class for storing paths
|
||||
for FastAPI app
|
||||
|
||||
Args:
|
||||
app (FastAPI): Application object
|
||||
"""
|
||||
|
||||
self.app = app
|
||||
|
||||
@abc.abstractmethod
|
||||
def add_paths(self) -> None:
|
||||
"""Add paths to the FastAPI application"""
|
Loading…
Add table
Reference in a new issue