def get_book_list(): available_books = [] books = Book.objects.all() for cur_book in books: inventory = Inventory.objects(book=cur_book).get() if inventory.stock > 0: available_books.append(cur_book) return available_books
def get_book_list(): available_books = [] books = Book.objects.all() for book in books: inventory = Inventory.objects(book=book).get() if inventory.stock > 0: cur_book = {'book': book, 'inventory': inventory.stock} available_books.append(cur_book) return available_books
def mongo_db_seed(db_name): """ This is a sample mongodb test for populating sample data into mongodb :return: the db connection """ mongoengine.connect(db_name, host='localhost', port=27017) fake = Faker() for x in range(10): Book(title=fake.sentence(nb_words=10, variable_nb_words=True, ext_word_list=None), isbn=fake.isbn13(separator="-"), author=fake.name(), price=round(random.uniform(0, 100), 2), published=datetime.datetime.utcnow(), publisher=fake.company()).save() for book in Book.objects: Inventory( book=book.id, stock=random.randint(1, 100), ).save() for x in range(10): Customer(first_name=fake.first_name(), last_name=fake.last_name(), address=fake.address(), email=fake.email(), password='******', phone=fake.phone_number(), customer_since=datetime.datetime.utcnow(), orders=[]).save() for customer in Customer.objects: for x in range(random.randint(1, 5)): # the Book.objects.aggregate returns a dict. which is weird...was expecting an obj books = [ book['_id'] for book in Book.objects.aggregate(*[{ "$sample": { "size": random.randint(1, 3) } }]) ] total = 0.0 for book in books: total = round(total + Book.objects.with_id(book).price) order = Order(customer_name="{} {}".format(customer.first_name, customer.last_name), books=books, shipping_address=customer.address, total_price=total, order_status="processing", order_date=datetime.datetime.utcnow()).save() customer.orders.append(order.id) customer.save()
def update(): request_json = request.get_json() if 'id' in request_json and 'order_status' in request_json: order = Order.objects(id=request_json['id']).get() if request_json[ 'order_status'] == "fulfilled" and order.order_status == "processing": for book in order.books: inventory = Inventory.objects(book=book).get() inventory.stock -= 1 inventory.save() order.order_status = "fulfilled" order.save() return order.to_json()
def create(): request_json = request.get_json() books = [] # add only the books that is in stock for book in request_json['books']: inventory = Inventory.objects(book=book).get() if inventory.stock > 0: books.append(book) if len(books) > 0: order = Order(customer_name=request_json['customer_name'], books=books, shipping_address=request_json['shipping_address'], total_price=request_json['total_price'], order_status="processing", order_date=datetime.datetime.now).save() return order.to_json() else: return "no order has been created. book out of stock"