class Table11(DeclarativeBase, ApiModule): """ test 11 table """ __tablename__ = 'table11' __serialization__ = get_serialization( AttributeConfiguration(name='id', supports_json=(False, True)), AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='table01_id', supports_json=(True, False)), AttributeConfiguration(name='table01nams', supports_json=(False, True)), ) id = Column(Integer, primary_key=True) name = Column(Unicode(256), nullable=False, unique=True) table01_id = Column(Integer, ForeignKey('table01.id')) Table01 = get_table_cls(ApiModule, 'table01') Table01.__serialization__.append( AttributeConfiguration(name='table11s', supports_json=(False, True)), ) Table01.table11s = relationship('Table11') table01nams = column_property( select([(Table01.name)], table01_id == Table01.id))
class Client(Base, db.Model): __serialization__ = [ AttributeConfiguration(name='id', csv_sequence=1, **supported_serialization), AttributeConfiguration(name='short_name', **supported_serialization), AttributeConfiguration(name='long_name', **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) short_name = db.Column(db.String(64), nullable=False) long_name = db.Column(db.String(128), nullable=False) assessments = db.relationship('Assessment', back_populates='client') templates = db.relationship('Template', secondary=client_template, back_populates='clients') creator_id = db.Column(db.Integer, db.ForeignKey('user.id', onupdate="CASCADE", ondelete="CASCADE"), nullable=False) creator = db.relationship("User", back_populates="created_clients", uselist=False) managers = db.relationship('User', secondary=client_management, back_populates='managed_clients') auditors = db.relationship('User', secondary=client_audit, back_populates='audited_clients')
class Users(DeclarativeBase): """ user """ __tablename__ = 'users' __serialization__ = [ AttributeConfiguration(name='id', supports_json=True), AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='key', supports_json=(True, False)), AttributeConfiguration(name='group_id', supports_json=(True, False)), #AttributeConfiguration(name='group', supports_json=(False, True)), AttributeConfiguration(name='group_name', supports_json=(False, True)), ] id = Column( Integer, primary_key=True, ) name = Column( Unicode(256), nullable=False, unique=True, ) key = Column(Unicode(512), ) group_id = Column( Integer, ForeignKey('groups.id'), nullable=False, ) group = relationship( 'Groups', back_populates='users', )
class Active(Base, db.Model): __table_args__ = (db.UniqueConstraint('assessment_id', 'name'), ) __serialization__ = [ AttributeConfiguration(name='name', csv_sequence=1, **supported_serialization), AttributeConfiguration(name='uris', **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) assessment_id = db.Column(db.Integer, db.ForeignKey('assessment.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) assessment = db.relationship(Assessment, uselist=False) name = db.Column(db.String(128)) active_resources = db.relationship('AffectedResource', back_populates='active') @property def uris(self): for resource in self.active_resources: yield resource.uri
class User_OneToOne_Nested(BaseModel): """Mocked class with a single primary key.""" __tablename__ = 'users_one_to_one' __serialization__ = [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='address', supports_json=True, supports_yaml=(True, True), supports_dict=(True, True)), ] id = Column('id', Integer, primary_key=True) name = Column('username', String(50)) address = relationship('Address_Nested_OneToOne', backref='user', uselist=False)
class TestClass(BaseModel): __tablename__ = 'test_class' __serialization__ = { 'two_properties': [ AttributeConfiguration(name='id', supports_csv=False, supports_json=True, supports_dict=True, supports_yaml=False), AttributeConfiguration(name='second_column', supports_csv=True, supports_json=True, supports_dict=True, supports_yaml=False) ], 'one_property': [ AttributeConfiguration(name='id', supports_csv=True, supports_json=True, supports_dict=True, supports_yaml=True) ] } id = Column('id', Integer, primary_key=True) second_column = Column('second_column', Text)
class Address_Nested_OneToOne(BaseModel): """Mocked class with a single primary key.""" __tablename__ = 'addresses_nested_one_to_one' __serialization__ = [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='email', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None), ] id = Column('id', Integer, primary_key=True) email = Column('email_address', String(50), supports_csv=True, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=validators.email, on_deserialize=validators.email) user_id = Column('user_id', Integer, ForeignKey('users_one_to_one.id'))
class ModulesPermissions(DeclarativeBase, ApiModule): """ Resource Modules Permissions """ __tablename__ = 'modules_permissions' __http__ = ['GET', 'PUT'] __serialization__ = get_serialization( AttributeConfiguration(name='permission_level', supports_json=True), AttributeConfiguration(name='group_id', supports_json=False), AttributeConfiguration(name='module_id', supports_json=False), AttributeConfiguration(name='group', supports_json=(False, True)), AttributeConfiguration(name='module', supports_json=(False, True)), ) __table_args__ = (UniqueConstraint('group_id', 'module_id', name='_modules_permissions_uc'), ) permission_level = Column(Integer, nullable=False) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) module_id = Column(Integer, ForeignKey('modules.id'), nullable=False) group = column_property(select([(Groups.name)], group_id == Groups.id)) module = column_property(select([(Modules.name)], module_id == Modules.id))
class Client(Base, db.Model): __serialization__ = [ AttributeConfiguration(name='id', csv_sequence=1, **supported_serialization), AttributeConfiguration(name='short_name', **supported_serialization), AttributeConfiguration(name='long_name', **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) short_name = db.Column(db.String(64), nullable=False) long_name = db.Column(db.String(128), nullable=False) assessments = db.relationship('Assessment', back_populates='client') templates = db.relationship('Template', secondary=client_template, back_populates='clients') creator_id = db.Column(db.Integer, db.ForeignKey('user.id', onupdate="CASCADE", ondelete="CASCADE"), nullable=False) creator = db.relationship("User", back_populates="created_clients", uselist=False) managers = db.relationship('User', secondary=client_management, back_populates='managed_clients') auditors = db.relationship('User', secondary=client_audit, back_populates='audited_clients') finding_counter = db.Column(db.Integer, default=0, nullable=False) def generate_finding_counter(self) -> int: tx_commit = False while not tx_commit: self.finding_counter = Client.finding_counter + 1 db.session.add(self) try: db.session.commit() tx_commit = True except Exception as ex: pass return self.finding_counter def format_finding_code(self, finding) -> str: client_name_prefix = unidecode(self.short_name).replace(" ", "_").upper() return f"{client_name_prefix}_{finding.assessment.creation_date:%Y%m%d}_{finding.client_finding_id:06d}"
class TestClass(BaseModel): __tablename__ = 'test_class' __serialization__ = [ AttributeConfiguration(name='id', supports_json=True, supports_dict=True), AttributeConfiguration(name='json_column', supports_json=True, supports_dict=True) ] id = Column('id', Integer, primary_key=True) json_column = Column(JSON)
class Modules(DeclarativeBase): __tablename__ = 'modules' __serialization__ = [ AttributeConfiguration(name='id', supports_json=(False, True)), AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='groups', supports_json=(False, True)), ] id = Column(Integer, primary_key=(False, True)) name = Column(Unicode(256), nullable=False, unique=True) groups = relationship('ModulesPermissions', cascade='all, delete-orphan')
class Table01(DeclarativeBase, ApiModule): """ test 01 table """ __tablename__ = 'table01' __serialization__ = get_serialization( AttributeConfiguration(name='id', supports_json=(False, True)), AttributeConfiguration(name='name', supports_json=True), ) id = Column(Integer, primary_key=True) name = Column(Unicode(256), nullable=False, unique=True)
class Groups(DeclarativeBase, ApiModule): """ Ресурс групп """ __tablename__ = 'groups' __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='users', supports_json=(False, True)), AttributeConfiguration(name='modules', supports_json=(False, True)), ) name = Column(Unicode(256), nullable=False, unique=True) users = relationship('Users', cascade='all, delete-orphan') modules = relationship('ModulesPermissions', cascade='all, delete-orphan')
class AffectedResource(Base, db.Model): __table_args__ = (db.UniqueConstraint('active_id', 'route'), ) __serialization__ = [ AttributeConfiguration(name='uri', csv_sequence=1, **supported_serialization), ] id = db.Column(db.Integer, primary_key=True) active_id = db.Column(db.Integer, db.ForeignKey('active.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) active = db.relationship(Active, uselist=False, back_populates='active_resources') route = db.Column(db.String(256)) findings = db.relationship('Finding', secondary=finding_affected_resource) @property def uri(self): return "{}{}".format(self.active.name, self.route or '') def delete_last_reference(self): if len(self.findings) == 1: if len(self.active.active_resources ) == 1 and self.active.active_resources[0] is self: self.active.delete() else: self.delete()
class Geoms(DeclarativeBase, ApiModule): """ Resource Reference of Geoms """ __tablename__ = 'geoms' __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='properties', supports_json=True), AttributeConfiguration(name='layers', supports_json=(False, True)), ) name = Column(Unicode(256), nullable=False, unique=True) properties = Column(JsonType()) layers = relationship('Layers', cascade='all, delete-orphan')
class Users(DeclarativeBase): __tablename__ = 'users' __serialization__ = [ AttributeConfiguration(name='id', supports_json=(False, True)), AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='key', supports_json=(True, False)), AttributeConfiguration(name='group_id', supports_json=(True, False)), AttributeConfiguration(name='group', supports_json=(False, True)), ] id = Column(Integer, primary_key=True,) name = Column(Unicode(256), nullable=False, unique=True) key = Column(Unicode(512)) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) group = column_property(select([(Groups.name)], group_id == Groups.id))
class Users(DeclarativeBase, ApiModule): """ Ресурс пользователей """ __tablename__ = 'users' __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='key', supports_json=(True, False)), AttributeConfiguration(name='group_id', supports_json=(True, False)), AttributeConfiguration(name='group', supports_json=(False, True)), ) name = Column(Unicode(256), nullable=False, unique=True) key = Column(Unicode(512)) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) group = column_property(select([(Groups.name)], group_id == Groups.id))
class Modules(DeclarativeBase, ApiModule): __tablename__ = 'modules' __http__ = ['GET', 'PUT'] __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=(False, True)), AttributeConfiguration(name='access', supports_json=(False, True)), AttributeConfiguration(name='enable', supports_json=True), AttributeConfiguration(name='delete', supports_json=True), AttributeConfiguration(name='groups', supports_json=(False, True)), ) name = Column(Unicode(256), nullable=False, unique=True) access = Column(Boolean, default=False) enable = Column(Boolean, default=True) delete = Column(Boolean, default=False) groups = relationship('ModulesPermissions', cascade='all, delete-orphan')
def original_hybrid_config(request): config = AttributeConfiguration(name='hybrid', supports_csv=True, csv_sequence=None, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None) return config
class Users(DeclarativeBase, ApiModule): """ Resource Users """ __tablename__ = 'users' __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='auth_name', supports_json=True), AttributeConfiguration(name='full_name', supports_json=True), AttributeConfiguration(name='auto_create', supports_json=True), AttributeConfiguration(name='groups', supports_json=(False, True)), ) name = Column(Unicode(256), nullable=False, unique=True) auth_name = Column(Unicode(256), unique=True) full_name = Column(Unicode(1024)) auto_create = Column(Boolean(), default=False) groups = relationship('UsersGroups', cascade='all, delete-orphan')
class Layers(DeclarativeBase, ApiModule): """ Resource Reference of Layers """ __tablename__ = 'layers' __serialization__ = get_serialization( AttributeConfiguration(name='name', supports_json=True), AttributeConfiguration(name='symbol', supports_json=True), AttributeConfiguration(name='properties', supports_json=True), AttributeConfiguration(name='all_properties', supports_json=(False, True)), AttributeConfiguration(name='geom_id', supports_json=(True, False)), ) name = Column(Unicode(256), nullable=False, unique=True) symbol = Column(Unicode()) properties = Column(JsonType()) all_properties = Column(JsonType()) geom_id = Column(Integer, ForeignKey('geoms.id'), nullable=False)
class UsersGroups(DeclarativeBase, ApiModule): """ Resource Users Groups """ __tablename__ = 'users_groups' __serialization__ = get_serialization( AttributeConfiguration(name='auto_create', supports_json=True), AttributeConfiguration(name='user_id', supports_json=(True, False)), AttributeConfiguration(name='group_id', supports_json=(True, False)), AttributeConfiguration(name='user', supports_json=(False, True)), AttributeConfiguration(name='group', supports_json=(False, True)), ) __table_args__ = (UniqueConstraint('user_id', 'group_id', name='_users_groups_uc'), ) auto_create = Column(Boolean(), default=False) user_id = Column(Integer, ForeignKey('users.id'), nullable=False) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) user = column_property(select([(Users.name)], user_id == Users.id)) group = column_property(select([(Groups.name)], group_id == Groups.id))
class Pet(db.Model): __tablename__ = 'pet' __serialization__ = [ AttributeConfiguration( name='store', supports_dict=True, ), ] id = db.Column( db.Integer, db.Sequence('pet_id_seq'), primary_key=True, supports_dict=True, ) name = db.Column( db.String, index=True, unique=True, nullable=False, supports_dict=True, ) store_id = db.Column( db.Integer, db.ForeignKey('store.id'), nullable=False, supports_dict=False, ) status = db.Column( db.String, default='pending', server_default='pending', supports_dict=True, ) def __repr__(self): return "<Pet(id='{0:d}' name='{1:s}' status='{2:s}' store='{3:s}')>".format( self.id, self.name, self.status, self.store.name, )
class ModulesPermissions(DeclarativeBase): __tablename__ = 'modules_permissions' __serialization__ = [ AttributeConfiguration(name='id', supports_json=(False, True)), AttributeConfiguration(name='permission_level', supports_json=True), AttributeConfiguration(name='group_id', supports_json=False), AttributeConfiguration(name='module_id', supports_json=False), AttributeConfiguration(name='group', supports_json=(False, True)), AttributeConfiguration(name='module', supports_json=(False, True)), ] id = Column(Integer, primary_key=True) permission_level = Column(Integer, nullable=False) group_id = Column(Integer, ForeignKey('groups.id'), nullable=False) module_id = Column(Integer, ForeignKey('modules.id'), nullable=False) group = column_property(select([(Groups.name)], group_id == Groups.id)) module = column_property(select([(Modules.name)], module_id == Modules.id))
def new_config_set(request): config_set = [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='addresses', supports_json=True, supports_yaml=(True, True), supports_dict=(True, False)), AttributeConfiguration(name='hybrid', supports_csv=True, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='password', supports_csv=False, supports_json=False, supports_yaml=False, supports_dict=False) ] dict_representation = { 'id': { 'supports_csv': (True, True), 'csv_sequence': 1, 'supports_json': (True, True), 'supports_yaml': (True, True), 'supports_dict': (True, True), 'on_serialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None }, 'on_deserialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None } }, 'name': { 'supports_csv': (True, True), 'csv_sequence': 2, 'supports_json': (True, True), 'supports_yaml': (True, True), 'supports_dict': (True, True), 'on_serialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None }, 'on_deserialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None } }, 'addresses': { 'supports_csv': (False, False), 'csv_sequence': None, 'supports_json': (True, True), 'supports_yaml': (True, True), 'supports_dict': (True, False), 'on_serialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None }, 'on_deserialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None } }, 'hybrid': { 'supports_csv': (True, True), 'csv_sequence': None, 'supports_json': (True, True), 'supports_yaml': (True, True), 'supports_dict': (True, True), 'on_serialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None }, 'on_deserialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None } }, 'password': { 'supports_csv': (False, False), 'csv_sequence': None, 'supports_json': (False, False), 'supports_yaml': (False, False), 'supports_dict': (False, False), 'on_serialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None }, 'on_deserialize': { 'csv': None, 'json': None, 'yaml': None, 'dict': None } } } return config_set, dict_representation
def original_config_set(request): """Original serialization configuration applied to the complex model class. Dictionary key ``True`` indicates that it applies to ``complex_meta``, while ``False`` indicates that it applies to just ``complex`` (non-meta). """ config_set = { True: [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='addresses', supports_json=True, supports_yaml=(True, True), supports_dict=(True, False)), AttributeConfiguration(name='hybrid', supports_csv=True, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='password', supports_csv=(True, False), csv_sequence=3, supports_json=(True, False), supports_yaml=(True, False), supports_dict=(True, False)) ], False: [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='password', supports_csv=(True, False), csv_sequence=3, supports_json=(True, False), supports_yaml=(True, False), supports_dict=(True, False)), AttributeConfiguration(name='addresses', supports_json=True, supports_yaml=(True, True), supports_dict=(True, False)) ] } return config_set
class User_Complex_PostgreSQL(BaseModel): """Mocked class with a single primary key.""" __tablename__ = 'users_complex_postgresql' __serialization__ = [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=return_serialized, on_deserialize=return_deserialized), AttributeConfiguration(name='addresses', supports_json=True, supports_yaml=(True, True), supports_dict=(True, False)), AttributeConfiguration(name='hybrid', supports_csv=True, supports_json=True, supports_yaml=True, supports_dict=True, display_name='hybrid_value'), AttributeConfiguration(name='password', supports_csv=(True, False), csv_sequence=3, supports_json=(True, False), supports_yaml=(True, False), supports_dict=(True, False)), AttributeConfiguration(name='time_delta', supports_csv=True, supports_json=False, supports_yaml=False, supports_dict=False) ] id = Column('id', Integer, primary_key=True) name = Column('username', String(50)) addresses = relationship('Address_Complex_PostgreSQL', backref='user') password = Column('password', String(50)) hidden = Column('hidden_column', String(50)) smallint_column = Column('smallint_column', sqlite.SMALLINT, supports_csv=True, csv_sequence=4) _hybrid = 1 time_delta = Column('time_delta', Interval) @hybrid_property def hybrid(self): return self._hybrid @hybrid.setter def hybrid(self, value): self._hybrid = value @hybrid_property def hybrid_differentiated(self): return self._hybrid @hybrid_differentiated.setter def hybrid_differentiated(self, value): self._hybrid = value keywords_basic = association_proxy('keywords_basic', 'keyword')
class User_Complex_Meta(BaseModel): """Mocked class with a single primary key.""" __tablename__ = 'users_complex_meta' __serialization__ = [ AttributeConfiguration(name='id', supports_csv=True, csv_sequence=1, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='name', supports_csv=True, csv_sequence=2, supports_json=True, supports_yaml=True, supports_dict=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='addresses', supports_json=True, supports_yaml=(True, True), supports_dict=(True, False)), AttributeConfiguration(name='hybrid', supports_csv=True, supports_json=True, supports_yaml=True, supports_dict=True), AttributeConfiguration(name='password', supports_csv=(True, False), csv_sequence=3, supports_json=(True, False), supports_yaml=(True, False), supports_dict=(True, False)) ] id = Column('id', Integer, primary_key=True) name = Column('username', String(50)) addresses = relationship('Address_Complex_Meta', backref='user') password = Column('password', String(50)) hidden = Column('hidden_column', String(50)) _hybrid = 1 @hybrid_property def hybrid(self): return self._hybrid @hybrid.setter def hybrid(self, value): self._hybrid = value @hybrid_property def hybrid_differentiated(self): return self._hybrid @hybrid_differentiated.setter def hybrid_differentiated(self, value): self._hybrid = value keywords_basic = association_proxy('keywords_basic', 'keyword')
class User(UserMixin, db.Model): __tablename__ = 'user' __serialization__ = [ AttributeConfiguration(name='id', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='username', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='email', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='about_me', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='karma', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='timestamp', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='submitted', supports_json=True, on_serialize=None, on_deserialize=None) ] id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64)) email = db.Column(db.String(120), index=True, unique=True) password_hash = db.Column(db.String(128)) posts = db.relationship("Post", backref="author", lazy="dynamic") comments = db.relationship("Comment", backref="author", lazy="dynamic") about_me = db.Column(db.String(180)) karma = db.Column(db.Integer, default=1) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) refresh_tokens = db.relationship('RefreshToken', backref='user', lazy="dynamic") company_id = db.Column(db.Integer, db.ForeignKey("company.id")) admin = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) subscribe_newsletter = db.Column(db.Boolean, default=True) is_super_admin = db.relationship('Administrator', backref='user', lazy="dynamic") nb_conn_attempt = db.Column(db.Integer, default=0) conn_blocked_timestamp = db.Column('conn_blocked_timestamp', db.DateTime, default=datetime.utcnow) def get_reset_password_token(self, expires_in=600): return jwt.encode( { "reset_password": self.id, "exp": time() + expires_in }, current_app.config["SECRET_KEY"], algorithm="HS256", ).decode("utf-8") def get_mail_verification_token(self, expires_in=600): return jwt.encode( { "user_id": self.id, "exp": time() + expires_in }, current_app.config["SECRET_KEY"], algorithm="HS256", ).decode("utf-8") def get_invitation_token(self, expires_in=60 * 60 * 48): return jwt.encode( { "company_id": self.company_id, "exp": time() + expires_in }, current_app.config["SECRET_KEY"], algorithm="HS256", ).decode("utf-8") @staticmethod def verify_reset_password_token(token): try: id = jwt.decode(token, current_app.config["SECRET_KEY"], algorithms=["HS256"])["reset_password"] except Exception: return return User.query.get(id) @staticmethod def verify_mail_token(token): try: id = jwt.decode(token, current_app.config["SECRET_KEY"], algorithms=["HS256"])["user_id"] except Exception: return return User.query.get(id) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) def can_post(self): if (len( Post.query.filter(Post.timestamp >= datetime.strftime( datetime.now(), "%Y-%m-%d")).filter_by(author=self, deleted=0).all()) > current_app.config["USER_POSTS_PER_DAY"]): return False else: return True def can_comment(self): if (len( Comment.query.filter(Comment.timestamp >= datetime.strftime( datetime.now(), "%Y-%m-%d")).filter_by(author=self).all()) > current_app.config["USER_COMMENTS_PER_DAY"]): return False else: return True def __repr__(self): return f"<User {self.username}>"
class Comment(db.Model): __tablename__ = 'comment' __serialization__ = [ AttributeConfiguration(name='id', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='text', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='timestamp', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='path', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='parent_id', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='kids', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='post_id', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='thread_timestamp', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='score', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='type_comment', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='username', supports_json=True, on_serialize=None, on_deserialize=None), AttributeConfiguration(name='thread_score', supports_json=True, on_serialize=None, on_deserialize=None), ] _N = 6 id = db.Column(db.Integer, primary_key=True) text = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey("user.id")) timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) path = db.Column(db.Text, index=True) parent_id = db.Column(db.Integer, db.ForeignKey("comment.id")) replies = db.relationship( "Comment", backref=db.backref("parent", remote_side=[id]), lazy="dynamic", ) post_id = db.Column(db.Integer, db.ForeignKey("post.id")) thread_timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow) score = db.Column(db.Integer, default=0) thread_score = db.Column(db.Integer, default=0) company_id = db.Column(db.Integer, default=0) def update_votes(self): self.score += 1 if self.parent_id is None: self.thread_score = self.score for child_comment in Comment.query.filter( Comment.path.like(self.path + "%")): child_comment.thread_score = self.thread_score db.session.commit() def save(self): db.session.add(self) db.session.commit() prefix = self.parent.path + "." if self.parent else "" self.path = prefix + "{:0{}d}".format(self.id, self._N) db.session.commit() def level(self): return len(self.path) // self._N - 1 @hybrid_property def kids(self): comment_ids = Comment.query.filter_by(parent_id=self.id).all() return [i.id for i in comment_ids] @hybrid_property def type_comment(self): return 'comment' @hybrid_property def username(self): return User.query.filter_by(id=self.user_id).first().username def __repr__(self): return ( f"<Comment: {self.text} Post: {self.post_id} User: {self.user_id}>" )