tmpl-fastapi/app/common.py

53 lines
1.1 KiB
Python

import secrets
from pathlib import Path
from fastapi.templating import Jinja2Templates
from pydantic import BaseSettings
# Directories
file_dir = Path(__file__).parent
templates_dir = str(file_dir.parent / 'templates')
static_dir = str(file_dir.parent / 'static')
# Main configuration
class Settings(BaseSettings):
debug: bool = False
secret_key: str = 'secret'
app_host: str = '127.0.0.1'
app_port: int = 8000
# Instantiate Settings class
settings = Settings()
# Jinja templates handler
templates = Jinja2Templates(
directory=templates_dir,
)
def secret_key_check() -> None:
"""Generates a secret key automatically
if the env var `secret_key` is not set
or contains text `secret`"""
if settings.secret_key == 'secret':
key_file = Path('/tmp/secret_key')
if key_file.exists():
with key_file.open('rt') as f:
secret_key = f.read()
else:
secret_key = secrets.token_hex(32)
with key_file.open('wt') as f:
f.write(secret_key)
settings.secret_key = secret_key
# Call the function
secret_key_check()