存储库模式在 Python 中的实现?

新手上路,请多包涵

主要是出于好奇,我正在寻找一个 Python 框架或示例,用于从域逻辑中解耦持久性逻辑的存储库模式。

“Repository Pattern”这个名字出现在帖子“ Untangle Domain and Persistence Logic with Curator ”(Ruby)中,idea来自《领域驱动设计》一书的 一段Martin Fowler 。模型类不包含持久性逻辑,而是应用程序声明存储库子类,其实例的行为类似于模型实例的内存集合。每个存储库以不同的方式保存模型,例如 SQL(各种模式约定)、Riak 或其他 noSQL 以及内存(用于缓存)。框架约定意味着存储库子类通常需要最少的代码:只需声明 SQLRepository 的“WidgetRepository”子类即可提供一个集合,该集合将模型 Widget 持久保存到名为“widgets”的数据库表并将列与 Widget 属性匹配。

与其他模式的区别:

活动记录模式:例如,Django ORM。该应用程序仅定义具有域逻辑的模型类和一些用于持久性的元数据。 ORM 将持久化逻辑添加到模型类中。这将域和持久性混合在一个类中(根据帖子,这是不受欢迎的)。

感谢@marcin,我看到当 Active Record 支持不同的后端和 .save(using=“other_database”) 函数时,这提供了存储库模式的多后端优势。

所以在某种意义上,存储库模式就像 Active Record 一样,将持久化逻辑移到了一个单独的类中。

数据映射器模式:例如,SQLAlchemy 的经典映射。该应用程序为数据库表和从模型到表的数据映射器定义了额外的类。因此模型实例可以以多种方式映射到表,例如支持遗留模式。不要认为 SQLAlchemy 提供非 SQL 存储的映射器。

原文由 Graham 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 407
2 个回答

您可能想仔细看看 James Dennis 的 DictShield 项目

“DictShield 是一个与数据库无关的建模系统。它提供了一种轻松建模、验证和重塑数据的方法。所有这些都不需要任何特定的数据库。”

原文由 Jordan Dimov 发布,翻译遵循 CC BY-SA 3.0 许可协议

意料之外:

I define two example domains, User and Animal , an base storage class Store and two specialized Storage classes UserStore and AnimalStore 。使用上下文管理器关闭数据库连接(为简单起见,我在此示例中使用 sqlite):

 import sqlite3

def get_connection():
    return sqlite3.connect('test.sqlite')

class StoreException(Exception):
    def __init__(self, message, *errors):
        Exception.__init__(self, message)
        self.errors = errors

# domains

class User():
    def __init__(self, name):
        self.name = name

class Animal():
    def __init__(self, name):
        self.name = name

# base store class
class Store():
    def __init__(self):
        try:
            self.conn = get_connection()
        except Exception as e:
            raise StoreException(*e.args, **e.kwargs)
        self._complete = False

    def __enter__(self):
        return self

    def __exit__(self, type_, value, traceback):
        # can test for type and handle different situations
        self.close()

    def complete(self):
        self._complete = True

    def close(self):
        if self.conn:
            try:
                if self._complete:
                    self.conn.commit()
                else:
                    self.conn.rollback()
            except Exception as e:
                raise StoreException(*e.args)
            finally:
                try:
                    self.conn.close()
                except Exception as e:
                    raise StoreException(*e.args)

# store for User obects
class UserStore(Store):

    def add_user(self, user):
        try:
            c = self.conn.cursor()
            # this needs an appropriate table
            c.execute('INSERT INTO user (name) VALUES(?)', (user.name,))
        except Exception as e:
            raise StoreException('error storing user')

# store for Animal obects
class AnimalStore(Store):

    def add_animal(self, animal):
        try:
            c = self.conn.cursor()
            # this needs an appropriate table
            c.execute('INSERT INTO animal (name) VALUES(?)', (animal.name,))
        except Exception as e:
            raise StoreException('error storing animal')

# do something
try:
    with UserStore() as user_store:
        user_store.add_user(User('John'))
        user_store.complete()

    with AnimalStore() as animal_store:
        animal_store.add_animal(Animal('Dog'))
        animal_store.add_animal(Animal('Pig'))
        animal_store.add_animal(Animal('Cat'))
        animal_store.add_animal(Animal('Wolf'))
        animal_store.complete()
except StoreException as e:
    # exception handling here
    print(e)

原文由 laurasia 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏