Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import uuid
- import json
- import os.path
- class Collection:
- def __init__(self, name, db_name):
- self.name = name
- self.db_name = db_name
- self.data = {}
- filename = db_name + '_' + name
- if (os.path.isfile(filename)):
- datafile = open(filename, "r")
- loaded = json.loads(datafile.read())
- self.data = loaded
- def __getitem__(self, key):
- return self.data[key]
- def __delitem__(self, key):
- del self.data[key]
- def insert(self, dict):
- uid = str(uuid.uuid4())
- self.data[uid] = dict
- self.save()
- return uid
- def find(self, dict):
- results = []
- for key in self.data:
- if(all(item in self.data[key].items() for item in dict.items())):
- results.append(self.data[key])
- return results
- def save(self):
- text = json.dumps(self.data)
- text_file = open(self.db_name + '_' + self.name, "w")
- text_file.write(text)
- text_file.close()
- class DB:
- def __init__(self, name):
- self.name = name
- self.data = {}
- def __getattr__(self, attr):
- if (not(attr in self.__dict__)):
- self.data[attr] = Collection(attr, self.name)
- return self.data[attr]
- def __enter__(self):
- return self
- def __exit__(self, type, value, traceback):
- pass
- # Test
- with DB('db name') as db:
- collection = db.my_product_collection # collection is an instance of Collection
- # 'my_product_collection' can be any string identifying this specific collection
- # One DB has multiple Collections. One Collection has multiple documents
- uid = collection.insert({'my': 'val'}) # insert always get a dict as its sole argument
- print(collection[uid])
- del collection[uid]
- collection.insert({'name': 'Bob', 'group': 'A', 'age': 22})
- collection.insert({'name': 'Alice', 'group': 'A', 'age': 22})
- collection.insert({'name': 'John', 'group': 'B'})
- collection.insert({'name': 'Jack', 'email': 'jack@domain.tld'})
- for uid, it in collection.find({'group': 'A', 'age': 22}):
- # Equivalent to 'SELECT * FROM my_product_collection WHERE group == "A" AND age == 22'
- # Find always receives a dict, the query, and should return all the documents
- # that have all the keys in the query with the right value
- # Here: Bob and Alice
- print('found', uid, it)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement