class StoreModel(db.Model):
    __tablename__ = 'stores'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    items = db.relationship('ItemModel', lazy='dynamic')

    # a nice explanation for lazy='dynamic': https://www.jianshu.com/p/8427da16729a
    # when lazy='dynamic', self.items is no longer a list of items, it becomes a query builder
    # it need .all() to execute the query

    def __init__(self, name):
        self.name = name

    def json(self):
        return {
            "id": self.id,
            "name": self.name,
            "items": [item.json() for item in self.items.all()]
        }

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()
        # SELECT * FROM items WHERE name = name LIMIT 1

    @classmethod
    def find_all(cls):
        return cls.query.all()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #2
0
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 {
            'id': self.id, 
            'name': self.name, 
            'price': self.price, 
            'store_id': self.store_id
        }

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()

    @classmethod
    def find_all(cls):
        return cls.query.all()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #3
0
class InstrumentModel(BaseModel):
    __tablename__ = 'instrument'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(250), nullable=False, unique=True)
    description = db.Column(db.String(512))
    model = db.Column(db.String(80))
    status = db.Column(db.String(80), default='unpaired')
    pairing_code = db.Column(db.String(80), unique=True)
    created_at_utc = db.Column(db.DateTime,
                               nullable=False,
                               default=datetime.utcnow())

    clinic_id = db.Column(db.Integer,
                          db.ForeignKey('clinic.id'),
                          nullable=False)
    clinic = db.relationship('ClinicModel',
                             backref='InstrumentModel',
                             lazy=True)

    @classmethod
    def find_by_name(cls, name):
        """Find the model by name"""
        return cls.query.filter_by(name=name).first()

    @staticmethod
    def parent_id_exists(path_id):
        """Check if clinic with id=path_id exists in the DB"""
        if not ClinicModel.find_by_id(path_id):
            raise ValidationError(
                'Clinic with id={} does not exist.'.format(path_id))

    def set_parent_id(self, parent_id):
        self.clinic_id = parent_id

    @classmethod
    def get_from_db(cls, parent_field=None, parent_id=None, self_id=None):
        return super().get_from_db(cls.clinic_id, parent_id, self_id)
Beispiel #4
0
class ItemModel(db.Model):
    __tablename__ = 'items'  # defining the table name used in this resource

    # which attribute of the table is to be used, must be same as the instance variables
    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

    # return the item object in JSON format
    def json(self):
        return {
            'name': self.name,
            'price': self.price,
            'store_id': self.store_id
        }

    # gets the row from the DB and returns it in ItemModel object format
    @classmethod
    def get_by_name(cls, name):
        return cls.query.filter_by(name=name).first()

    # adds itself to the DB
    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    # Deletes itself from the DB
    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #5
0
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'))  #gets the id from the id field in the stores table
    store = db.relationship(
        'StoreModel'
    )  # item property that lets sql that each item is related to only one store. many to one

    # it sets a property that shows which store in the Store table the store_id is attached to

    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
        }  #return json version of the item model

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(
            name=name).first()  # SELECT * FROM items WHERE name=name LIMIT 1

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #6
0
class User(Bot, db.Model):
    __tablename__ = 'users'
    __table_args__ = (db.UniqueConstraint('psid', 'id', name='unique_user_orders'),
                      )
    id = db.Column(db.Integer, primary_key=True)
    psid = db.Column(db.String, unique=True)
    name = db.Column(db.String(80))
    phone_number = db.Column(db.String)
    address = db.Column(db.String)
    orders = db.relationship('Order', backref='user', lazy='dynamic')

    def __init__(self, psid):
        super().__init__()
        self.psid = psid
        self.name = ''
        self.phone_number = 0
        self.address = ''

    @classmethod
    def find_by_psid(cls, psid):
        return cls.query.filter_by(psid=psid).first()

    def get_info(self):
        request_endpoint = '{}/{}'.format(self.graph_url, self.psid)
        response = requests.get(
            request_endpoint,
            params=self.auth_args
        )
        result = response.json()
        self.name = result['first_name']

    def save(self):
        db.session.add(self)
        db.session.commit()

    def remove(self):
        db.session.remove(self)
        db.session.commit()
Beispiel #7
0
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}

    #talking to db to find the given name record
    #since the method is used before creating this object, so we use classmethod
    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(
            name=name).first()  #SELECT * FROM items WHERE name = name

    @classmethod
    def find_all(cls):
        return cls.query

    #Insert into db by the given item(name,price)
    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    #Update the item with given name to price
    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #8
0
class Lecture(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    description = db.Column(db.String(500))
    day = db.Column(db.Integer)
    start_time = db.Column(db.String(5))
    end_time = db.Column(db.String(5))
    speaker_id = db.Column(db.Integer, db.ForeignKey('speaker.id'))
    speaker = db.relationship('Speaker', backref=db.backref('lecture'))

    def __init__(self, id_, speaker_id, title, description, day, start_time,
                 end_time):
        self.id = id_
        self.speaker_id = speaker_id
        self.title = title
        self.description = description
        self.day = day
        self.start_time = start_time
        self.end_time = end_time

    def __str__(self):
        return 'Lecture #{}: {}'.format(self.id, self.title)

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'speaker_id': self.speaker_id,
            'day': self.day,
            'start_time': self.start_time,
            'end_time': self.end_time
        }

    @staticmethod
    def get(id_=None):
        return _lectures if id_ is None else Lecture.query.filter_by(
            id=id_).first()
Beispiel #9
0
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'))

    # List of items - Many to One
    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 ItemModel.query.filter_by(name=name).first()

    def save_to_db(self):
        # SQL alchemy add to database
        db.session.add(self)
        db.session.commit()

    # Delete our item
    def delete_from_db(self, name):
        db.session.delete(self)
        db.session.commit()

    #Print
    def __str__(self):
        return 'name : {} \nprice: {}'.format(self.name, self.price)
Beispiel #10
0
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):
        return cls.query.filter_by(name=name).first() # SELECT * FROM items WHERE name=name LIMIT 1

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

        # connection = sqlite3.connect("data.db")
        # cursor = connection.cursor()

        # query = "INSERT INTO items VALUES (?, ?)"
        # cursor.execute(query, (self.name, self.price))

        # connection.commit()
        # connection.close()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
class PasswordRecoveryRequestModel(db.Model):

    __tablename__ = "password_recovery_request"

    id = db.Column(db.String(50), primary_key=True)
    expire_at = db.Column(db.Integer, nullable=False)
    change_made = db.Column(db.Boolean, nullable=False, default=False)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)
    user = db.relationship("UserModel")

    def __init__(self, user_id: int, **kwargs):
        super().__init__(**kwargs)

        self.id = uuid4().hex
        self.expire_at = int(
            time()) + PASSWORD_RECOVERY_REQUEST_EXPIRATION_DELTA
        self.user_id = user_id

    @classmethod
    def find_by_id(cls, _id) -> "PasswordRecoveryRequestModel":
        return cls.query.filter_by(id=_id).first()

    @property
    def expired(self) -> bool:
        return time() > self.expire_at

    def force_to_expire(self):
        if not self.expired:
            self.expire_at = int(time())
            self.save_to_db()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #12
0
class ConfirmationModel(db.Model):
    __tablename__ = "confirmations"

    id = db.Column(db.String(50), primary_key=True)
    expire_at = db.Column(db.Integer, nullable=False)
    confirmed = db.Column(db.Boolean, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    user = db.relationship("UserModel")

    def __init__(self, user_id: int, **kwargs):
        super().__init__(**kwargs)
        self.user_id = user_id
        self.id = uuid4().hex
        self.expire_at = int(time()) + int(
            os.environ.get("CONFIRMATION_EXPIRATION_DELTA")
        )
        self.confirmed = False

    @classmethod
    def find_by_id(cls, id: str) -> "ConfirmationModel":
        return cls.query.filter_by(id=id).first()

    @property
    def expired(self) -> bool:
        return time() > self.expire_at

    def forced_to_expire(self) -> None:
        if not self.expired:
            self.expire_at = time()
            self.save_to_db()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.remove(self)
        db.session.commit()
Beispiel #13
0
class CarrierModel(db.Model):
    __tablename__ = 'carriers'

    id = db.Column(db.Integer, primary_key=True)
    carriername = db.Column(db.String(25))
    carrierdomain = db.Column(db.String(25))

    usercarrier = db.relationship('UserModel',
                                  backref='carrier',
                                  lazy='dynamic',
                                  foreign_keys='UserModel.carrierid')

    def __init__(self, carriername, carrierdomain):
        self.carriername = carriername
        self.carrierdomain = carrierdomain

    def json(self):
        return {
            "id": self.id,
            "carriername": self.carriername,
            "carrierdomain": self.carrierdomain
        }

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    @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(carriername=name).first()
Beispiel #14
0
class CustModel(db.Model):
    __tablename__ = 'cust'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    pos = db.relationship('PoModel', lazy='dynamic')

    def __init__(self, name):
        self.name = name

    def json_t(self):
        return {
            'name': self.name,
            'pos': [item.json() for item in self.items.all()]
        }

    @classmethod
    def find_by_name(cls, name):
        # conn = sqlite3.connect('tb.db')
        # cursor = conn.cursor()
        # query = "select * from items where name = ?"
        # results = cursor.execute(query, (name,))
        # row = results.fetchone()
        # conn.close()
        #
        # if row:
        #     return cls(*row)

        return cls.query.filter_by(name=name).first()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def del_from_db(self):
        db.delete(self)
        db.session.commit()
Beispiel #15
0
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 to_json(self):
        """Return a json representation of the object."""
        return {'id': self.id,
                'name': self.name,
                'price': self.price,
                'store_id': self.store_id
                }

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()  # 'SELECT * FROM items WHERE name=name LIMIT 1'

    @classmethod
    def find_all(cls):
        return cls.query.all()

    def save_to_db(self):
        """Upsert (update or insert) data into db."""
        db.session.add(self)  # 'INSERT INTO items VALUES (?, ?)' 'UPDATE items SET price=? WHERE name=?'
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #16
0
class IngredientModel(db.Model):
    __tablename__ = 'ingredients'

    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(50))
    amount = db.Column(db.Float(precision=2))
    measurement = db.Column(db.String(20))

    recipe_id = db.Column(db.Integer,db.ForeignKey('recipes.id'))
    recipe = db.relationship('RecipeModel')

    def __init__(self,name,amount,measurement,recipe_id):
        self.name = name
        self.amount = amount
        self.measurement = measurement
        self.recipe_id = recipe_id

    def json(self):
        return {
            'id' : self.id,
            'name': self.name,
            'amount' : self.amount,
            'measurement' = self.measurement
        }

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    def find_by_id(cls , _id):
        return cls.query.filter_by(id=_id).first()

    def find_by_recipe(cls, recipe_id):
        return cls.query.filter_by(recipe_id=recipe_id)
Beispiel #17
0
class FAQModel(db.Model):
    __tablename__ = 'faq'
    id = db.Column(db.Integer, unique=True, primary_key=True)
    category = db.relationship('CategoryModel', secondary=category, backref=db.backref('faq', lazy='dynamic'))
    question = db.Column(db.String(30), unique=False, nullable=False)
    answer = db.Column(db.String(30), unique=False, nullable=False)

    def __init__(self, faq_category,question, answer):
        self.question = question
        self.answer = answer
        self.category.append(faq_category)

    def json(self):
        categor = [cat.json() for cat in self.category]
        return {
            "id": self.id,
            "category": categor,
            "question": self.question,
            "answer": self.answer,
        }

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()

    @classmethod
    def find_by_id(cls, idd):
        return FAQModel.query.filter_by(id=idd).first()

    @classmethod
    def get_faqs(cls):
        list_faq = [faq.json() for faq in FAQModel.query.all()]
        dicc = {"FAQ": list_faq}
        return dicc
Beispiel #18
0
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_item_by_name(cls, name):
        return cls.query.filter_by(name=name).first()

    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()
        db.session.commit()
Beispiel #19
0
class TagModel(db.Model):
    __tablename__ = "tags"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(120))

    article = db.relationship('ArticleTagModel')

    def __init__(self, name):
        self.name = name.lower()

    def json(self):
        return {"id": self.id, "name": self.name }

    @classmethod
    def find_by_id(cls,_id):
        return cls.query.filter_by(id=_id).first()

    @classmethod
    def search_by_name(cls,name):
        return cls.query.filter(cls.name.like('%' + name + '%'))

    @classmethod
    def exists(cls,name):
        query = cls.query.filter_by(name=name).first()
        return bool(query)

    @classmethod
    def get_all_tags(cls,tags):
        return cls.query.filter(cls.id.in_(tags))

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #20
0
class ItemModel(db.Model):
    __tablename__ = "items"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True)
    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: str, price: float, store_id: int):
        self.name = name
        self.price = price
        self.store_id = store_id

    def json(self) -> ItemJSON:
        return {
            "id": self.id,
            "name": self.name,
            "price": self.price,
            "store_id": self.store_id,
        }

    @classmethod
    def find_by_name(cls, name: str) -> "ItemModel":
        return cls.query.filter_by(name=name).first()

    @classmethod
    def find_all(cls) -> List["ItemModel"]:
        return cls.query.all()

    def save_to_db(self) -> None:
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self) -> None:
        db.session.delete(self)
        db.session.commit()
class ConfirmationModel(db.Model):
    __tablename__ = "confirmations"

    id = db.Column(db.String(50), primary_key=True)
    expire_at = db.Column(db.Integer, nullable=False)
    confirmed = db.Column(db.Boolean, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    user = db.relationship("UserModel")

    def __init__(self, user_id: int, **kwargs):
        # Initializes expire_at, confirmed, user_id
        super().__init__(**kwargs)
        self.user_id = user_id
        self.id = uuid4().hex
        self.expire_at = int(time()) + CONFIRMATION_EXPIRATION_DELTA
        self.confirmed = False

    @classmethod
    def find_by_id(cls, _id: str) -> "ConfirmationModel":
        return cls.query.filter_by(id=_id).first()

    @property
    def expired(self):
        return time(
        ) > self.expire_at  # current time > time ago + confirmation delta

    def force_to_expire(self):
        if not self.expired:
            self.expire_at = int(time())
            self.save_to_db()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #22
0
class ItemModel(db.Model): #Extends 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) ) #precision is places after decimal point

    store_id = db.Column( db.Integer , db.ForeignKey('stores.id')) #Item has a foreign key which is 'Store' primary key!
    store = db.relationship('StoreModel') #This is a 'JOIN' between items and store tables
                                          #Now each 'ItemModel' has a property called 'store'
                                          #that is a 'StoreModel' type that matches the store_id^

    def __init__(self , name , price , store_id):
        self.name = name
        self.price = price
        self.store_id = store_id

    def json(self): #Returns JSON representation of 'ItemModel'
        return {'name' : self.name , 'price' : self.price }

    @classmethod
    def find_by_name( cls , name ):
        return cls.query.filter_by(name=name).first() #SELECT * FROM iterms WHERE name = name
        #No need to connect or have a cursor ... ItemModel.query belongs to db.Model, and
        #filter_by will filter a Model by name.
        #You can also continue to filter: filter_by(...).filter_by(...).
        #.first() does a LIMIT 1
        #The query is essentially a SQL command

    def save_to_db(self):
        print("Item is {0}: ".format(self.name))
        db.session.add(self) #'session' belonds to db and it is a collection of objects we add to.
        db.session.commit() #Note: SQLAlchemy will do an 'update' it actually updates. (upserting)

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #23
0
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')  #maps the item to the respective store

    #in the storemodel table

    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}
        #we will still use a class method in this since we have to return a class object
        #through this funtion as opposed to a dictionary
    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()
        #return items model object representing the data

#since we have made a class with the instances variable we dont need a classmethod

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #24
0
class UserModel(db.Model):
    __tablename__ = "users"
    id = db.Column(db.String(50), primary_key=True)
    playerId = db.Column(db.String(9), unique=True)
    username = db.Column(db.String(36), unique=True)
    ip = db.Column(db.String(50), nullable=True)
    created_at = db.Column(db.TIMESTAMP(), default=datetime.datetime.utcnow)
    updated_at = db.Column(db.TIMESTAMP(), default=datetime.datetime.utcnow)
    last_online = db.Column(db.TIMESTAMP(), default=datetime.datetime.utcnow)

    settings = db.relationship(
        "UserSettingsModel", lazy="joined", cascade="all, delete-orphan"
    )

    @classmethod
    def find_by_id(cls, _id: str) -> "UserModel":
        return cls.query.filter_by(id=_id).first()

    @classmethod
    def find_by_playerId(cls, playerId: str) -> "UserModel":
        return cls.query.filter_by(playerId=playerId).first()

    @classmethod
    def find_by_username(cls, username: str) -> "UserModel":
        return cls.query.filter_by(username=username).first()

    @staticmethod
    def get_new_PlayerId():
        return (random.sample(random.choice(string.ascii_uppercase), 3) +
                random.sample(range(0, 10), 6))

    def save_to_db(self) -> None:
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self) -> None:
        db.session.delete(self)
        db.session.commit()
Beispiel #25
0
class StoreModel(db.Model):
    __tablename__ = 'stores'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    #För att välja antalet decimaler använd "precision"

    #skapar upp en "flera till en"-relation med ItemModel och därav en lista av "ItemModels"
    #läs på om "lazy". Har något med avvägningen av hastighet vid skapande och sökande av i tabeller
    items = db.relationship('ItemModel', lazy='dynamic')

    def __init__(self, name):
        self.name = name

    #.all är kopplat till "lazy=dynamic".
    def json(self):
        return {
            'name': self.name,
            'items': [item.json() for item in self.items.all()]
        }

    @classmethod
    def find_by_name(cls, name):
        #query kommer från SQLAlchemy som vi enkelt bygger querys med.
        #return ItemModel.query.filter_by(name=name) #SELECT * FROM items WHERE name=name
        #return ItemModel.query.filter_by(name=name).filter_by(id=1) #filterar på flera värden
        #return ItemModel.query.filter_by(name=name, id=1) #filterar på flera argument
        return cls.query.filter_by(name=name).first(
        )  # SELECT * FROM items WHERE name=name LIMIT 1, returnerar den första raden.

    def save_to_db(self):
        #Session är alla objekt i denna sessionen som vi skall skriva till databasen
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
class StoreModel(db.Model):
    __tablename__ = 'stores'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    items = db.relationship(
        'ItemModel', lazy='dynamic'
    )  # it Allow the store table to see items table and we use lazy= 'dynamic' To prevent it from creating a file for each item that has a stored id. It will take up space

    def __init__(self, name):
        self.name = name

    def json(self):
        return {
            "id": self.id,
            "name": self.name,
            "items": [
                item.json() for item in self.items.all()
            ],  #Because i use lazy= 'dynamic' i can use self.items as a query but it will go to table every time and it will be slowe
        }

    @classmethod
    def find_item_by_name(cls, name):
        return cls.query.filter_by(
            name=name).first()  # SELECT * FROM items WHERE name = name LIMIT 1

    @classmethod
    def find_all(cls):
        return cls.query.all()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #27
0
class StoreModel(db.Model):

    __tablename__ = 'stores'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))

    items = db.relationship('ItemModel', lazy='dynamic')
    

    def __init__(self, name):
        self.name = name
        

    def json(self):
        return {'name': self.name, 'items': [item.json() for item in self.items.all()]}


    @classmethod
    def find_by_name(cls, name):
        #return Item Model object
       return cls.query.filter_by(name=name).first() # Select * from items where name=name
       #or
       #return ItemModel.query.filter_by(name=name).first() # Select * from items where name=name

     
    #insert and update both can be acheived by this method
    #@classmethod
    def save_to_db(self):
        db.session.add(self)
        db.session.commit()



    # @classmethod
    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()       
Beispiel #28
0
class BrandModel(db.Model):
    __tablename__ = 'brands'

    id = db.Column(db.Integer, primary_key=True)
    name = db.column(db.string(80))
    description = db.column(db.string(80))
    created_at = db.Column(db.DateTime, nullable=False,
        default=datetime.utcnow)				
    updated_at = db.Column(db.DateTime, nullable=False,
        default=datetime.utcnow)				

    branches = db.relationship('BranchModel', lazy='dynamic')


    def __init__(self, name, description, created_at, updated_at):
    	self.firstname = name
    	self.lastname = description
    	self.created_at = created_at
        self.updated_at = updated_at

 	def json(self):
        return {'name': self.name, }

    @classmethod
    def find_by_name(cls, name):
        return cls.query.filter_by(name=name).first()

    @classmethod
    def find_by_id(cls, _id):
        return cls.query.filter_by(id=_id).first()

   	def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #29
0
class ItemModel(db.Model):
    __tablename__ = 'items'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    description = db.Column(db.String(400))
    link = db.Column(db.String(100))
    image_link = db.Column(db.String(200))

    store_id = db.Column(db.Integer, db.ForeignKey('stores.id'))
    store = db.relationship('StoreModel')

    def __init__(self, title, description, link, image_link, store_id):
        self.title = title
        self.description = description
        self.link = link
        self.image_link = image_link
        self.store_id = store_id

    def json(self):
        return {
            'title ': self.title,
            'description': self.description,
            'link': self.link,
            'image_link': self.image_link
        }

    @classmethod
    def find_by_title(cls, title):
        return cls.query.filter_by(title=title).first()

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()
Beispiel #30
0
class StoreModel(db.Model):
    __tablename__ = "stores"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))  # max name size is 80 char

    # item = db.relationship('ItemModel') #this says there is a relationship between Storemodel and itemmodel
    # this is a many to one relationship so
    # item is a list of items
    # and it will be created an object for every item in the Store
    # to reduce the amount of memory used we will use
    items = db.relationship("ItemModel", lazy="dynamic")

    def __init__(self, name):
        self.name = name

    def json(self):
        return {
            "name": self.name,
            "items": [item.json() for item in self.items.all()],
        }  # .all transform self.items in a query builder insted of a list and .all retrieves all the items in that table
        # this will make this method slower (it's a trade off.. previous version will have store creation slower)

    @classmethod
    def find_by_name(cls, name):
        # using sql alchemy to make queries

        return cls.query.filter_by(name=name).first(
        )  # same as Select * from items where name= name LIMIT 1
        # is returning an object

    def save_to_db(self):
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self):
        db.session.delete(self)
        db.session.commit()