-
Notifications
You must be signed in to change notification settings - Fork 0
/
MongoDB.py
93 lines (81 loc) · 3.44 KB
/
MongoDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python3
import sys
from pymongo import MongoClient
class DataBase:
def __init__(self, host = None, port = None):
if host is None and port is None:
try:
self.conn = MongoClient()
self.db = self.conn['db']
self.collection = self.db['collection']
except:
print("Could not connect to MongoDB")
else:
self.host = host
self.port = port
try:
self.conn = MongoClient(host, port)
self.db = self.conn['db']
self.collection = self.db['collection']
except:
print("Could not connect to MongoDB")
def __del__(self):
self.conn.drop_database('db')
def count_book(self, book):
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
if record is None:
return None
return record['stock']
def add_book(self, book):
count = self.collection.find({'Name': book['Name'], 'Author': book['Author']}).count()
if count < 1:
book['stock'] = 0
rec_id = self.collection.insert_one(book)
return rec_id.inserted_id
else:
return "Error: Unable to add. Book already exists"
def buy_book(self, book, amt):
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
if record is not None:
stock = record['stock']
stock += amt
self.collection.update_one({'Name': book['Name'], 'Author': book['Author']},
{"$set": {'stock': stock}})
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
return record
else:
return "Error: Book does not exist"
def sell_book(self, book, amt):
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
if record is not None:
stock = record['stock']
if amt <= stock:
stock -= amt
self.collection.update_one({'Name': book['Name'], 'Author': book['Author']},
{"$set": {'stock': stock}})
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
return record
else:
return "Error: stock is not enough"
else:
return "Error: Book does not exist. Please add book first"
def delete_book(self, book):
record = self.collection.find_one({'Name': book['Name'], 'Author': book['Author']})
if record is not None:
self.collection.delete_one({'Name': book['Name'], 'Author': book['Author']})
return "Success"
else:
return "Error: Unable to delete. Book does not exist"
def list_books(self):
ret_array = list(self.collection.find())
return ret_array
# def exec_action(self, payload):
# action = payload['Action']
# msg = payload['Msg']
# if action == "ADD":
# book = msg['Book Info']
# self.add_book(self, book)
# elif action == 'DELETE':
# book = msg['Book Info']
if __name__ == "__main__":
print("This file encapsulates the MongoDB commands")