tmpl-fastapi/app/common.py

54 lines
1.1 KiB
Python
Raw Normal View History

import secrets
from pathlib import Path
from fastapi.templating import Jinja2Templates
from pydantic import BaseSettings
2023-02-27 18:05:04 +03:00
# Directories
2023-02-19 15:19:18 +03:00
file_dir = Path(__file__).parent
templates_dir = str(file_dir.parent / 'templates')
static_dir = str(file_dir.parent / 'static')
2023-02-20 11:09:43 +03:00
2023-02-27 18:05:04 +03:00
# Main configuration
2023-02-20 11:09:43 +03:00
class Settings(BaseSettings):
debug: bool = False
secret_key: str = 'secret'
app_host: str = '127.0.0.1'
app_port: int = 8000
2023-02-20 11:09:43 +03:00
2023-02-27 18:05:57 +03:00
# Instantiate Settings class
2023-02-20 11:09:43 +03:00
settings = Settings()
2023-02-19 15:19:18 +03:00
2023-02-27 18:05:04 +03:00
# Jinja templates handler
templates = Jinja2Templates(
2023-02-19 15:19:18 +03:00
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()