Ledger Nano X - The secure hardware wallet
SHARE
TWEET

Untitled

a guest Apr 9th, 2020 128 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask_sqlalchemy import SQLAlchemy
  2. from sqlalchemy import Column, Integer, String, DateTime, func, Boolean
  3.  
  4. from sqlalchemy import create_engine
  5.  
  6. db = SQLAlchemy()
  7.  
  8.  
  9. def init_app(app):
  10.     db.app = app
  11.     db.init_app(app)
  12.     return db
  13.  
  14.  
  15. def create_tables(app):
  16.     engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'])
  17.     db.metadata.create_all(engine)
  18.     return engine
  19.  
  20.  
  21. # represent each item -> should aligned with advertise-api
  22. class Item(db.Model):
  23.  
  24.     __tablename__ = 'item'
  25.     item_id = Column(Integer, primary_key=True, autoincrement=True)
  26.     cart_id = Column(Integer, nullable = False)
  27.     package_id = Column(Integer, nullable=False)
  28.     qty = Column(Integer, nullable=False)
  29.     price = Column(Integer, nullable=False)
  30.  
  31.     def __init__(self, unq_id, price, qty):
  32.         self.package_id = unq_id
  33.         self.price = price
  34.         self.qty = qty
  35.  
  36.     def updateCartId(self, id):
  37.         self.cart_id = id
  38.        
  39.     def to_json(self):
  40.         return {
  41.             'item_id' : self.item_id,
  42.             'cart_id' : self.user_id,
  43.             'package_id' : self.package_id,
  44.             'qty' : self.qty,
  45.             'price' : self.price
  46.         }
  47.  
  48.  
  49. # represent a shopping cart -> includes 1 or more items with varying quantities
  50. class ShoppingCart(db.Model):
  51.  
  52.     __tablename__ = 'shopping-cart'
  53.     cart_id = Column(Integer, primary_key=True, autoincrement=True)
  54.     user_id = Column(String, nullable=False)
  55.     cart_status = Column(db.String(20)) #OPEN --> CLOSED
  56.     created_time = Column(DateTime(timezone=True), server_default=func.now())
  57.     updated_time = Column(DateTime(timezone=True), server_default=func.now())
  58.     total = Column(Integer)
  59.     payment_status = Column(Boolean, default=False)
  60.  
  61.     def __init__(self, user_id):
  62.         self.content = dict() #content of cart
  63.         self.user_id = user_id
  64.         self.payment_status = False
  65.         self.cart_status = "OPEN"
  66.  
  67.     def update(self, item):
  68.         if item.package_id not in self.content:
  69.             self.content.update({item.package_id: item})
  70.             return
  71.         else:
  72.             try:
  73.                 self.content[item.package_id].qty = self.content[item.package_id].qty + item.qty
  74.             except AttributeError:
  75.                 pass
  76.             return
  77.  
  78.     def get_total(self):
  79.         return sum([v.price * v.qty for _, v in self.content.items()])
  80.  
  81.     def get_num_items(self):
  82.         return sum([v.qty for _, v in self.content.items()])
  83.  
  84.     def remove_item(self, key):
  85.         self.content.pop(key)
  86.  
  87.     def to_json(self):
  88.         return {
  89.             'cart_id' : self.cart_id,
  90.             'user_id' : self.user_id,
  91.             'cart_status' : self.cart_status,
  92.             'created_time' : self.created_time,
  93.             'updated_time' : self.updated_time,
  94.             'total' : self.total,
  95.             'payment_status' : self.payment_status
  96.         }
  97.  
  98. class Product(object):
  99.  
  100.     def __init__(self, id, name, price, qty):
  101.         self.product_id = id
  102.         self.qty = qty
  103.         self.name = name
  104.         self.price = price
  105.  
  106.  
  107. #####################################################
  108. import uuid
  109. from . import subscribe_api_blueprint
  110. from flask import request, jsonify, make_response
  111. from sqlalchemy import engine
  112. from sqlalchemy.orm import sessionmaker
  113. from service.model.model import ShoppingCart, Item, Product, db
  114.  
  115. # api-endpoint
  116. ADVERTISE_API_OK = False
  117. ADVERTISE_URL = "http://localhost:4996/packagesApi"
  118. Session = sessionmaker(bind=engine)
  119. session = Session()
  120.  
  121.  
  122. def generateCartId():
  123.     cart_Id = uuid.uuid1()
  124.     return str(cart_Id)
  125.  
  126. def populateCart(id):
  127.     #get all rows with this cartid from Item
  128.     cartItems = Item.query.filter_by(cart_id=id).all()
  129.     return cartItems.__dict__
  130.  
  131.  
  132.  
  133. # add an item to cart
  134. @subscribe_api_blueprint.route("/add", methods=['POST',"GET"])
  135. def addToCart():
  136.     try:
  137.         # parse request
  138.         post_data = request.get_json()
  139.         user = request.json['user_id']
  140.         product_id = request.json['product_id']
  141.         count = request.json['count']
  142.         # try to get cart_id from request -> decides later to create a new cart or not.
  143.         try:
  144.             cart_id = request.json['cart_id']
  145.         except KeyError:
  146.             cart_id = -1
  147.         # get all information about the item
  148.         if ADVERTISE_API_OK:
  149.             r = request.get(url=ADVERTISE_URL + "/" + product_id)
  150.         else:
  151.             r = Product(1,"p1",100, 100)
  152.         if count > int(r.qty):
  153.             responseObject =  {
  154.                 'status': 'fail',
  155.                 'message': 'Item requested is more than available quantity'
  156.             }
  157.             return jsonify(responseObject), 201
  158.         else:
  159.             # create the item object to be added to cart
  160.             item = Item(product_id, r.price, count)
  161.  
  162.             if cart_id == -1:
  163.                 # create a new cart
  164.                 cart = ShoppingCart(user)
  165.                 cart.total = r.price
  166.                 cart.created_time = func.now()
  167.                 cart.payment_status = False
  168.                 cart.cart_status = 'OPEN'
  169.                
  170.                 db.session.add(cart)
  171.                 db.session.commit()
  172.             else:
  173.                 # look into ShoppingCart db to get cart and use the same cart to add items
  174.                 cart = ShoppingCart.query.filter_by(cart_id=cart_id)
  175.                 #calculate cart total
  176.                 cartItems = populateCart(cart.cart_id)
  177.                 print cartItems
  178.                 for each in cartItems:
  179.                     cart.update(each)
  180.                 cart.total = cart.get_total()
  181.                 cart.updated_time = func.now()
  182.                 cart.payment_status = False
  183.                 cart.cart_status = 'OPEN'
  184.                
  185.                 db.session.add(cart)
  186.                 db.session.commit()
  187.            
  188.             #commit item with respective cart_ids to database
  189.             item.updateCartId(cart.cart_id)
  190.             db.session.add(item)
  191.             db.session.commit()
  192.  
  193.             # return cartId if add to cart is success.
  194.             responseObject =  {
  195.                 'status': 'success',
  196.                 cart.to_json()
  197.             }
  198.             return make_response(jsonify(responseObject)), 200
  199.     except Exception as e:
  200.         print(e)
  201.         return jsonify(message="Sorry, exception"), 201
  202.  
  203. # delete an item from cart
  204. @subscribe_api_blueprint.route("/delete", methods=['POST'])
  205. def deleteFromCart():
  206.     try:
  207.         # parse request
  208.         product_id = request.json['product_id']
  209.         pass
  210.     except Exception as e:
  211.         print(e)
  212.  
  213.  
  214. # get cart content
  215. @subscribe_api_blueprint.route("/get", methods=['GET'])
  216. def getCartItems():
  217.     try:
  218.  
  219.         pass
  220.     except Exception as e:
  221.         print(e)
  222.  
  223.  
  224. @subscribe_api_blueprint.route('/test')
  225. def hello_world():
  226.     return 'test!'
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top