@Mikkkch

Как правильно внедрить DEBUG в веб-проект?

Пишу CRUD для взаимодействия с записями в бд. Запись в базу данных организована таким образом, чтобы мы распаковывали __dict__ класса внутрь функции insert, предоставляемой классом Table SQLAlchemy. К примеру, у нас есть класс ConsumerCreation и он содержит поля username и password, что соответствует полям в таблице. В таком случае мы просто воспользуемся следующей конструкцией: <tablename>.insert(**instance.dict()).
Но что делать, если какой-то программист, использующий наш код, умудрился внести новое поле в класс ConsumerCreation, а в таблицу SQLAlchemy и в таблицу базы данных забыл это сделать?
Мой код:

from typing import Callable, Optional
from abc import ABC, abstractmethod

from databases import Database
from sqlalchemy import Table

from core.settings import DEBUG


class BaseCRUD(ABC):
    """
    Abstract manager for managing records of a specific table.

    All CRUDs inherited from this implement the interface described here.
    This interface is limited to creating, reading, updating and deleting.

    :param storage: a repository through which all requests will be carried out.
    :param storing_table: a table in which records will be retrieved from for further interaction with them.
    """

    storage:       Database
    storing_table: Table

    def __init__(self, storage: Database, storing_table: Table) -> None:
        self.storage, self.storing_table = storage, storing_table

    async def fields_and_columns_correspondence(self, data: dict) -> None:
        """
        A method that performs a self-test before writing anything to the database.

        In the case when we want to add a record to the database,
        conflicts may arise due to the fact that unnecessary values
        may be found in the passed parameters, or on the contrary, all
        necessary parameters may not be passed.

        :param data: parameters to be unpacked into a table.
        :raises ValueError: if the program fails validation.
        """

        if DEBUG:
            columns = [column.name for column in self.storing_table.columns]

            passed_parameters = data.keys()

            for parameter in passed_parameters:
                assert parameter in columns, \
                    f'The table called {self.storing_table.name} does not contain the column called {parameter}.'

            for column in columns:
                assert column in passed_parameters, \
                    f'The list of arguments passed to the {self.storing_table.name} ' \
                    f'table contains no argument for the {column} column.'

    @abstractmethod
    async def create(self):
        """
        Method responsible for creating the object.
        """

    @abstractmethod
    async def get(self):
        """
        Method responsible for getting the object.
        """

    @abstractmethod
    async def update(self):
        """
        Method responsible for updating the object.
        """

    @abstractmethod
    async def delete(self):
        """
        Method responsible for deleting the object.
        """


Проблема:
В моем коде вы можете видеть такой метод, внутри которого осуществляется проверка if DEBUG. То есть, если в настройках DEBUG содержит флаг False, то эта функция просто вернет None и не начнет ничего объявлять. Но что делать, когда DEBUG стоит True, а переменная __debug__ отключена? От этого метода толку не будет и мы просто так пропишем функционал, который будет тратить время во время выполнения инсерта.
  • Вопрос задан
  • 62 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы