Skip to content

Instantly share code, notes, and snippets.

@bchaber
Created November 4, 2021 09:32
Show Gist options
  • Save bchaber/27ab3827958637850589d4bd78da2618 to your computer and use it in GitHub Desktop.
Save bchaber/27ab3827958637850589d4bd78da2618 to your computer and use it in GitHub Desktop.
Data-Access-Object for working with Redis database
from json import dumps, loads
class Price:
def __init__(self, db):
self.db = db
def __getitem__(self, item):
price = self.db.hget("price", item)
if price:
return int(price)
class Stock:
def __init__(self, db):
self.db = db
def __iter__(self):
return iter(self.db.hkeys("stock"))
def __getitem__(self, item):
units = self.db.hget("stock", item)
if units:
return int(units)
return 0
def __setitem__(self, item, units):
self.db.hset("stock", item, units)
class Orders:
def __init__(self, db):
self.db = db
self.len = 0
def cancel(self, oid):
self.db.hdel(f"order:{oid}", "items", "total", "owner", "state")
def create(self, uid, order, total):
oid = self.len + 1
self.db.hset(f"order:{oid}", "items", dumps(order))
self.db.hset(f"order:{oid}", "total", total)
self.db.hset(f"order:{oid}", "owner", uid)
self.db.hset(f"order:{oid}", "state", "unpaid")
self.len += 1
return oid
def all(self):
result = []
for order in self.db.keys("order:*"):
result.append(int(order[len("order:"):]))
return result
def for_user(self, uid):
result = []
for order in self.db.keys("order:*"):
owner = self.db.hget(order, "owner")
if str(uid) == owner:
result.append(int(order[len("order:"):]))
return result
def set_state(self, oid, state):
self.db.hset(f"order:{oid}", "state", state)
def __getitem__(self, oid):
items = self.db.hget(f"order:{oid}", "items")
if items:
order = loads(items)
total = self.db.hget(f"order:{oid}", "total")
owner = self.db.hget(f"order:{oid}", "owner")
state = self.db.hget(f"order:{oid}", "state")
return (order, int(total), int(owner), state)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment