Skip to content

Commit

Permalink
Fixed issue with afterInit being called twice & errors in afterInit n…
Browse files Browse the repository at this point in the history
…ot being caught when constructing a new model instance; refs bmuller#30; fixes bmuller#34
  • Loading branch information
Erik Allik committed Nov 30, 2012
1 parent af89267 commit 344ff88
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
12 changes: 11 additions & 1 deletion twistar/dbobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ class DBObject(Validator):
# it will be of the form {'othername': <BelongsTo instance>, 'anothername': <HasMany instance>}
RELATIONSHIP_CACHE = None

def __new__(cls, *args, **kwargs):
try:
ret = super(DBObject, cls).__new__(cls, *args, **kwargs)
ret.__init__(*args, **kwargs)
except:
return defer.fail()
else:
return defer.maybeDeferred(ret.afterInit).addCallback(lambda _: ret)


def __init__(self, **kwargs):
"""
Constructor. DO NOT OVERWRITE. Use the L{DBObject.afterInit} method.
Expand Down Expand Up @@ -377,7 +387,7 @@ def findOrCreate(klass, **attrs):
def _findOrCreate(trans):
def handle(result):
if len(result) == 0:
return klass(**attrs).save()
return klass(**attrs).addCallback(lambda inst: inst.save())
return result[0]
return klass.findBy(**attrs).addCallback(handle)
return _findOrCreate()
Expand Down
16 changes: 7 additions & 9 deletions twistar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,13 @@ def createInstances(props, klass):
@return: A C{Deferred} that will pass the result to a callback
"""
if type(props) is list:
ks = [klass(**prop) for prop in props]
ds = [defer.maybeDeferred(k.afterInit) for k in ks]
return defer.DeferredList(ds).addCallback(lambda _: ks)

if props is not None:
k = klass(**props)
return defer.maybeDeferred(k.afterInit).addCallback(lambda _: k)

return defer.succeed(None)
return defer.DeferredList(
[klass(**prop) for prop in props], fireOnOneErrback=True, consumeErrors=True
).addCallback(lambda result: [x[1] for x in result])
elif props is not None:
return klass(**props)
else:
return defer.succeed(None)


def dictToWhere(attrs, joiner="AND"):
Expand Down

0 comments on commit 344ff88

Please sign in to comment.