主要出于好奇,我正在寻找一个 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 存储提供映射器。
最佳答案
想不通:
我定义了两个示例域,User 和 Animal,一个基本存储类 Store 和两个专门的存储类 UserStore 和 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)
关于python - 在 Python 中实现存储库模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9699598/
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我需要在RubyonRails中实现无向图G=(V,E)并考虑构建一个Vertex和一个Edge模型,其中Vertex有_多条边。由于边恰好连接两个顶点,您将如何在Rails中执行此操作?您是否知道任何有助于实现此类图表的gem或库(对重新发明轮子不感兴趣;-))? 最佳答案 不知道有任何现有库在ActiveRecord之上提供图形逻辑。您可能必须实现自己的Vertex、EdgeActiveRecord支持的模型(请参阅Rails安装的rails/activerecord中的vertex.rb和edge.rb/test/fixtur
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭10年前。问题1)我想知道rubyonrails是否有功能类似于primefaces的gem。我问的原因是如果您使用primefaces(http://www.primefaces.org/showcase-labs/ui/home.jsf),开发人员无需担心javascript或jquery的东西。据我所知,JSF是一个规范,基于规范的各种可用实现,prim
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht