config.py 1.23 KB
Newer Older
崔为之's avatar
崔为之 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/11/3 19:43
# @File        : config.py
# @Description :
"""


from typing import Any

from flask import Flask
崔为之's avatar
崔为之 committed
17
from loguru import logger
崔为之's avatar
崔为之 committed
18

崔为之's avatar
崔为之 committed
19 20
from application.libs import ConfigKeyError

崔为之's avatar
崔为之 committed
21 22 23 24 25 26 27 28 29 30 31 32

class ConfigHelper:
    """
    The ConfigHelper class is a utility for fetching configuration values
    from a Flask application.

    :param app: The Flask application instance from which to fetch configuration values.
    """

    def __init__(self, app: Flask):
        self.app = app

崔为之's avatar
崔为之 committed
33
    def __getattr__(self, name: str) -> Any:
崔为之's avatar
崔为之 committed
34
        """
崔为之's avatar
崔为之 committed
35
        Get a config value as an attribute.
崔为之's avatar
崔为之 committed
36

崔为之's avatar
崔为之 committed
37 38
        :param name: The name of the config key.
        :return: The value for the provided key, or None if it does not exist.
崔为之's avatar
崔为之 committed
39
        """
崔为之's avatar
崔为之 committed
40 41 42
        try:
            return self.app.config[name]
        except KeyError:
崔为之's avatar
崔为之 committed
43 44
            logger.error(f'Key {name} not found in configuration')
            raise ConfigKeyError(name)
崔为之's avatar
崔为之 committed
45 46 47 48 49 50

    def __repr__(self):
        return f"<ConfigHelper with app {self.app}>"

    def __str__(self):
        return f"ConfigHelper for app {self.app}"