在允许注入依赖项的类中删除DRY的Pythonic方法

2024-10-01 22:31:39 发布

您现在位置:Python中文网/ 问答频道 /正文

在这样的代码中,如何删除干的或使其更具Pythonic?我知道我可以把插入作为一个函数,但我不喜欢这样,很多类会有太多的函数,因为像这样的代码有不同的实现无处不在。你知道吗

注入的db\u conn由Nameko(microservice framework)的dependencProvider管理,当一个worker已经完成作业时,dependencProvider关闭连接。你知道吗

我还使db\u conn对象与with语句兼容。我在__exit__方法中关闭连接。你知道吗

这是当前代码。你知道吗

class CommandChatBot(BaseChatBot):

    def __init__(self, db_conn=None):
         self.db_conn = None
         if db_conn:
             self.db_conn = db_conn

    def add_interaction(self, question, answer, recipient):

        if self.db_conn:
            self.db_conn.use_or_create_db(db=recipient)
            return self.db_conn.insert(
                table=schemas.commandchatbot.TABLE,
                document={
                    'question': question,
                    'answer': answer
                }
            )
        else:
            with db_connection_factory() as conn:
                conn.use_or_create_db(db=recipient)
                return conn.insert(
                    table=schemas.commandchatbot.TABLE,
                    document={
                       'question': question,
                       'answer': answer
                    }
                )

当不注入依赖项时,上面的代码也是低效的,因为每个函数必须实例化它们自己的db\u conn对象。我在考虑类似于with语句的东西,但是对于整个类来说,这是可能的吗?你知道吗

当依赖项是dependencProvider的子类时,连接将关闭;当微服务分派新的worker时,将调用get\u dependency();当worker删除时,将调用worker\u teardown();微服务中的所有代码都已执行。你知道吗

class DbConnectionProvider(DependencyProvider):

        def __init__(self):
            self.db_conn = db_connection_factory()

        def get_dependency(self, worker_ctx):
            return self.db_conn

        def worker_teardown(self, worker_ctx):
            self.db_conn.close_conn()

db\u conn\u factory()生成的对象之一

class RethinkDbAdapter(DatabaseAdapter):

    def __init__(self, db=None, create_db_if_not_exist=True):
        uri = build_nosqldatabase_uri(return_dict=True)

        self.raw_connection = r.connect(
            host=uri['host'],
            port=uri['port']
        )

        ...........

    # __enter__ and __exit__ allows the use of 'with' statement
    def __enter__(self):
        return self

    # Close connection when 'with' statement is out of scope
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.raw_connection.close()

    def close_conn(self):
        """
        Only used in Nameko DependencyProvider.
        """
        return self.raw_connection.close()

    .........

Tags: 函数代码answerselfclosedbreturndef
1条回答
网友
1楼 · 发布于 2024-10-01 22:31:39

看起来您将以下代码封装在另一个方法中,您可以从if或else块调用该方法:

insert(
            table=schemas.commandchatbot.TABLE,
            document={
                'question': question,
                'answer': answer
            }
        )

相关问题 更多 >

    热门问题