python - 在 Python 中实现存储库模式?

标签 python repository-pattern

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

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

与其他模式的区别:

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

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

所以在某种意义上,Repository Pattern 就像 Active Record 一样,将持久性逻辑移到了一个单独的类中。

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

最佳答案

想不通:

我定义了两个示例域,UserAnimal,一个基本存储类 Store 和两个专门的存储类 UserStoreAnimalStore。使用上下文管理器关闭数据库连接(为简单起见,我在此示例中使用 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)

关于python - 在 Python 中实现存储库模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699598/

相关文章:

python - 找到两个选定单元格之间的最短路径(如果不能沿对角线走)

python - 获取一列对象的最后一个字符并将其作为数据框上的列 - pandas python

python - 在 python 类型提示中,如何使参数接受基类的任何子类?

python - Enthought Canopy Python 和 OpenCV

c# - 我如何使 .Include 在 IEnumerable 上工作

python pip : cloudmonkey not installing correctly

c# - 具有通用基类的ASP.NET Core 2.0存储库模式

c# - 类型转换动态对象并传递到 UnitOfWork 和存储库模式。抛出异常

wpf - 在多个 View 模型之间共享模型对象的最佳实践是什么?

Spring with Neo4j, GraphRepository<?> vs 手工界面