class Course(Base): "Represents a course description" def __init__(self, page_inst, course_div, session): """ Parses html course info into a this Course object. Args: page_inst: a Page object on which this course is found. course_div: a lxml.html._Element representing a div containing course details. session: a neo4j.GraphDatabase.driver.session object. """ div_id = self.course_div.xpath('./a[2]/@name')[0] self.link = page_inst.url + '#' + div_id self.start_year = page_inst.start_year self.end_year = page_inst.end_year # inheret the department code. Note this will result in multiple # listings of crosslisted courses in Bates.db. self.dept_code = page_inst.dept_code self.name = course_div.xpath('./h4[@class="crsname"]/text()')[0] self.code = self.name.split('.')[0] self.desc = course_div.xpath('./span[@class="CourseDesc"]/text()') self.desc = ' '.join(self.desc) self.concentrations = course_div.xpath('./span/div/ul/li/a/text()') self.requirements_flag = False self.requirements = [] def parse_reqirements(self): """ Populates self.requirements """ if 'Prerequisite(s):' in self.desc: self.requirements_flag = True reqs = self.desc.split('Prerequisite(s):')[1].split('.')[0].strip() # if '100-level' in reqs: # pass # if 'one' in reqs.split(): # pass current_dept = self.dept_code translator = str.maketrans({k: ' ' for k in string.punctuation}) reqs = reqs.translate(translator) reqs = (i for i in reqs.split()) # results = [] # TODO: figure out how to parse nested 'and' and 'or's for chunk in reqs: # if chunk.lower() in ['or', 'and']: # results.append(chunk) if chunk.isupper() and chunk.isalpha() and len(chunk) > 2: current_dept = chunk if chunk[0].isnumeric() and len(chunk) >= 3: Requirement(self, current_dept + ' ' + chunk) link = Column(String()) name = Column(String()) code = Column(String(10), primary_key=True) desc = Column(String()) requirements_flag = Column(Boolean()) start_year = Column(SmallInteger()) end_year = Column(SmallInteger())
class HistoryDate(orm.base.Base): __tablename__ = "history_date" id = Column(Integer, primary_key=True) update_time = Column(DateTime) create_time = Column(DateTime) code = Column(String(100)) open = Column(Float(6)) high = Column(Float(6)) low = Column(Float(6)) close = Column(Float(6)) preclose = Column(Float(6)) amount = Column(Float(6)) turn = Column(Float(6)) pctChg = Column(Float(6)) peTTM = Column(Float(6)) psTTM = Column(Float(6)) pcfNcfTTM = Column(Float(6)) pbMRQ = Column(Float(6)) volume = Column(Integer()) adjustflag = Column(SmallInteger()) tradestatus = Column(SmallInteger()) isST = Column(SmallInteger()) def __init__(self): pass
class OutgoingAMQP(Base): """ An outgoing AMQP connection. """ __tablename__ = 'out_amqp' __table_args__ = (UniqueConstraint('name', 'def_id'), {}) id = Column(Integer, Sequence('out_amqp_seq'), primary_key=True) name = Column(String(200), nullable=False) is_active = Column(Boolean(), nullable=False) delivery_mode = Column(SmallInteger(), nullable=False) priority = Column(SmallInteger(), server_default=str(AMQP_DEFAULT_PRIORITY), nullable=False) content_type = Column(String(200), nullable=True) content_encoding = Column(String(200), nullable=True) expiration = Column(String(20), nullable=True) user_id = Column(String(200), nullable=True) app_id = Column(String(200), nullable=True) def_id = Column(Integer, ForeignKey('conn_def_amqp.id', ondelete='CASCADE'), nullable=False) def_ = relationship(ConnDefAMQP, backref=backref('out_conns_amqp', cascade='all, delete, delete-orphan')) def __init__(self, id=None, name=None, is_active=None, delivery_mode=None, priority=None, content_type=None, content_encoding=None, expiration=None, user_id=None, app_id=None, def_id=None, delivery_mode_text=None, def_name=None): self.id = id self.name = name self.is_active = is_active self.delivery_mode = delivery_mode self.priority = priority self.content_type = content_type self.content_encoding = content_encoding self.expiration = expiration self.user_id = user_id self.app_id = app_id self.def_id = def_id self.delivery_mode_text = delivery_mode_text # Not used by the DB self.def_name = def_name # Not used by the DB
class OfflineAccountRecharge(Base, BaseModel): # 线下充值账号 __tablename__ = 'dj_offline_account_recharge' id = Column(Integer(), primary_key=True, autoincrement=True) name = Column(String(64), default='', nullable=False) accountId = Column(String(64), default='', nullable=False) bank = Column(String(64), default='', nullable=True) # 银行卡账号有 bankInfo = Column(String(255), default="", nullable=True) status = Column(SmallInteger(), default=0, nullable=False) # 0 上线,1 暂停使用 kind = Column(SmallInteger(), default=0, nullable=False) # 0支付宝 1银行卡 2微信 __table_args__ = {'mysql_charset': 'utf8mb4'}
class ShabaBetBill(Base): #沙巴日志模型类 __tablename__ = 'dj_shababetbill' transId = Column(BigInteger(), default=0, primary_key=True) sportType = Column(Integer(), default=0) leagueId = Column(Integer(), default=0) homeId = Column(Integer(), default=0) awayId = Column(Integer(), default=0) betTeam = Column(String(45), default='') oddsType = Column(SmallInteger(), default=0) odds = Column(Float(), default=0) stake = Column(Float(), default=0) betType = Column(SmallInteger(), default=0) ticketStatus = Column(String(10), default='') winLostAmount = Column(Float(), default='') currency = Column(SmallInteger(), default=0) vendorMemberId = Column(String(50), default='') transActionTime = Column(Integer(), default=0) agentId = Column(String(32), default='') winLostDateTime = Column(Integer(), default=0) operatorId = Column(String(50), default='') baStatus = Column(String(5), default='') betTag = Column(String(500), default='') __table_args__ = {'mysql_charset': 'utf8mb4'} @staticmethod def getSqlObj(dictBill: dict): tbl = Base.metadata.tables["dj_shababetbill"] from lib.timehelp.timeHelp import strToTimestamp objSql = tbl.insert().values( vendorMemberId=dictBill["vendorMember_id"], transId=dictBill['trans_id'], sportType=dictBill['sport_type'], leagueId=dictBill["league_id"], betTag=dictBill["bet_tag"], homeId=dictBill["home_id"], awayId=dictBill["away_id"], betTeam=dictBill['bet_team'], oddsType=dictBill["odds_type"], odds=dictBill["odds"], stake=dictBill["stake"], betType=dictBill["bet_type"], transActionTime=strToTimestamp(dictBill["transaction_time"]), winLostDateTime=strToTimestamp(dictBill['winlost_datetime']), ticketStatus=dictBill["ticket_status"], winLostAmount=dictBill["winlost_amount"], currency=dictBill['currency'], agentId=dictBill['agentId'], operatorId=dictBill['operator_id'], baStatus=dictBill['ba_status'], ) return objSql
class Reqirement(Base): requirer = Column(String()) required = Column(String()) start_year = Column(SmallInteger()) end_year = Column(SmallInteger()) def __init__(self, course_inst, required_course_code): self.requirer = course_inst.code self.required = required_course_code self.start_year = course_inst.start_year self.end_year = course_inst.end_year
class CompareTypeSpecificityTest(TestBase): @testing.fixture def impl_fixture(self): from alembic.ddl import impl from sqlalchemy.engine import default return impl.DefaultImpl(default.DefaultDialect(), None, False, True, None, {}) def test_typedec_to_nonstandard(self, impl_fixture): class PasswordType(TypeDecorator): impl = VARBINARY def copy(self, **kw): return PasswordType(self.impl.length) def load_dialect_impl(self, dialect): if dialect.name == "default": impl = sqlite.NUMERIC(self.length) else: impl = VARBINARY(self.length) return dialect.type_descriptor(impl) impl_fixture.compare_type(Column("x", sqlite.NUMERIC(50)), Column("x", PasswordType(50))) @testing.combinations( (VARCHAR(30), String(30), False), (VARCHAR(30), String(40), True), (VARCHAR(30), Integer(), True), (DECIMAL(10, 5), Numeric(10, 5), False), (DECIMAL(10, 5), Numeric(12, 5), True), (DECIMAL(10, 5), DateTime(), True), (Numeric(), Numeric(scale=5), False), (INTEGER(), Integer(), False), (BIGINT(), Integer(), True), (BIGINT(), BigInteger(), False), (BIGINT(), SmallInteger(), True), (INTEGER(), SmallInteger(), True), (Integer(), String(), True), (DateTime(), DateTime(timezone=False), False), (DateTime(), DateTime(timezone=True), True), (DateTime(timezone=False), DateTime(timezone=True), True), id_="ssa", argnames="compare_from,compare_to,expected", ) def test_compare_type(self, impl_fixture, compare_from, compare_to, expected): is_( impl_fixture.compare_type(Column("x", compare_from), Column("x", compare_to)), expected, )
class Ban(sqlalchemy_ext.Model): __bind_key__ = 'game' __tablename__ = 'SS13_ban' id = Column('id', Integer(), primary_key=True) bantime = Column('bantime', DateTime()) server_name = Column('server_name', String(32)) server_ip = Column('server_ip', Integer()) server_port = Column('server_port', SmallInteger()) round_id = Column('round_id', Integer()) role = Column('role', String(32)) expiration_time = Column('expiration_time', DateTime()) applies_to_admins = Column('applies_to_admins', SmallInteger()) reason = Column('reason', String(2048)) ckey = Column('ckey', String(32)) ip = Column('ip', Integer()) computerid = Column('computerid', String(32)) a_ckey = Column('a_ckey', String(32)) a_ip = Column('a_ip', Integer()) a_computerid = Column('a_computerid', Integer()) who = Column('who', String(2048)) adminwho = Column('adminwho', String(2048)) edits = Column('edits', Text()) unbanned_datetime = Column('unbanned_datetime', DateTime()) unbanned_ckey = Column('unbanned_ckey', String(32)) unbanned_ip = Column('unbanned_ip', Integer()) unbanned_computerid = Column('unbanned_computerid', String(32)) unbanned_round_id = Column('unbanned_round_id', Integer()) global_ban = Column('global_ban', SmallInteger()) hidden = Column('hidden', SmallInteger()) @classmethod def from_id(cls, id): try: return db_session.query(cls).filter(cls.id == id).one() except NoResultFound: return None @classmethod def grouped_from_id( cls, id ): # For getting job bans with the roles grouped as a seperate field, yep it's a headache try: single_from_id = cls.from_id(id) return db_session.query( *([c for c in cls.__table__.c] + [func.group_concat(Ban.role).label("roles")])).group_by( cls.bantime, cls.ckey).filter( cls.ckey == single_from_id.ckey, cls.bantime == single_from_id.bantime).one() except NoResultFound: return None
class LogConversion(db.Model): __bind_key__ = 'matomo' id = db.Column(BigInteger(), primary_key=True) idvisit = db.Column(BigInteger()) idsite = db.Column(Integer()) idvisitor = db.Column(Binary()) server_time = db.Column(DateTime(), primary_key=True) idaction_url = db.Column(Integer()) idlink_va = db.Column(BigInteger()) idgoal = db.Column(Integer()) buster = db.Column(Integer()) idorder = db.Column(String(100)) items = db.Column(SmallInteger()) url = db.Column(Text()) visitor_days_since_first = db.Column(SmallInteger()) visitor_days_since_order = db.Column(SmallInteger()) visitor_returning = db.Column(Integer()) visitor_count_visits = db.Column(Integer()) referer_keyword = db.Column(String(255)) referer_name = db.Column(String(70)) referer_type = db.Column(Integer()) config_device_brand = db.Column(String(100)) config_device_model = db.Column(String(100)) config_device_type = db.Column(Integer()) location_city = db.Column(String(255)) location_country = db.Column(String(3)) location_latitude = db.Column(Decimal(9, 6)) location_longitude = db.Column(Decimal(9, 6)) location_region = db.Column(String(2)) revenue = db.Column(Float()) revenue_discount = db.Column(Float()) revenue_shipping = db.Column(Float()) revenue_subtotal = db.Column(Float()) revenue_tax = db.Column(Float()) custom_var_k1 = db.Column(String(200)) custom_var_v1 = db.Column(String(200)) custom_var_k2 = db.Column(String(200)) custom_var_v2 = db.Column(String(200)) custom_var_k3 = db.Column(String(200)) custom_var_v3 = db.Column(String(200)) custom_var_k4 = db.Column(String(200)) custom_var_v4 = db.Column(String(200)) custom_var_k5 = db.Column(String(200)) custom_var_v5 = db.Column(String(200)) example_conversion_dimension = db.Column(Integer()) class Meta: managed = False db_table = 'log_conversion' unique_together = ( ('idvisit', 'idgoal', 'buster'), ('idsite', 'idorder'), ) verbose_name_plural = db_table
class Death(sqlalchemy_ext.Model): __bind_key__ = 'game' __tablename__ = 'SS13_death' id = Column('id', Integer(), primary_key=True) tod = Column('tod', DateTime()) server_ip = Column('server_ip', Integer()) server_port = Column('server_port', SmallInteger()) round_id = Column('round_id', Integer()) byondkey = Column('byondkey', String(32)) suicide = Column('suicide', SmallInteger())
class RepairData(Base): # 平台维护记录 from lib.timehelp.timeHelp import getNow __tablename__ = 'dj_repair' repairId = Column(String(128), primary_key=True) create_time = Column(Integer(), default=getNow()) start_time = Column(Integer(), default=0, nullable=False) end_time = Column(Integer(), default=0, nullable=False) repairFlag = Column(SmallInteger(), default=0, nullable=False) accountId = Column(String(64), default='', nullable=False) platform = Column(SmallInteger(), default=0, nullable=False) __table_args__ = {'mysql_charset': 'utf8mb4'}
def create_dl_projects(database): """ dl_projects: | uid | mediumint(8) unsigned | NO | PRI | NULL | auto_increment | | project_uid | mediumint(8) unsigned | YES | | NULL | | | framestore_uid | mediumint(8) unsigned | YES | | NULL | | | project_class | enum('master','user','template','split') | YES | | user | | | user_id | varchar(48) | YES | | NULL | | | name | varchar(255) | YES | | NULL | | | cfg_file | varchar(255) | YES | | NULL | | | FrameWidth | smallint(4) unsigned | YES | | NULL | | | FrameHeight | smallint(4) unsigned | YES | | NULL | | | FrameDepth | enum('8-bit','10-bit','12-bit','12-bit u') | YES | | 12-bit | | | AspectRatio | decimal(7,4) | YES | | NULL | | | ProxyEnable | enum('true','false') | YES | | true | | | ProxyWidthHint | decimal(6,2) | YES | | NULL | | | ProxyDepthMode | enum('8-bit','SAME_AS_HIRES') | YES | | 8-bit | | | ProxyMinFrameSize | smallint(4) unsigned | YES | | NULL | | | ProxyAbove8bits | enum('true','false') | YES | | false | | | ProxyQuality | varchar(48) | YES | | NULL | | | FieldDominance | enum('FIELD_1','FIELD_2','PROGRESSIVE') | YES | | PROGRESSIVE | | | VisualDepth | enum('8-bit','12-bit','unknown') | YES | | 12-bit | | | SetupDir | varchar(255) | YES | | NULL | | | Description | text | YES | | NULL | | | status | enum('active','inactive') | YES | | active | | """ engine = sqlalchemy.create_engine('mysql://pyre@localhost/%s' % database) metadata = MetaData() projects_table = Table( 'dl_projects', metadata, Column('uid', Integer(unsigned=True), primary_key=True, autoincrement=True), Column('project_uid', Integer(unsigned=True)), Column('framestore_uid', Integer(unsigned=True)), Column('project_class', String(24)), Column('user_id', String(48)), Column('name', String(255)), Column('cfg_file', String(255)), Column('FrameWidth', SmallInteger(unsigned=True)), Column('FrameHeight', SmallInteger(unsigned=True)), Column('FrameDepth', String(12)), Column('AspectRatio', Float(precision=4, asdecimal=True)), Column('ProxyEnable', String(12)), Column('ProxyWidthHint', Float(precision=2, asdecimal=True)), Column('ProxyDepthMode', String(24)), Column('ProxyMinFrameSize', SmallInteger(unsigned=True)), Column('ProxyAbove8bits', String(12)), Column('ProxyQuality', String(48)), Column('FieldDominance', String(48)), Column('VisualDepth', String(24)), Column('SetupDir', String(255)), Column('Description', Text), Column('status', String(24))) metadata.create_all(engine)
def upgrade(migrate_engine): meta.bind = migrate_engine domains_table = Table('domains', meta, autoload=True) recordsets_table = Table('recordsets', meta, autoload=True) records_table = Table('records', meta, autoload=True) domains_shard_col = Column('shard', SmallInteger(), nullable=True) domains_shard_col.create(domains_table) recordset_domain_shard_col = Column('domain_shard', SmallInteger(), nullable=True) recordset_domain_shard_col.create(recordsets_table) records_domain_shard_col = Column('domain_shard', SmallInteger(), nullable=True) records_domain_shard_col.create(records_table) def _set_default(): _add_shards(migrate_engine, domains_table, domains_shard_col, domains_table.c.id) _add_shards(migrate_engine, recordsets_table, recordset_domain_shard_col, recordsets_table.c.domain_id) _add_shards(migrate_engine, records_table, records_domain_shard_col, records_table.c.domain_id) def _set_nullable(): domains_table.c.shard.alter(nullable=False) recordsets_table.c.domain_shard.alter(nullable=False) records_table.c.domain_shard.alter(nullable=False) for i in range(0, 5): try: _set_default() _set_nullable() except Exception as e: # The population default & enforcement of nullable=False failed, # try again msg = i18n._LW("Updating migration for sharding failed, retrying.") LOG.warning(msg) if i >= 4: # Raise if we've reached max attempts causing migration to # fail raise e else: continue # It was successful, no exception so we break the loop. break
class Bbs(Base): # 表名 __tablename__ = 'bbs_bbs' # 表结构 bbsid = Column(SmallInteger(), primary_key=True, autoincrement=True) boardid = Column(SmallInteger()) parentid = Column(SmallInteger()) child = Column(SmallInteger()) username = Column(String(100)) expression = Column(String(100)) bbstitle = Column(String(200)) bbscontent = Column(Text()) dateandtime = Column(DateTime()) bbsclick = Column(BigInteger()) bbshot = Column(String(10))
class UserInfo(Base): #用户信息 __tablename__ = 'dj_account' accountId = Column(String(64), primary_key=True) #nick=Column(String(255),default="", nullable=True) userType = Column(SmallInteger(), default=0, nullable=False) # 1:普通用户 2:代理用户 phone = Column(String(255), default="", nullable=True) coin = Column(BigInteger(), default=0) guessCoin = Column(BigInteger(), default=0) pingboCoin = Column(BigInteger(), default=0) shabaCoin = Column(BigInteger(), default=0) notDrawingCoin = Column(BigInteger(), default=0) passwordMd5 = Column(String(255), default="", nullable=False) # secret=Column(String(255), default="", nullable=False) regTime = Column(Integer(), default=0, nullable=False) email = Column(String(255), default="", nullable=True) loginTime = Column(Integer(), default=0, nullable=True) loginIp = Column(String(255), default="", nullable=True) loginAddress = Column(String(255), default="", nullable=True) #登录地址 loginDeviceUdid = Column(String(255), default="", nullable=True) loginDeviceModel = Column(String(255), default="", nullable=True) #登录设备模型 loginDeviceName = Column(String(255), default="", nullable=True) #登录设备名称 logoutTime = Column(Integer(), default=0, nullable=True) lastBetTime = Column(Integer(), default=0, nullable=True) platform = Column(Integer(), default=0, nullable=True) # invalid=Column(Integer(), default=0,nullable=False) # lastReceviveMsgTime=Column(Integer(), default=0, nullable=False) firstPayCoin = Column(Integer(), default=0, nullable=True) firstPayTime = Column(Integer(), default=0, nullable=True) headAddress = Column(String(255), default="", nullable=True) realName = Column(String(255), default="", nullable=True) sex = Column(String(32), default="", nullable=True) born = Column(String(255), default="", nullable=True) address = Column(String(512), default="", nullable=True) bankcard = Column(String(1024), default="", nullable=True) tradePasswordMd5 = Column(String(255), default="", nullable=True) status = Column(SmallInteger(), default=0, nullable=True) #0 正常,1冻结 lockStartTime = Column(Integer(), default=0, nullable=True) #封停开始时间 lockEndTime = Column(Integer(), default=0, nullable=True) #封停结束 lockReason = Column(String(512), default="", nullable=True) #封停原因 level = Column(Integer(), default=0, nullable=False) #等级 levelValidWater = Column(Integer(), default=0, nullable=True) # 等级下的有效流水值 agentId = Column(String(64), default="", nullable=False, index=True) # 代理id lastPBCRefreshTime = Column(Integer(), default=0, nullable=True) #上一次平博钱包刷新时间 __table_args__ = {'mysql_charset': 'utf8mb4'}
class ArticleModel(db.Model): __tablename__ = "articles" id = Column(SmallInteger().with_variant(Integer, "sqlite"), primary_key=True) post_id = Column( BigInteger().with_variant(Integer, "sqlite"), ForeignKey(PostModel.id), nullable=False, ) # TODO : 성능상 글자 수 변경될 수 있음. body = Column(String(length=2000), nullable=False) created_at = Column(DateTime, default=get_server_timestamp()) updated_at = Column(DateTime, default=get_server_timestamp()) post = relationship("PostModel", backref=backref("article", uselist=False)) def to_entity(self) -> ArticleEntity: return ArticleEntity( id=self.id, post_id=self.post_id, body=self.body, created_at=self.created_at, updated_at=self.updated_at, )
class DanToc(CommonModel): __tablename__ = 'dantoc' id = db.Column(String, primary_key=True, default=default_uuid) ma = db.Column(String(255), index=True) ten = db.Column(String(255)) tenkhongdau = db.Column(String) active = db.Column(SmallInteger(), default=0)
class NPRTable(Base): __tablename__ = settings.NPR_DB_TABLE_NAME VERW_RECHT_ID = Column(Numeric(10, 0), nullable=False, primary_key=True) LAND_C_V_RECHT = Column(String(3)) VERK_P_V_RECHT = Column(Numeric(10, 0)) VERK_PUNT_OMS = Column(Unicode(80)) B_TYD_V_RECHT = Column(String(14)) E_TYD_V_RECHT = Column(String(14)) E_TYD_R_AANP = Column(String(14)) BEDRAG_V_RECHT = Column(Numeric(10, 2)) BTW_V_RECHT = Column(Numeric(10, 2)) BEDR_V_RECHT_B = Column(Numeric(10, 2)) BTW_V_RECHT_BER = Column(Numeric(10, 2)) BEDR_V_RECHT_H = Column(Numeric(10, 2)) BTW_V_RECHT_HER = Column(Numeric(10, 2)) TYD_HERBEREK = Column(String(14)) RECHTV_V_RECHT = Column(String(10)) RECHTV_INT_OMS = Column(Unicode(80)) GEB_BEH_V_RECHT = Column(SmallInteger()) GEBIEDS_BEH_OMS = Column(Unicode(80)) GEB_C_V_RECHT = Column(String(10)) GEBIED_OMS = Column(Unicode(80)) REG_TYD_V_RECHT = Column(String(14)) COORD_V_RECHT = Column(Unicode(30)) GEBR_DOEL_RECHT = Column(String(10)) GEBR_DOEL_OMS = Column(Unicode(80)) R_TYD_E_TYD_VR = Column(String(14)) VER_BATCH_ID = Column(Integer()) VER_BATCH_NAAM = Column(String(12), index=True) KENM_RECHTV_INT = Column(Unicode(40))
class OrderLine(Base): __tablename__ = 'order_lines' id = Column(Integer(), primary_key=True) order_id = Column(Integer(), ForeignKey('orders.id')) item_id = Column(Integer(), ForeignKey('items.id')) quantity = Column(SmallInteger()) item = relationship("Item")
class User(CommonModel): __tablename__ = 'user' id = db.Column(String, primary_key=True, default=default_uuid) name = db.Column(String()) unsigned_name = db.Column(String()) email = db.Column(String(255)) phone = db.Column(String()) password = db.Column(String(255)) accountName = db.Column(String(255)) salt = db.Column(String()) active = db.Column(SmallInteger(), default=0) #0- chua active, 1- active # confirmed_at = db.Column(DateTime()) # type_confirm = db.Column(SmallInteger()) #0 - email, 1- sms roles = relationship("Role", secondary=roles_users) organization_id = db.Column(String, ForeignKey('organization.id', onupdate='CASCADE', ondelete='SET NULL'), nullable=True) Organization = relationship('Organization') # Methods def __repr__(self): """ Show user object info. """ return '<User: {}>'.format(self.id) def has_role(self, role): if isinstance(role, str): return role in (role.name for role in self.roles) else: return role in self.roles
class PostReportModel(db.Model): __tablename__ = "post_reports" id = Column(SmallInteger().with_variant(Integer, "sqlite"), primary_key=True) post_id = Column(BigInteger, ForeignKey(PostModel.id), nullable=False) report_user_id = Column(BigInteger, nullable=True) status = Column(String(20)) context = Column(String(100)) confirm_admin_id = Column(Integer) is_system_report = Column(Boolean) created_at = Column(DateTime, default=get_server_timestamp()) updated_at = Column(DateTime, default=get_server_timestamp()) post = relationship("PostModel", backref="post_report") def to_entity(self) -> PostReportEntity: return PostReportEntity( id=self.id, post_id=self.post_id, report_user_id=self.report_user_id, status=self.status, context=self.context, confirm_admin_id=self.confirm_admin_id, is_system_report=self.is_system_report, created_at=self.created_at, updated_at=self.updated_at, )
class User(CommonModel): __tablename__ = 'user' # Authentication Attributes. display_name = db.Column(String(255), nullable=False) unsigned_display_name = db.Column(String(255)) email = db.Column(String(255), index=True) phone = db.Column(String(255), index=True, unique=True, nullable=False) password = db.Column(String(255), nullable=False) salt = db.Column(String(255), nullable=False) is_active = db.Column(Boolean, default=True) id_identifier = db.Column(String(32), index=True) gender = db.Column(SmallInteger(), default=1) birthday = db.Column(BigInteger()) address = db.Column(String) status = db.Column(String) start_time = db.Column(BigInteger(), index=True) end_time = db.Column(BigInteger(), index=True) group_last_access_id = db.Column(UUID(as_uuid=True), ForeignKey("group.id")) group_last_access = db.relationship("Group", foreign_keys=[group_last_access_id]) def __repr__(self): """ Show user object info. """ return '<User: {}>'.format(self.id)
class Users(Base): __tablename__ = "users" user_id = Column(Integer, primary_key=True) name = Column(String(32), nullable=False, index=True) password = Column(String(64), nullable=False) gender = Column(SmallInteger()) email = Column(String(64)) phone = Column(String(32)) image = Column(String(128)) country = Column(String(32)) city = Column(String(32)) create_time = Column(TIMESTAMP(True), nullable=False, server_default=text('NOW()')) def base_info(self): data = {} for key, value in self.__dict__.items(): if not key.startswith("_") and key != "password": if isinstance(value, datetime): data[key] = TH.datetime_to_timestamp(value) else: data[key] = value return data def mini_info(self): return dict(user_id=self.user_id, name=self.name, gender=self.gender, country=self.country, city=self.city,)
class MonthLineSales(Base, BaseTable): __tablename__ = 'month_line_sales' month_id = Column(Integer(), primary_key=True) line_id = Column(Integer(), primary_key=True) platform_id = Column(SmallInteger(), nullable=False) line_desc = Column(String(70), nullable=False) sales = Column(Integer(), nullable=False)
class WihtDrawalBill(Base): #提款日志模型类 __tablename__ = 'dj_withdrawalbill' orderId = Column(String(128), primary_key=True) accountId = Column(String(32), default="") withdrawalTime = Column(Integer(), default=0) withdrawalIp = Column(String(32), default="") withdrawalCoin = Column(Integer(), default=0) cardNum = Column(String(20), default="") orderState = Column(Integer(), default=0) agentId = Column(String(32), default='') userType = Column(SmallInteger(), default=1) bankOrderId = Column(String(128), default='') #提款时银行流水号 __table_args__ = {'mysql_charset': 'utf8mb4'} @staticmethod def getSqlObj(dictBill: dict): tbl = Base.metadata.tables["dj_withdrawalbill"] objSql = tbl.insert().values( orderId=dictBill["orderId"], accountId=dictBill["accountId"], withdrawalTime=dictBill["withdrawalTime"], withdrawalIp=dictBill["withdrawalIp"], withdrawalCoin=dictBill["withdrawalCoin"], cardNum=dictBill["cardNum"], orderState=dictBill["orderState"], agentId=dictBill['agentId'], userType=dictBill['userType'], bankOrderId=dictBill['bankOrderId'], ) return objSql
class Post(Base): __tablename__ = 'posts' def __repr__(self): if len(self.title) > 36: return self.title[:36] + '…' return self.title id = Column(UUID(), nullable=False, primary_key=True, default=lambda: str(uuid.uuid4())) type = Column(SmallInteger(), nullable=False, default=0) title = Column(String(512), nullable=False) created_on = Column(DateTime(), nullable=False, default=datetime.utcnow) published_on = Column(DateTime(), nullable=True) # half a year after utcnow by default archived_on = Column( DateTime(), nullable=False, default=lambda: datetime.utcnow() + timedelta(hours=4380)) author = Column(UUID(), ForeignKey('employees.id', ondelete='NO ACTION'), nullable=False) approved_by = Column(UUID(), ForeignKey('employees.id', ondelete='NO ACTION'), nullable=True) status = Column(SmallInteger(), nullable=False, default=0) body = Column(String(81920), nullable=False) approver = relationship("Employee", back_populates="approved_posts", foreign_keys=approved_by) creator = relationship("Employee", back_populates="created_posts", foreign_keys=author) attachments = relationship("Attachment", back_populates='post_ref', primaryjoin="Post.id == Attachment.post") posts_title_idx = Index("posts_title_idx", title) posts_status_author_published_on_created_on_idx =\ Index("posts_status_author_published_on_created_on_idx", status, author, published_on, created_on)
class CategoryModel(db.Model): __tablename__ = "categories" id = Column(SmallInteger().with_variant(Integer, "sqlite"), primary_key=True) name = Column(String(40), nullable=False) created_at = Column(DateTime, default=get_server_timestamp()) updated_at = Column(DateTime, default=get_server_timestamp())
class TuyenDonVi(CommonModel): __tablename__ = 'tuyendonvi' id = db.Column(String, primary_key=True, default=default_uuid) ma = db.Column(String(255), index=True) ten = db.Column(String(255)) mota = db.Column(String(255)) tenkhongdau = db.Column(String) active = db.Column(SmallInteger(), default=0)
class UserMsg(Base): # 用户邮件信息 __tablename__ = 'dj_all_msg' id = Column(Integer(), primary_key=True) msgId = Column(String(64), nullable=False) msgTime = Column(Integer(), default=0, nullable=False) msgTitle = Column(String(255), default="", nullable=False) msgDetail = Column(Text(length=65536), default="", nullable=False) readFlag = Column(SmallInteger(), default=0, nullable=False) sendTo = Column(String(32), default=0, nullable=False) sendFrom = Column(String(32), default="", nullable=False) type = Column(SmallInteger(), default=0, nullable=False) # 0.用户消息,1.公告消息,2.新闻消息,3.代理消息 broadcast = Column(SmallInteger(), default=0, nullable=False) # 0.不轮播, 1.轮播 isdelete = Column(SmallInteger(), default=0, nullable=True) __table_args__ = {'mysql_charset': 'utf8mb4'}
def upgrade(): op.create_table('regions', Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(length=50))) op.create_table( 'cities', Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(length=50), default=ColumnDefault('')), Column('region_id', Integer(), ForeignKey('regions.id')), Column('image', String(length=300))) op.create_table('users', Column('id', Integer(), primary_key=True, nullable=False), Column('email', String(length=50))) op.create_table('venues', Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(length=100))) op.create_table('spaces', Column('id', Integer(), primary_key=True, nullable=False), Column('venue_id', Integer(), ForeignKey('venues.id')), Column('owner_id', Integer(), ForeignKey('users.id')), Column('name', String(length=100))) op.create_table('space_images', Column('id', Integer(), primary_key=True, nullable=False), Column('space_id', Integer(), ForeignKey('spaces.id')), Column('file', String(length=300)), Column('order', SmallInteger(), default=ColumnDefault(0))) op.create_table('features', Column('id', Integer(), primary_key=True, nullable=False), Column('name', String(length=40)), Column('description', Text())) op.create_table('space_features', Column('id', Integer(), primary_key=True, nullable=False), Column('space_id', Integer(), ForeignKey('spaces.id')), Column('feature_id', Integer(), ForeignKey('features.id')), Column('price', Numeric(), default=ColumnDefault(0))) op.create_table( 'orders', Column('id', Integer(), primary_key=True, nullable=False), Column('space_id', Integer(), ForeignKey('spaces.id')), Column('user_id', Integer(), ForeignKey('users.id')), Column('date_created', DateTime(), default=ColumnDefault(datetime.datetime.utcnow)), Column('status', String(length=8), default=ColumnDefault('NEW')), Column('activity_type', JSON()), Column('configuration', JSON()), Column('booking_date_start', JSON()), Column('booking_date_end', JSON())) op.create_table( 'order_items', Column('id', Integer(), primary_key=True, nullable=False), Column('order_id', Integer(), ForeignKey('orders.id')), Column('feature_id', Integer(), ForeignKey('space_features.id')), Column('price', Numeric(), default=ColumnDefault(0)), Column('date_created', DateTime(), default=ColumnDefault(datetime.datetime.utcnow)), Column('status', String(length=8), default=ColumnDefault('PAID')), Column('name', String(length=100), default=ColumnDefault('')))