class ModelNumber(db.Model): __tablename__ = "did_number" number_id = db.Column(db.Integer, primary_key=True) value = db.Column(db.String(20)) monthy_price = db.Column(db.Float(precision=2)) setup_price = db.Column(db.Float(precision=2)) currency = db.Column(db.String(4)) available = db.Column(db.Boolean) table_id = db.Column(db.Integer, db.ForeignKey("table.id")) table_name = db.relationship( "ModelTable", foreign_keys="ModelNumber.table_id") def __init__(self, id, value, monthy_price, setup_price, currency, available, table_id): self.id = id self.value = value self.monthy_price = monthy_price self.setup_price = setup_price self.currency = currency self.available = available self.table_id = table_id def list_json(self): return { "id": self.number_id, "value": "+{} {} {}-{}".format(self.value[:2], self.value[2:4], self.value[4:9], self.value[9:]), "monthyPrice": "{:.2f}".format(self.monthy_price), "setupPrice": "{:.2f}".format(self.setup_price), "currency": self.currency, "available": self.available, } def number_json(self): return { "id": self.number_id, "value": "+{} {} {}-{}".format(self.value[:2], self.value[2:4], self.value[4:9], self.value[9:]), "monthyPrice": "{:.2f}".format(self.monthy_price), "setupPrice": "{:.2f}".format(self.setup_price), "currency": self.currency, "available": self.available, "table_id": self.table_id if self.table_id else "", "table_name": self.table_name.name if self.table_name else "" } def save_number(self): db.session.add(self) db.session.commit() def delete_number(self): db.session.delete(self) db.session.commit() @classmethod def find_number(cls, number_id): if not number_id: return None number = cls.query.filter_by(number_id=number_id).first() if number: return number return None def update_number(self, id, value, monthy_price, setup_price, currency, available, table_id): self.value = value self.monthy_price = monthy_price self.setup_price = setup_price self.currency = currency self.available = available self.table_id = table_id
class OrderModel(db.Model): __tablename__ = 'order' id = db.Column(db.Integer, primary_key=True) uid = db.Column(db.Integer, db.ForeignKey('user.id')) originalAmount = db.Column(db.Float(precision=2)) finalAmount = db.Column(db.Float(precision=2)) # TODO menu list menus = db.relationship('Menu', secondary=dishes, backref=db.backref('orders', lazy='dynamic')) status = db.Column(db.String(10)) time = db.Column(db.String(10)) phone = db.Column(db.String(20)) deliverAddress = db.Column(db.String(200)) def __init__(self, oid, uid, originalAmount, finalAmount, status, time, phone, deliverAddress): self.id = oid self.uid = uid self.originalAmount = originalAmount self.finalAmount = finalAmount self.status = status self.time = time self.phone = phone self.deliverAddress = deliverAddress def json(self): return { 'oid': self.id, 'uid': self.uid, 'originalAmount': self.originalAmount, 'finalAmount': self.finalAmount, 'status': self.status, 'time': self.time, 'phone': self.phone, 'deliverAddress': self.deliverAddress, 'midList': [menu.id for menu in menus] } def json_extend(self): return { 'oid': self.id, 'uid': self.uid, 'originalAmount': self.originalAmount, 'finalAmount': self.finalAmount, 'status': self.status, 'time': self.time, 'phone': self.phone, 'deliverAddress': self.deliverAddress, 'menu_list': [menu.json() for menu in menus] } @classmethod def find_all(cls): return cls.query.all() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() @classmethod def find_by_user_id(cls, uid): return cls.query.filter_by(id=uid).all() def save_to_db(self): # upsert db.session.add(self) db.session.commit() def delete_from_db(self): # delete db.session.delete(self) db.session.commit()
class ListingModel(db.Model): """The ListingModel object stores information about the listing, as well as the book and user objects associated with it. Attributes: listing_id (int): An id to represent the listing, generated by the table. price (float): The price of the listing. condition (string): The condition of the listing. isbn (int): The isbn of the listing. book (BookModel): The book being represented by the listing. google_tok (string): The google token of the user who made the posting. user (UserModel): The user who made the posting. status (string): The status of the listing. timestamp (int): The time the listing was posted. """ __tablename__ = 'listings' # our listings database # listing id's are assigned by integer key, not used by constructor listing_id = db.Column(db.Integer, primary_key=True) price = db.Column(db.Float(precision=2)) condition = db.Column(db.String(15)) isbn = db.Column(db.Integer, db.ForeignKey('books.isbn')) book = db.relationship('BookModel') google_tok = db.Column(db.String, db.ForeignKey('users.google_tok')) user = db.relationship('UserModel') status = db.Column(db.String(15)) timestamp = db.Column(db.Integer) def __init__(self, price, condition, isbn, google_tok, status): self.price = price self.condition = condition self.isbn = isbn self.google_tok = google_tok self.status = status self.timestamp = datetime.datetime.now() # Both json functions below used to also include 'isbn': self.isbn def listing_json_w_user(self): """Returns the listing jsonified, with a reference to the user who posted. Args: none. Returns: json: A jsonified listing. """ try: return { "listing_id": self.listing_id, 'price': self.price, 'condition': self.condition, 'status': self.status, 'user': self.user.user_json_wo_listings(), 'timestamp': self.timestamp } except: return {"Message": "User does not exist in DB"} def listing_json_w_book(self): """Returns the listing jsonified, with a reference to the book being represented. Args: none. Returns: json: A jsonified listing. """ try: return { "listing_id": self.listing_id, 'price': self.price, 'condition': self.condition, 'status': self.status, 'book': self.book.book_json_wo_listings(), 'timestamp': self.timestamp } except: return {"Message": "Book does not exist in DB"} def listing_json_w_book_and_user(self): """Returns the listing jsonified, with a reference to the book being represented and the user who posted it. Args: none. Returns: json: A jsonified listing. """ try: return { "listing_id": self.listing_id, 'price': self.price, 'condition': self.condition, 'status': self.status, 'book': self.book.book_json_wo_listings(), 'user': self.user.user_json_wo_listings(), 'timestamp': self.timestamp } except: # return {"message": "user deleted"} return {"Message": "Object does not exist in DB"} def bare_json(self): """Returns a json object representing the listing. Args: none. Returns: json: A jsonified listing. """ return { 'price': self.price, 'condition': self.condition, 'status': self.status, "listing_id": self.listing_id, 'timestamp': self.timestamp } def bu_bare_json(self): # Book to user bare jason """Returns a json object representing the listing. Used when going from books to users. Args: none. Returns: json: A jsonified listing. """ return { 'price': self.price, 'condition': self.condition, 'status': self.status, "listing_id": self.listing_id, "google_tok": self.google_tok, 'timestamp': self.timestamp } # def get_user(self): # user = [] # user.append(user.find_by_google_tok(self.google_tok)) # return user @classmethod def find_by_isbn(cls, isbn): # abstracted and redifined from get """Finds all listings matching an isbn. Args: isbn (int): The isbn to search with. Returns: ListingModel[]: A list of listings. """ listings = ListingModel.query.filter_by( name=isbn).all() # returns all listings of isbn as a list if len(listings) > 0: return listings return None @classmethod def find_by_listing_id(cls, listing_id): """Finds all listings matching a listing id. Args: listing_id (int): The listing id to search for. Returns: ListingModel[]: A list of listings. """ listing = ListingModel.query.filter_by(listing_id=listing_id).first() # For next time... How to search ONLY listing_id column??? if listing: return listing return None def save_to_db(self): """Saves the listing to the database. Args: none. Returns: none. """ # write to database # abstracted just like find_by_name so that it can be used by both post and put db.session.add(self) db.session.commit() def delete_from_db(self): """deletes the listing to the database. Args: none. Returns: none. """ db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey("stores.id")) store = db.relationship('StoreModel') def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return {"name": self.name, "price": self.price} @classmethod def find_by_name(cls, name): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # # query = "SELECT * FROM items WHERE name=?" # # result = cursor.execute(query, (name,)) # item = result.fetchone() # # connection.close() # if item: # # This will work, but we can # # replace this two parameters using following approach # # return cls(item[0], item[1]) # return cls(*item) return cls.query.filter_by(name=name).first() # def insert(self): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # # insert_query = "INSERT INTO items VALUES(?, ?)" # # cursor.execute(insert_query, (self.name, self.price)) # # connection.commit() # connection.close() def save_to_db(self): db.session.add(self) db.session.commit() # def update(self): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # # query = "UPDATE items SET price=? WHERE name=?" # # cursor.execute(query, (self.price, self.name)) # # connection.commit() # connection.close() def delete_from_db(self): db.session.delete(self) db.session.commit()
class RestaurantModel(db.Model): __tablename__ = 'restaurant' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True) fee = db.Column(db.Float(precision=2)) limit = db.Column(db.Float(precision=2)) address = db.Column(db.String(200)) openTime = db.Column(db.String(10)) closeTime = db.Column(db.String(10)) isOpen = db.Column(db.Boolean) logo = db.Column(db.String(200)) promo = db.Column(db.String(100)) phone = db.Column(db.String(20)) menu = db.relationship('MenuModel', lazy='dynamic') def __init__(self, _id, name, fee, limit, address, openTime, closeTime, isOpen, logo, promo, phone): self.id = _id self.name = name self.fee = fee self.limit = limit self.address = address self.openTime = openTime self.closeTime = closeTime self.isOpen = isOpen self.logo = logo self.promo = promo self.phone = phone def json(self): return { 'id': self.id, 'name': self.name, 'fee': self.fee, 'limit': self.limit, 'address': self.address, 'openTime': self.openTime, 'closeTime': self.closeTime, 'isOpen': self.isOpen, 'logo': self.logo, 'promo': self.promo, 'phone': self.phone, 'menu': [menu.json() for menu in self.menu.all()] } @classmethod def find_all(cls): return cls.query.all() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() def save_to_db(self): # upsert db.session.add(self) db.session.commit() def delete_from_db(self): # delete db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __table__ = "item" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) def __init__(self, name, price): self.name = name self.price = price def json(self): return {'name': self.name, 'price': self.price} @classmethod def get_item_by_name(cls, name): connection = sqlite3.connect('database.db') cursor = connection.cursor() query = "SELECT * FROM item WHERE name=?" result = cursor.execute(query, (name, )) row = result.fetchone() connection.close() if row: return cls(*row) return None def insert_item(self): connection = sqlite3.connect('database.db') cursor = connection.cursor() query = "INSERT INTO item VALUES(?, ?)" cursor.execute(query, (self.name, self.price)) connection.commit() connection.close() @classmethod def delete_item(cls, name): connection = sqlite3.connect('database.db') cursor = connection.cursor() query = "DELETE FROM item WHERE name=?" cursor.execute(query, (name, )) connection.commit() connection.close() def update_item(self): connection = sqlite3.connect('database.db') cursor = connection.cursor() query = "UPDATE item SET price=? WHERE name=?" cursor.execute(query, (self.price, self.name)) connection.commit() connection.close() @classmethod def get_items(cls): connection = sqlite3.connect('database.db') cursor = connection.cursor() query = "SELECT * FROM item" result = cursor.execute(query) rows = result.fetchall() connection.close() if rows: items = [cls(*i).json() for i in rows] return items return None
class ItemModel(db.Model): __tablename__ = "items" id = db.Column(db.Integer, primary_key=True) #we tell it what column the table contains i.e we tell alchemy their is column called id which is an integer and has ptimary key name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey("stores.id")) #stores.id which is the name of the column in stores.py store = db.relationship("StoreModel") def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return {"name": self.name, "price": self.price} @classmethod #we continue with the class method here because it returns an object of item model as oppose to a dictionary def find_by_name(cls, name): return cls.query.filter_by(name=name).first() # select * FROM items WHERE name = name LIMIT =1 # connection = sqlite3.connect("data.db") # cursor = connection.cursor() # query = "SELECT * FROM items WHERE name=?" # result = cursor.execute(query, (name,)) # row = result.fetchone() # connection.close() # if row: # # return {"item": {"name": row[0], "price":row[1]}} # return cls(*row) #This should return an object of item model instead fo a dictionary def save_to_db(self): # def insert(self): # if self.find_by_name(name): #we can use slef ot Item which is class name # return {"message": "An item with the name '{}' already exist. ".format(name)}, 400 # # if next(filter(lambda x: x["name"] == name, items), None): # # return {"message": "An item with the name '{}' already exist. ".format(name)}, 400 # # data = request.get_json() # data = Item.parser.parse_args() # item = {"name": name, "price": data["price"]} #we create json of the database #ues before adding to database # items.append(item) #append this new item, after you have append then return the item #second method # connection = sqlite3.connect("data.db") # cursor = connection.cursor() # query = "INSERT INTO items VALUES(?, ?)" # cursor.execute(query, (self.name, self.price)) # connection.commit() # connection.close() #third method with sqlalchemy db.session.add(self) #The session is a collections of object to be to the database db.session.commit() #This whole method is good for both update and insert def delete_from_db(self): # def update(self): # connection = sqlite3.connect("data.db") # cursor = connection.cursor() # query = "UPDATE items SET price=? WHERE name=?" # cursor.execute(query, (self.price, self.name)) # connection.commit() # connection.close() db.session.delete(self) db.session.commit()
class TransactionModel(db.Model): __tablename__ = 'transaction' transaction_id = db.Column(db.Integer, primary_key=True, autoincrement=True) amount = db.Column(db.Float(precision=2)) exchange = db.Column(db.Float(precision=2)) method = db.Column(db.String(20)) description = db.Column(db.String(200)) date = db.Column(db.DateTime, default=datetime.now()) is_expense = db.Column(db.Boolean) deleted = db.Column(db.Boolean, default=False) currency_id = db.Column(db.Integer, db.ForeignKey('currency.currency_id'), nullable=True) currency = db.relationship('CurrencyModel') category_id = db.Column(db.Integer, db.ForeignKey('category.category_id'), nullable=False) category = db.relationship('CategoryModel') sale_id = db.Column(db.Integer, db.ForeignKey('sale.sale_id'), nullable=True) sale = db.relationship('SaleModel') def __init__(self, transaction_id, amount, description, date, is_expense, category_id, method, sale_id=None, exchange=None, currency_id=None, deleted=None): self.transaction_id = transaction_id self.amount = amount self.description = description self.method = method if date is not None: formatted_date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") self.date = formatted_date self.is_expense = is_expense self.category_id = category_id self.sale_id = sale_id if exchange is not None: self.exchange = exchange if currency_id is not None: self.currency_id = currency_id if deleted is not None: self.deleted = deleted @classmethod def filter_by_deleted(cls, deleted): return cls.query.filter_by(deleted=deleted).all() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(transaction_id=_id).first() @classmethod def find_by_sale_id(cls, sale_id): return cls.query.filter_by(sale_id=sale_id).all() def update_to_db(self): transaction_to_update = TransactionModel.find_by_id( self.transaction_id) if self.category_id is not None: transaction_to_update.category_id = self.category_id if self.amount is not None: transaction_to_update.amount = self.amount if self.description is not None: transaction_to_update.description = self.description if self.date is not None: formatted_date = datetime.strptime(self.date, "%Y-%m-%d %H:%M:%S") transaction_to_update.date = formatted_date if self.is_expense is not None: transaction_to_update.is_expense = self.is_expense if self.category_id is not None: transaction_to_update.category_id = self.category_id if self.method is not None: transaction_to_update.method = self.method transaction_to_update.save_to_db() @classmethod def find_all(cls): return cls.query.order_by(TransactionModel.date.desc()).all() def save_to_db(self): db.session.add(self) db.session.commit() @classmethod def delete_from_db(cls, transaction_id): transaction_to_delete = cls.find_by_id(transaction_id) transaction_to_delete.deleted = True transaction_to_delete.save_to_db() def json(self): return { 'transaction_id': self.transaction_id, 'amount': self.amount, 'description': self.description, 'currency_id': self.currency_id, 'method': self.method, 'date': str(self.date)[:19], 'category_id': self.category_id, 'is_expense': self.is_expense, 'exchange': self.exchange, 'sale_id': self.sale_id, 'deleted': self.deleted }
#import sqlite3 from db import db class ItemModel(db.Model): __tablename__='items' id=db.Column(db.Integer,primary_key=True) name=db.Column(db.String(80)) price=db.Column(db.Float(precision=2)) store_id=db.Column(db.Integer,db.ForeignKey('store.id')) store=db.relationship('StoreModel') def __init__(self,name,price,store_id): self.name=name self.price=price self.store_id=store_id def json(self): return {'name':self.name,'price':self.price} @classmethod def find_by_name(cls,name): return cls.query.filter_by(name=name).first() #similar to select query '''connection=sqlite.connect('data.db') cursor=connection.cursor() query="SELECT * FROM items WHERE name=?" result=cursor.execute(query,(name,)) row=result.fetchone()
class ItemModel( db.Model ): #extend the classes so that the alchemy can be interacted with __tablename__ = 'items' id = db.Column( db.Integer, primary_key=True) #we will also assign an ID to the item now name = db.Column(db.String(20)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) store = db.relationship( 'StoreModel') #this means that the joins are no longer needed, the #sqlalchemy by looking at this knows that the items table #has a foreign key and thus the ItemModel has a relationship #with StoreModel #the same can also be done in the StoreModel def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): #this will return a json representation of an item return {"name": self.name, "price": self.price, "store": self.store_id} @classmethod def get_by_name(cls, name): print("trying to retrieve item") return cls.query.filter_by(name=name).first() # this will automatically create the query using the ItemModel class extended to db.Model #No need to build any connections or cursors #SELECT * FROM items WHERE name = name #This will return the first row only #And the return will be in form of ItemModel object #connection = sqlite3.connect('data.db') #cursor = connection.cursor() #fetch_query = "SELECT * FROM items WHERE name = ?" #result = cursor.execute(fetch_query, (name,)) #row = result.fetchone() #connection.close() #if row: #return cls(row[0], row[1]) #return an object ItemModel #this is a perfect scenario for argument unpacking. #hence: # return cls(*row) #return None @classmethod def search_item_exist_in_store(cls, name, store): return cls.query.filter_by(name=name, store_id=store).first() def save_to_db( self ): # as this is simply putting an object into the db, we no longer need #separate functions for insert and update db.session.add( self ) #no need to define the column and values because db already knows it. db.session.commit() #connection = sqlite3.connect('data.db') #cursor = connection.cursor() #insert_query = "INSERT INTO items VALUES (?,?)" #result = cursor.execute(insert_query, (self.name, self.price)) #connection.commit() #connection.close() def delete_from_db(self): db.session.delete(self) db.session.commit()
class ItemModel(db.Model): __tablename__ = "item_tbl" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey("store_tbl.id")) store = db.relationship("StoreModel") def __init__(self, _id=None, name=None, price=None, store_id=None): self.id = _id self.name = name self.price = price self.store_id = store_id def json(self): return { "id": self.id, "item_name": self.name, "item_price": self.price, "store_id": self.store_id } def save_item(self): try: db.session.add(self) db.session.commit() return {"message": "Success", "status": True}, 200 except: return { "error": "An error has been occur, Please restart it again!", "status": False }, 500 def get_item(self, item_id): try: return self.query.filter_by(id=item_id).first() except: return { "error": "An error has been occur, Please restart it again!", "status": False } def delete_item(self): try: db.session.delete(self) db.session.commit() return {"message": "Item removed success", "status": True}, 200 except: return { "error": "An error has been occur, Please restart it again!", "status": False }, 500 def get_items(self): try: items = self.query.all() if items: return [item.json() for item in items] except: return { "error": "An error has been occur, Please restart it again!", "status": False } @classmethod def get_all(self): try: return self.query.all() except: return { "error": "An error has been occur, Please restart it again!", "status": False } @classmethod def get_item_by_name(cls, name): try: return cls.query.filter_by(name=name).first() except: return { "error": "An error has been occur, Please restart it again!", "status": False }, 500 @classmethod def get_item_by_id(cls, id): try: return cls.query.filter_by(id=id).first() except: return { "error": "An error has been occur, Please restart it again!", "status": False }, 500
class UserModel(db.Model): __tablename__ = 'users' user_id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(100), unique=True, nullable=False) password = db.Column(db.String(255), nullable=False) first_name = db.Column(db.String(80)) last_name = db.Column(db.String(80)) role = db.Column(db.Integer, default=2) # 1:admin, 2: seller, 3:promoter salary = db.Column(db.Float(precision=2), default=0.00) seller_commissions = db.Column(db.Float(precision=2), default=0.00) def __init__(self, email, password, first_name, last_name, role=None): if not (role and role != 1): role = UserModel.check_if_admin(email) self.role = role self.email = email self.password = password self.first_name = first_name self.last_name = last_name def __repr__(self): return '<User %r>' % self.email def update_to_db(self, user_id): user_to_update = UserModel.find_by_id(user_id) if self.first_name is not None: user_to_update.first_name = self.first_name if self.last_name is not None: user_to_update.last_name = self.last_name if self.password is not None: user_to_update.password = self.password if self.salary is not None: user_to_update.salary = self.salary if not (self.role and self.role != 1): user_to_update.role = UserModel.check_if_admin( user_to_update.email) else: user_to_update.role = self.role user_to_update.save_to_db() @classmethod def check_if_admin(cls, email): role = 2 with open('./config.json', 'r') as f: config = json.load(f) admins = config["admins"] for admin in admins: if email == admin["email"]: role = 1 return role def save_to_db(self): db.session.add(self) db.session.commit() @classmethod def find_by_mail(cls, email): return cls.query.filter_by(email=email).first() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(user_id=_id).first() @classmethod def delete_by_id(cls, _id): user = cls.find_by_id(_id) db.session.delete(user) db.session.commit() return @classmethod def find_all(cls): return cls.query.order_by(UserModel.last_name).all() @classmethod def find_promoters(cls): return cls.query.filter(UserModel.role.in_((1, 2, 3))).all() @classmethod def find_sellers(cls): return cls.query.filter(UserModel.role.in_((1, 2))).all() def json(self): return { 'user_id': self.user_id, 'email': self.email, 'first_name': self.first_name, 'last_name': self.last_name, 'role': self.role }
class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50)) price = db.Column(db.Float(precision=2)) store_id = db.Column(db.Integer, db.ForeignKey('stores.id')) stores = db.relationship('StoreModel') def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def json(self): return { 'name': self.name, 'price': self.price, 'store_id': self.store_id } @classmethod def find_by_name(cls, name): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # query = "SELECT * FROM items WHERE name=?" # result = cursor.execute(query, (name,)) # row = result.fetchone() # connection.commit() # connection.close() # if row: # item = cls(*row) #send the row list as * and constructor will unpack it # return item # return row item = cls.query.filter_by( name=name).first() #same as SELECT * FROM items LIMIT 1; return item # def insert_item(self): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # query = "INSERT INTO items VALUES(?,?)" # result = cursor.execute(query, (self.name, self.price)) # connection.commit() # connection.close() # def update_item(self): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # query = 'UPDATE items SET price=? WHERE name=?' # cursor.execute(query, (self.price, self.name)) # connection.commit() # connection.close() def save_to_db(self): db.session.add(self) db.session.commit() def delete_item(self): # connection = sqlite3.connect('data.db') # cursor = connection.cursor() # query = 'DELETE FROM items WHERE name=?' # cursor.execute(query, (self.name,)) # connection.commit() # connection.close() db.session.delete(self) db.session.commit()
class MotosModel(db.Model): """ Object DB SQL Model: Motos """ __tablename__ = 'motos' id = db.Column(db.Integer(), primary_key=True, unique=True, nullable=False, autoincrement=True) license_number = db.Column(db.String(), nullable=False) battery = db.Column(db.Integer(), nullable=False) available = db.Column(db.Boolean(), nullable=False) latitude = db.Column(db.Float(), nullable=False) longitude = db.Column(db.Float(), nullable=False) def __init__(self, license_number, battery, latitude, longitude): self.license_number = license_number self.battery = battery self.available = battery > 15.0 self.latitude = latitude self.longitude = longitude def json(self): """ Converts Motos to JSON and returns it Return: dict """ return { 'id': self.id, 'license_number': self.license_number, 'battery': self.battery, 'available': self.available, 'latitude': self.latitude, 'longitude': self.longitude } def save_to_db(self): """ Adds a moto into the database """ db.session.add(self) db.session.commit() def delete_from_db(self): """ Deletes a moto from database """ db.session.delete(self) db.session.commit() def set_available(self, available): self.available = available db.session.commit() def update_coords(self, latitude, longitude): self.latitude = latitude self.longitude = longitude db.session.commit() @classmethod def find_by_id(cls, id): """ Finds an user by id Param: number id Return: MotosModel """ return MotosModel.query.filter_by(id=id).first() @classmethod def all_motos(cls): """ Finds all MotosModel and returns them Return: all MotosModels """ return MotosModel.query.all() @classmethod def get_available_motos(cls, available): """ Finds availiable MotosModel and returns them Return: all available MotosModels """ return MotosModel.query.filter_by(available=available).all() @classmethod def find_by_license_number(cls, license_number): """ Finds a moto by license_number Param: number license_number Return: MotosModel """ return MotosModel.query.filter_by( license_number=license_number).first() @classmethod def find_last_rentals_info(cls, moto, num_rentals, associated_rentals): """ Finds n last rentals from a moto Param: moto id and rentals num Return: Json """ final_list = [moto.json()] count = 0 associated_rentals_json = [ rental.json() for rental in associated_rentals ] sorted_associated_rentals = sorted(associated_rentals_json, key=lambda k: k['id']) sorted_associated_rentals.reverse() for rental in sorted_associated_rentals: if (count < num_rentals): count += 1 user = UsersModel.find_by_id(rental['user_id']) final_list.append([rental, user.json()]) else: break return final_list
class MenuModel(db.Model): __tablename__ = 'menu' id = db.Column(db.Integer, primary_key=True) restaurantID = db.Column(db.Integer, db.ForeignKey('restaurant.id')) name = db.Column(db.String(30), unique=True) price = db.Column(db.Float(precision=2)) category = db.Column(db.String(20)) description = db.Column(db.String(300)) spicy = db.Column(db.Integer) isAvailable = db.Column(db.Boolean) isRecommended = db.Column(db.Boolean) image = db.Column(db.String(2000)) restaurant = db.relationship('RestaurantModel') def __init__(self, _id, restaurantID, name, price, category, description, spicy, isAvailable, isRecommended, image): self.id = _id self.restaurantID = restaurantID self.name = name self.price = price self.category = category self.description = description self.spicy = spicy self.isAvailable = isAvailable self.isRecommended = isRecommended self.image = image def json(self): return { 'id': self.id, 'restaurantID': self.restaurantID, 'name': self.name, 'price': self.price, 'category': self.category, 'description': self.description, 'spicy': self.spicy, 'isAvailable': self.isAvailable, 'isRecommended': self.isRecommended, 'image': self.image } @classmethod def find_all(cls): return cls.query.all() @classmethod def find_by_id(cls, mid): return cls.query.filter_by(id=mid).first() @classmethod def find_by_name(cls, restaurantID, name): return cls.query.filter_by(restaurantID=restaurantID, name=name).first() @classmethod def find_like_name(cls, restaurantID, name): return cls.query.filter_by(restaurantID=restaurantID).filter( cls.name.like(name)) @classmethod def find_by_category(cls, restaurantID, category): return cls.query.filter_by(restaurantID=restaurantID, category=category) def save_to_db(self): # upsert db.session.add(self) db.session.commit() def delete_from_db(self): # delete db.session.delete(self) db.session.commit()