Skip to content

Commit

Permalink
change db api to for insert vs update and avoid updates when no change
Browse files Browse the repository at this point in the history
  • Loading branch information
harryf committed Jun 13, 2008
1 parent 4e9e683 commit ccbd48f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 25 deletions.
7 changes: 4 additions & 3 deletions dammit/db/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
class MockDB(object):
def __init__(self):
self.uris = {}
self.stored = []

def load(self, id):
return self.uris.get(id, None)

def store(self, uri):
self.stored.append(uri)
def insert(self, uri):
self.uris[uri.id] = uri

def update(self, uri):
self.uris[uri.id] = uri

def delete(self, id):
Expand Down
52 changes: 30 additions & 22 deletions dammit/uri.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,47 +485,55 @@ def register(self, uri, status = 200, **kwargs):
id = URI.hash(uri)

u = self.db.load(id)
newrecord = True

if u:
if u.is_redirected():
# 301 is immutable - can return straight away
return u

newrecord = False
else:
if 200 <= status < 300:
u = URI()
else:
return None

def apply_attribute(uri, key, value):
updated = False
try:
if not getattr(uri, key) == value:
setattr(uri, key, value)
updated = True
except:
pass
return updated


updated = False

# need to set status before location
try:
u.status = status
except:
pass
updated = updated | apply_attribute(u, 'status', status)


kwargs['uri'] = uri
allowedargs = ('uri', 'location', 'tags', 'pairs')
kwargs['status'] = status
attrs = ('uri', 'status', 'location', 'tags', 'pairs')

now = datetime.datetime.now()
updated = False

for k, v in kwargs.items():
if not k in allowedargs:
continue
try:
if not getattr(u, k) == v:
setattr(u, k, v)
updated = True
except Exception, e:
pass
for k in attrs:
if k in kwargs:
updated = updated | apply_attribute(u, k, kwargs[k])

if not u.updated or updated:
u.updated = now
now = datetime.datetime.now()

if not u.created:
if newrecord:
u.created = now

self.db.store(u)
u.updated = now
self.db.insert(u)
else:
if updated:
u.updated = now
self.db.update(u)

return u

Expand Down

0 comments on commit ccbd48f

Please sign in to comment.