Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from flask_sqlalchemy import SQLAlchemy
- from sqlalchemy import Column, Integer, String, DateTime, func, Boolean
- from sqlalchemy import create_engine
- db = SQLAlchemy()
- def init_app(app):
- db.app = app
- db.init_app(app)
- return db
- def create_tables(app):
- engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
- db.metadata.create_all(engine)
- return engine
- # represent each item -> should aligned with advertise-api
- class Item(db.Model):
- __tablename__ = 'item'
- item_id = Column(Integer, primary_key=True, autoincrement=True)
- cart_id = Column(Integer, nullable = False)
- package_id = Column(Integer, nullable=False)
- qty = Column(Integer, nullable=False)
- price = Column(Integer, nullable=False)
- def __init__(self, unq_id, price, qty):
- self.package_id = unq_id
- self.price = price
- self.qty = qty
- def updateCartId(self, id):
- self.cart_id = id
- def to_json(self):
- return {
- 'item_id' : self.item_id,
- 'cart_id' : self.user_id,
- 'package_id' : self.package_id,
- 'qty' : self.qty,
- 'price' : self.price
- }
- # represent a shopping cart -> includes 1 or more items with varying quantities
- class ShoppingCart(db.Model):
- __tablename__ = 'shopping-cart'
- cart_id = Column(Integer, primary_key=True, autoincrement=True)
- user_id = Column(String, nullable=False)
- cart_status = Column(db.String(20)) #OPEN --> CLOSED
- created_time = Column(DateTime(timezone=True), server_default=func.now())
- updated_time = Column(DateTime(timezone=True), server_default=func.now())
- total = Column(Integer)
- payment_status = Column(Boolean, default=False)
- def __init__(self, user_id):
- self.content = dict() #content of cart
- self.user_id = user_id
- self.payment_status = False
- self.cart_status = "OPEN"
- def update(self, item):
- if item.package_id not in self.content:
- self.content.update({item.package_id: item})
- return
- else:
- try:
- self.content[item.package_id].qty = self.content[item.package_id].qty + item.qty
- except AttributeError:
- pass
- return
- def get_total(self):
- return sum([v.price * v.qty for _, v in self.content.items()])
- def get_num_items(self):
- return sum([v.qty for _, v in self.content.items()])
- def remove_item(self, key):
- self.content.pop(key)
- def to_json(self):
- return {
- 'cart_id' : self.cart_id,
- 'user_id' : self.user_id,
- 'cart_status' : self.cart_status,
- 'created_time' : self.created_time,
- 'updated_time' : self.updated_time,
- 'total' : self.total,
- 'payment_status' : self.payment_status
- }
- class Product(object):
- def __init__(self, id, name, price, qty):
- self.product_id = id
- self.qty = qty
- self.name = name
- self.price = price
- #####################################################
- import uuid
- from . import subscribe_api_blueprint
- from flask import request, jsonify, make_response
- from sqlalchemy import engine
- from sqlalchemy.orm import sessionmaker
- from service.model.model import ShoppingCart, Item, Product, db
- # api-endpoint
- ADVERTISE_API_OK = False
- ADVERTISE_URL = "http://localhost:4996/packagesApi"
- Session = sessionmaker(bind=engine)
- session = Session()
- def generateCartId():
- cart_Id = uuid.uuid1()
- return str(cart_Id)
- def populateCart(id):
- #get all rows with this cartid from Item
- cartItems = Item.query.filter_by(cart_id=id).all()
- return cartItems.__dict__
- # add an item to cart
- @subscribe_api_blueprint.route("/add", methods=['POST',"GET"])
- def addToCart():
- try:
- # parse request
- post_data = request.get_json()
- user = request.json['user_id']
- product_id = request.json['product_id']
- count = request.json['count']
- # try to get cart_id from request -> decides later to create a new cart or not.
- try:
- cart_id = request.json['cart_id']
- except KeyError:
- cart_id = -1
- # get all information about the item
- if ADVERTISE_API_OK:
- r = request.get(url=ADVERTISE_URL + "/" + product_id)
- else:
- r = Product(1,"p1",100, 100)
- if count > int(r.qty):
- responseObject = {
- 'status': 'fail',
- 'message': 'Item requested is more than available quantity'
- }
- return jsonify(responseObject), 201
- else:
- # create the item object to be added to cart
- item = Item(product_id, r.price, count)
- if cart_id == -1:
- # create a new cart
- cart = ShoppingCart(user)
- cart.total = r.price
- cart.created_time = func.now()
- cart.payment_status = False
- cart.cart_status = 'OPEN'
- db.session.add(cart)
- db.session.commit()
- else:
- # look into ShoppingCart db to get cart and use the same cart to add items
- cart = ShoppingCart.query.filter_by(cart_id=cart_id)
- #calculate cart total
- cartItems = populateCart(cart.cart_id)
- print cartItems
- for each in cartItems:
- cart.update(each)
- cart.total = cart.get_total()
- cart.updated_time = func.now()
- cart.payment_status = False
- cart.cart_status = 'OPEN'
- db.session.add(cart)
- db.session.commit()
- #commit item with respective cart_ids to database
- item.updateCartId(cart.cart_id)
- db.session.add(item)
- db.session.commit()
- # return cartId if add to cart is success.
- responseObject = {
- 'status': 'success',
- cart.to_json()
- }
- return make_response(jsonify(responseObject)), 200
- except Exception as e:
- print(e)
- return jsonify(message="Sorry, exception"), 201
- # delete an item from cart
- @subscribe_api_blueprint.route("/delete", methods=['POST'])
- def deleteFromCart():
- try:
- # parse request
- product_id = request.json['product_id']
- pass
- except Exception as e:
- print(e)
- # get cart content
- @subscribe_api_blueprint.route("/get", methods=['GET'])
- def getCartItems():
- try:
- pass
- except Exception as e:
- print(e)
- @subscribe_api_blueprint.route('/test')
- def hello_world():
- return 'test!'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement