class User(db.Model, UserMixin): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(150), nullable=False) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) login_count = db.Column(db.Integer) current_login_ip = db.Column(db.String(255)) current_login_at = db.Column(db.DateTime, default=datetime.utcnow) created_at = db.Column(db.DateTime, default=datetime.utcnow) updated_at = db.Column(db.DateTime, default=datetime.utcnow) posts = db.relationship('Post', backref='author', lazy='dynamic') comments = db.relationship('Comment', backref='author', lazy='dynamic') roles = db.relationship('Role', secondary=role_users, backref=db.backref('users', lazy="dynamic"), cascade="save-update, merge, delete") def __init__(self, email, password=None, *args, **kwargs): super(User, self).__init__(email=email, password=password, *args, **kwargs) if not self.username: self.username = self.email.split("@")[0] if not self.roles: user_role = Role.query.filter(Role.name == 'user').first() self.roles.append(user_role) def __repr__(self): return f'<User #{self.id} {self.email}>'
class SensorTypes(db.Model): sensor_type_id = db.Column(db.Integer, unique=True, nullable=False, primary_key=True) sensor_type_value = db.Column(db.String(80), unique=False, nullable=False, primary_key=False) sensor_type_title = db.Column(db.String(80), unique=False, nullable=False, primary_key=False) def __repr__(self): return"<Title>: {}>".format(self.sensor_type_title)
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), index=True) password = db.Column(db.String(128)) fio = db.Column(db.String(32), default=None) def to_dict(self): return { 'username': self.username, 'fio': self.fio, } @staticmethod def current(): idx = 1 user = User.query.get(idx) if user is None: user = User(fio='ООО "Интернет магазин"', username='******') db.session.add(user) db.session.commit() return user def verify_password(self, password): # TODO: Hash password in future return password == self.password
class Files(db.Model): id: int name: str filename: str created_date: datetime id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer) name = db.Column(db.String(256)) filename = db.Column(db.String(256)) filename_norm = db.Column(db.String(256), default=None) status = db.Column(db.String(20)) processed = db.Column(db.Integer, default=0) failed = db.Column(db.Integer, default=0) created_date = db.Column(db.DateTime(timezone=True), server_default=func.now()) finish_date = db.Column(db.DateTime(timezone=True), default=None) def as_dict(self): d = {} for c in self.__table__.columns: d[c.name] = getattr(self, c.name) if c.name == 'created_date': d[c.name] = d[c.name].isoformat() return d
class User(db.Model): uid = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(32), unique=True) password_hash = db.Column(db.String(144)) timelines = db.relationship('Timeline', backref='owner', lazy='joined') def __init__(self, username, password): self.username = username self.password_hash = generate_password_hash(password, method='sha512') @classmethod def authenticate(cls, username, password): """Authenticates details of a user Parameters ---------- username : str The username of the user to authenticate password : str The password to authenticate with Returns ------- User The authenticated user """ if any(i is None for i in (username, password)): return dict(error='missing fields'), 400 user = cls.query.filter_by(username=username).first() if user is None or not check_password_hash(user.password_hash, password): return dict(error='incorrect credentials or user doesn\'t exist'), 401 else: token = create_access_token(identity=user) return dict(username=user.username, token=token), 200
class MessageQueue(db.Model): id = db.Column(db.Integer, primary_key=True) channel_name = db.Column(db.String(120), unique=False, nullable=False) uuid = db.Column(db.String(40), unique=False, nullable=False) message_id = db.Column(db.Integer, unique=False, nullable=False) created_date = db.Column(db.TIMESTAMP, default=datetime.utcnow) def __init__(self, channel_name, uuid, message_id): self.channel_name = channel_name self.uuid = uuid self.message_id = message_id self.created_date = datetime.utcnow() def dict(self): sub = { "channel_name": self.channel_name, "uuid": self.uuid, "created": int((self.created_date - datetime.utcfromtimestamp(0)).total_seconds()), } return sub
class Image(db.Model): __tablename__ = 'images' id = db.Column('id', db.Integer, primary_key=True) url = db.Column('url', db.String(255), nullable=False) def __init__(self, filename): self.url = 'images/' + filename
class Unit(db.Model): __tablename__ = 'units' id = db.Column('id', db.Integer, primary_key=True) name = db.Column('name', db.String(10), unique=True, nullable=False) def __init__(self, name): self.name = name
class Gcm(db.Model): id = db.Column(INTEGER(unsigned=True), primary_key=True) uuid = db.Column(db.VARCHAR(40), nullable=False) gcmid = db.Column(db.TEXT, nullable=False) timestamp_created = db.Column(db.TIMESTAMP, default=datetime.utcnow) def __init__(self, device, gcmid): self.uuid = device self.gcmid = gcmid def __repr__(self): return '<Gcm {}>'.format(self.uuid) def as_dict(self): data = { "uuid": self.service.as_dict(), "gcm_registration_id": self.gcmId, "timestamp": int(self.timestamp_created.strftime('%s')), } return data @staticmethod def send_message(message): """ :type message: Message """ subscriptions = Subscription.query.filter_by( service=message.service).all() if len(subscriptions) == 0: return 0 gcm_devices = Gcm.query.filter( Gcm.uuid.in_([l.device for l in subscriptions])).all() if len(gcm_devices) > 0: data = dict(message=message.as_dict(), encrypted=False) Gcm.gcm_send([r.gcmid for r in gcm_devices], data) if len(gcm_devices) > 0: uuids = [g.uuid for g in gcm_devices] gcm_subscriptions = Subscription.query.filter_by( service=message.service).filter( Subscription.device.in_(uuids)).all() last_message = Message.query.order_by(Message.id.desc()).first() for l in gcm_subscriptions: l.timestamp_checked = datetime.utcnow() l.last_read = last_message.id if last_message else 0 db.session.commit() return len(gcm_devices) @staticmethod def gcm_send(ids, data): url = 'https://android.googleapis.com/gcm/send' headers = dict(Authorization='key={}'.format(google_api_key)) data = dict(registration_ids=ids, data=data) if current_app.config['TESTING'] is True: current_app.config['TESTING_GCM'].append(data) else: requests.post(url, json=data, headers=headers)
class Event(db.Model): __tablename__ = "events" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True) paused = db.Column(db.Boolean) paused_until = db.Column(db.DateTime) current_topic_id = db.Column(db.Integer) topics = relationship("Topic", backref=backref("event"), cascade="all, delete-orphan") speakers = relationship("Speaker", backref=backref("event"), cascade="all, delete-orphan") def __init__(self, name, paused=False, current_topic_id=None): self.name = name self.paused = paused self.paused_until = datetime(1970, 1, 1) self.current_topic_id = current_topic_id or -1 def __repr__(self): return "<Event(id={}, name={}, paused={}, paused_until={})>".format( self.id, self.name, self.paused, self.paused_until) def sorted_topics(self): return sorted(self.topics, key=lambda tp: tp.get_index()) def get_current_topic(self): candidates = [ topic for topic in self.topics if topic.id == self.current_topic_id ] if len(candidates) < 1: return None return candidates[0]
class Users(db.Model, UserMixin): __tablename__ = 'users' # Primary key id = db.Column(db.Integer, primary_key=True) # Columns email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Roles', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) # Representation def __repr__(self): return '<id %r>' % self.id # Check if a user email exists @classmethod def check_user(class_, email): Users = class_ # Query for the email user = Users.query.filter_by(email=email).first() # Return true if exists if user: return user else: return False
class DefaultTOP(DatabaseModel): __tablename__ = "defaulttops" __model_name__ = "defaulttop" id = db.Column(db.Integer, primary_key=True) protocoltype_id = db.Column(db.Integer, db.ForeignKey("protocoltypes.id")) name = db.Column(db.Text) number = db.Column(db.Integer) description = db.Column(db.Text) localtops = relationship("LocalTOP", backref=backref("defaulttop"), cascade="all, delete-orphan") def get_parent(self): return self.protocoltype def is_at_end(self): return self.number > 0 def get_localtop(self, protocol): return LocalTOP.query.filter_by(defaulttop_id=self.id, protocol_id=protocol.id).first() def get_top(self, protocol): localtop = self.get_localtop(protocol) top = TOP(protocol_id=protocol.id, name=self.name, description=getattr(localtop, "description", "")) return top
class Genre(db.Model): __tablename__ = 'genres' id = db.Column(db.Integer, primary_key=True, autoincrement=True) description = db.Column(db.String(100)) def __repr__(self): return f"<Genre id={self.id} description={self.description}>"
class Room(db.Model): __tablename__ = "rooms" id = db.Column("room_id", db.Integer, primary_key=True) info = db.Column("info", db.String(), nullable=True) name = db.Column("name", db.String(50), nullable=False) seats = db.relationship('Seat', back_populates="room", cascade="all, delete") def __init__(self, name, info): self.name = name self.info = info def get_seat_list(self): seat_list = list(map(lambda x: x.to_json(), self.seats)) sorted_seat_list = sorted(seat_list, key=lambda x: x['id']) return sorted_seat_list def to_json(self): return { "id": self.id, "name": self.name, "info": self.info, "seats": { "count": len(self.seats), "seats": self.get_seat_list(), }, } def __str__(self): return str(self.__class__) + ":" + str(self.__dict__)
class Subscription(db.Model): id = db.Column(INTEGER(unsigned=True), primary_key=True) device = db.Column(db.VARCHAR(40), nullable=False) service_id = db.Column(INTEGER(unsigned=True), db.ForeignKey('service.id'), nullable=False) service = db.relationship('Service', backref=db.backref('subscription', lazy='dynamic')) timestamp_created = db.Column(db.TIMESTAMP, default=datetime.utcnow) timestamp_checked = db.Column(db.TIMESTAMP) def __init__(self, device, service): self.device = device self.service = service self.timestamp_checked = datetime.utcnow() - timedelta(minutes=30) def __repr__(self): return '<Subscription %r>' % self.id def messages(self): return Message.query \ .filter_by(service_id=self.service_id) \ .filter(Message.timestamp_created > self.timestamp_checked) def as_dict(self): data = { "uuid": self.device, "service": self.service.as_dict(), "timestamp": int(self.timestamp_created.strftime('%s')), "timestamp_checked": int(self.timestamp_checked.strftime('%s')) } return data
class Board(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(32), nullable=False) rules = db.Column(db.String, nullable=True) threads = relationship("Thread", order_by=desc(Thread.last_updated)) max_threads = db.Column(db.Integer, default=50) mimetypes = db.Column(db.String, nullable=False)
class GoalLike(db.Model): __tablename__ = "goal_like" id = db.Column(db.Integer, primary_key=True) goal_id = db.Column(db.ForeignKey('goal.id')) user_id = db.Column(db.ForeignKey('user.id')) created_at = db.Column(db.DateTime, default=datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.now())
class SuccessStoryLike(db.Model): __tablename__ = "success_story_like" id = db.Column(db.Integer, primary_key=True) success_story_id = db.Column(db.ForeignKey('successstory.id')) user_id = db.Column(db.ForeignKey('user.id')) created_at = db.Column(db.DateTime, default=datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.now())
class LikeTodoAssociation(DatabaseModel): __tablename__ = "liketodoassociations" like_id = db.Column(db.Integer, db.ForeignKey("likes.id"), primary_key=True) todo_id = db.Column(db.Integer, db.ForeignKey("todos.id"), primary_key=True)
class LikeProtocolAssociation(DatabaseModel): __tablename__ = "likeprotocolassociations" like_id = db.Column(db.Integer, db.ForeignKey("likes.id"), primary_key=True) protocol_id = db.Column(db.Integer, db.ForeignKey("protocols.id"), primary_key=True)
class OldTodo(DatabaseModel): __tablename__ = "oldtodos" __model_name__ = "oldtodo" id = db.Column(db.Integer, primary_key=True) old_id = db.Column(db.Integer) who = db.Column(db.Text) description = db.Column(db.Text) protocol_key = db.Column(db.Text)
class DecisionCategoryAssociation(DatabaseModel): __tablename__ = "decisioncategoryassociations" decision_id = db.Column(db.Integer, db.ForeignKey("decisions.id"), primary_key=True) decisioncategory_id = db.Column(db.Integer, db.ForeignKey("decisioncategories.id"), primary_key=True)
class ClassType(db.Model): __tablename__ = "class_types" id = db.Column(db.Integer, primary_key=True) value = db.Column(db.String) def __init__(self, value): self.value = value
class LikeDecisionAssociation(DatabaseModel): __tablename__ = "likedecisionassociations" like_id = db.Column(db.Integer, db.ForeignKey("likes.id"), primary_key=True) decision_id = db.Column(db.Integer, db.ForeignKey("decisions.id"), primary_key=True)
class List(db.Model): __tablename__ = "list" id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.ForeignKey('user.id')) name = db.Column(db.String(128), nullable=False) created_at = db.Column(db.DateTime, default=datetime.now()) updated_at = db.Column(db.DateTime, default=datetime.now()) goals = db.relationship('UserGoal', backref="list", lazy='dynamic')
class TodoProtocolAssociation(DatabaseModel): __tablename__ = "todoprotocolassociations" todo_id = db.Column(db.Integer, db.ForeignKey("todos.id"), primary_key=True) protocol_id = db.Column(db.Integer, db.ForeignKey("protocols.id"), primary_key=True)
class Tag(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) bg_style = db.Column(db.String, nullable=True) text_style = db.Column(db.String, nullable=True) def to_dict(self): return {"name": self.name}
class Poster(db.Model): id = db.Column(db.Integer, primary_key=True) hex_string = db.Column(db.String(4), nullable=False) ip_address = db.Column(db.String(15), nullable=False) thread = db.Column(db.Integer, db.ForeignKey("thread.id", ondelete="CASCADE"), nullable=False) slip = db.Column(db.Integer, db.ForeignKey("slip.id"), nullable=True)
class Media(db.Model): id = db.Column(db.Integer, primary_key=True) ext = db.Column(db.String(4), nullable=False) mimetype = db.Column(db.String(255), nullable=False) is_animated = db.Column(db.Boolean, nullable=False) def delete_attachment(self): storage.delete_attachment(self.id, self.ext)
class TodoMail(DatabaseModel): __tablename__ = "todomails" __model_name__ = "todomail" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(128), unique=True) mail = db.Column(db.Text) def get_formatted_mail(self): return "{} <{}>".format(self.name, self.mail)