Skip to content

Commit

Permalink
Merge pull request #114 from bbonenfant/implement-hash-setnx
Browse files Browse the repository at this point in the history
Setnx method on the Hash object.
  • Loading branch information
coleifer committed Jan 8, 2020
2 parents b4ab286 + 6fdffc4 commit 870cb4a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions walrus/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ def items(self, lazy=False):
else:
return list(self)

def setnx(self, key, value):
"""
Set ``key`` to ``value`` if ``key`` does not exist.
:returns: True if successfully set or False if the key already existed.
"""
return bool(self.database.hsetnx(self.key, key, value))

@chainable_method
def update(self, *args, **kwargs):
"""
Expand Down
5 changes: 5 additions & 0 deletions walrus/tests/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ def test_from_dict(self):
hsh = Hash.from_dict(db, 'test', data)
self.assertEqual(hsh.as_dict(True), data)

def test_setnx(self):
key, value = "key_setnx", "value_setnx"
self.assertTrue(self.hsh.setnx(key, value))
self.assertFalse(self.hsh.setnx(key, value))


class TestSet(WalrusTestCase):
def setUp(self):
Expand Down

0 comments on commit 870cb4a

Please sign in to comment.