backend-development-course/app/local_db.py

163 lines
3.8 KiB
Python
Raw Permalink Normal View History

2024-10-28 17:19:47 +02:00
import uuid
2024-10-28 20:10:04 +02:00
import time
2024-10-28 17:19:47 +02:00
class LocalDB:
def __init__(self):
self.users = {}
self.categories = {}
self.records = {}
def reset(self):
for k, v in list(self.users.items()):
if v == "test1":
del self.users[k]
2024-10-28 18:18:28 +02:00
for k, v in list(self.categories.items()):
if v == "test2":
del self.categories[k]
2024-10-28 17:19:47 +02:00
def get_users(self):
return self.users
def get_user(self, uid):
if uid in self.users:
return {
'uuid': uid,
'name': self.users[uid]
}
else:
return {}
def add_user(self, name):
if not name:
return {}
if name in set(self.users.values()):
return {}
new_uuid = uuid.uuid4().hex
self.users[new_uuid] = name
return {
'uuid': new_uuid,
'name': name
}
def del_user(self, uid):
if uid in self.users:
name = self.users[uid]
del self.users[uid]
return {
'uuid': uid,
'name': name
}
else:
return {}
2024-10-28 18:18:28 +02:00
def get_category(self, uid):
if uid in self.categories:
return {
'uuid': uid,
'name': self.categories[uid]
}
else:
return {}
def add_category(self, name):
if not name:
return {}
if name in set(self.categories.values()):
return {}
new_uuid = uuid.uuid4().hex
self.categories[new_uuid] = name
return {
'uuid': new_uuid,
'name': name
}
def del_category(self, uid):
if uid in self.categories:
name = self.categories[uid]
del self.categories[uid]
return {
'uuid': uid,
'name': name
}
else:
return {}
2024-10-28 20:10:04 +02:00
def get_record(self, uid):
if uid in self.records:
r = self.records[uid]
return {
'uuid': uid,
'user_id': r['user_id'],
'cat_id': r['cat_id'],
'date': r['date'],
'amount': r['amount']
}
else:
return {}
def filter_records(self, filters):
results = []
for k, v in self.records.items():
if 'user_id' in filters and v['user_id'] != filters['user_id']:
continue
if 'cat_id' in filters and v['cat_id'] != filters['cat_id']:
continue
results.append({
'uuid': k,
'user_id': v['user_id'],
'cat_id': v['cat_id'],
'date': v['date'],
'amount': v['amount']
})
return results
def add_record(self, user_id, cat_id, amount):
if user_id not in self.users:
return {}
if cat_id not in self.categories:
return {}
new_uuid = uuid.uuid4().hex
self.records[new_uuid] = {
'user_id': user_id,
'cat_id': cat_id,
'date': time.time(),
'amount': amount
}
return {
'uuid': new_uuid,
'user_id': user_id,
'cat_id': cat_id,
'date': time.time(),
'amount': amount
}
def del_record(self, uid):
if uid in self.records:
r = self.records[uid]
del self.records[uid]
return {
'uuid': uid,
'user_id': r['user_id'],
'cat_id': r['cat_id'],
'date': r['date'],
'amount': r['amount']
}
else:
return {}