class Project(db.Model): """项目方""" __tablename__ = 'project' __table_args__ = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.VARCHAR(32), comment="项目名称") callback_url = db.Column(db.VARCHAR(256), comment="回调地址, 示例http[s]://[user]:[passwd]@[ip|domain]:[port]") access_key = db.Column(db.VARCHAR(128), comment="回调签名 access_key") secret_key = db.Column(db.VARCHAR(128), comment="回调签名 secret_key") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) project_coin = orm.relationship('ProjectCoin', primaryjoin="Project.id==ProjectCoin.project_id", foreign_keys="Project.id", backref="Project") def __str__(self): return "{id}-{name}-{access_key}-{callback_url}".format( id=self.id, name=self.name, access_key=self.access_key, callback_url=self.callback_url)
class ProjectList(db.Model): __tablename__ = "project_list" id = db.Column(db.Integer, primary_key=True, autoincrement=True) project_name = db.Column(db.VARCHAR(50), nullable=False) join_time = db.Column(db.VARCHAR(50), nullable=False) status = db.Column(db.VARCHAR(50), nullable=False) version = db.Column(db.TEXT(), nullable=True)
class ApiAuth(db.Model): """ API 权限认证表 """ __tablename__ = 'api_auth' __table_args__ = ( # 确保一个项目方只能有一个 key UniqueConstraint( 'access_key', 'project_id', name='uk_access_key_project_id'), {'mysql_engine': "INNODB"} ) id = db.Column(db.Integer, primary_key=True, autoincrement=True) project_id = db.Column(db.Integer, nullable=False, comment="项目 ID") access_key = db.Column(db.VARCHAR(128), nullable=False, comment="key", unique=True) secret_key = db.Column(db.VARCHAR(128), comment="secret") ip = db.Column(db.VARCHAR(128), comment='受限IP地址') status = db.Column(db.SmallInteger, default=1, comment='是否启用 1:启用 0:禁用') create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) def __str__(self): return ' -'.join( [str(self.id), str(self.access_key), str(self.secret_key), str(self.create_time), str(self.update_time)])
class ProjectDeposit(db.Model): """项目方订单""" __tablename__ = 'project_deposit' __table_args = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) project_id = db.Column(db.Integer, nullable=False, comment="项目 ID") tx_id = db.Column(db.Integer, nullable=False, comment="币种ID", index=True) order_id = db.Column(db.VARCHAR(128), nullable=False, index=True, comment="充值订单号") address = db.Column(db.VARCHAR(128), nullable=False, comment="订单绑定地址") is_send = db.Column(db.SmallInteger, nullable=False, comment="是否推送 0:未推 1:已推 2:不用推") # tx_hash = db.Column(db.VARCHAR(128), nullable=False, comment="交易hash", unique=True) # amount = db.Column(db.VARCHAR(64), nullable=False, comment="交易金额") # sender = db.Column(db.VARCHAR(128), nullable=False, comment="发送人") # receiver = db.Column(db.VARCHAR(128), nullable=False, comment="接收人") # gas = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额, ETH使用") # gas_price = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额, ETH使用") # fee = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="真实手续费") # contract = db.Column(db.VARCHAR(128), comment="代币名称或地址") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) def __str__(self): return "{id}-{project_id}-{is_send}".format( id=self.id, project_id=self.project_id, is_send=self.is_send)
class RpcConfig(db.Model): """ RPC 节点配置表 """ __tablename__ = 'rpc_config' __table_args__ = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.Integer, primary_key=True, autoincrement=True) coin_id = db.Column(db.Integer, unique=False, default=0, comment="主链ID") name = db.Column(db.VARCHAR(32), comment="配置币种名称") driver = db.Column(db.VARCHAR(64), comment="驱动类型. 当前仅使用 ETHEREUM") host = db.Column(db.VARCHAR(256), comment="节点地址, 示例http[s]://[user]:[passwd]@[ip|domain]:[port]") status = db.Column(db.SmallInteger, default=1, comment="是否有效,0否 1是") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) def __str__(self): return "{id}-{coin_id}-{name}-{driver}-{host}".format( id=self.id, coin_id=self.coin_id, name=self.name, driver=self.driver, host=self.host) @staticmethod def get_rpc() -> RpcBase: """获取rpc, 返回RPC对象""" rpc_config = RpcConfig.query.filter_by(driver='Ethereum', status=1).first() if not rpc_config: return None driver = rpc_config.driver host = rpc_config.host rpc = DriverFactory(driver, host) return rpc
class SafeProblem(db.Model): __tablename__ = 'SafeProblem' I_SECURITYID = db.Column(db.Integer, primary_key=True) ID = db.Column(db.Integer) S_RESPONSIBILITYDEPT = db.Column(db.VARCHAR(20)) S_RISKPOINT = db.Column(db.VARCHAR(20)) S_HANDLEREASULT = db.Column(db.VARCHAR(20)) D_CHECKDATE = db.Column(db.DATETIME)
class HostList(db.Model): __tablename__ = 'host_list' id = db.Column(db.Integer, primary_key=True, autoincrement=True) host_name = db.Column(db.String(50), nullable=False) ip_address = db.Column(db.String(50), nullable=False) port_num = db.Column(db.String(50), nullable=False) create_time = db.Column(db.DateTime, default=datetime.now) user = db.Column(db.VARCHAR(50), nullable=True) pwd = db.Column(db.VARCHAR(50), nullable=True)
class ProjectOrder(db.Model): """项目方订单""" __tablename__ = 'project_order' __table_args = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) project_id = db.Column(db.Integer, nullable=False, comment="项目 ID") action_id = db.Column(db.VARCHAR(128), nullable=False, unique=True, comment="执行ID, 唯一编码, 控制幂等") coin_id = db.Column(db.Integer, nullable=False, comment="币种表关联键", index=True) tx_hash = db.Column(db.VARCHAR(128), nullable=False, comment="交易hash", unique=True) amount = db.Column(db.VARCHAR(64), nullable=False, comment="交易金额") sender = db.Column(db.VARCHAR(128), nullable=False, comment="发送人") receiver = db.Column(db.VARCHAR(128), nullable=False, comment="接收人") gas = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额,ETH使用") gas_price = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额,ETH使用") fee = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="真实使用手续费") contract = db.Column(db.VARCHAR(128), comment="代币名称或地址") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) def __str__(self): return "{id}-{project_id}-{tx_hash}".format( id=self.id, project_id=self.project_id, tx_hash=self.tx_hash) @classmethod def get_tx_by_action_or_hash(cls, action_id=None, tx_hash=None): """根据action id 或 tx_hash 获取交易""" params = {} if action_id: params['action_id'] = action_id if tx_hash: params['tx_hash'] = tx_hash trx = ProjectOrder.query.filter_by(**params).first() return trx @classmethod def add(cls, project_id, action_id, coin_id, tx_hash, amount, sender, receiver, gas=0, gas_price=0, fee=0, contract=None): """添加项目方发送交易""" session = db.session() trx = ProjectOrder( project_id=project_id, action_id=action_id, coin_id=coin_id, tx_hash=tx_hash, amount=amount, sender=sender, receiver=receiver, gas=gas, gas_price=gas_price, fee=fee, contract=contract) tx_saved = session.add(trx) session.commit() return tx_saved
class Notice(db.Model): """ 公告表 用于公告一些话 @:param notice_date 指定的公告时间 @:param notice_content 公告的内容 @:param notice_createTime 公告的产生时间 """ __tablename__ = 'timer_notice' notice_id = db.Column(db.Integer, primary_key=True, autoincrement=True) notice_date = db.Column(db.VARCHAR(10), nullable=True) notice_content = db.Column(db.VARCHAR(300), nullable=True) notice_createTime = db.Column(db.DateTime, nullable=True)
class Mac(db.Model): """ MAC地址表 用于记录用户的MAC地址,用于路由器爬虫的识别人员 @:param user_id 用户的ID号 @:param mac MAC地址 @:param type MAC的类型,现在1是手机类型,2是电脑类型 """ __tablename__ = 'record_mac' mac_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.Integer, db.ForeignKey('timer_users.user_id')) mac = db.Column(db.VARCHAR(20), nullable=True, unique=True) type = db.Column(db.VARCHAR(10), nullable=True)
class DayTime(db.Model): """ 一天24小时时间表 用于绘制24小时到寝图,记录每个小时过来的分钟数 @:param user_id 用户的ID号 @:param time_date 该天的日期 @:param time_point 该天的时间点 @:param time_count 该天该时间点的在线分钟数 """ __tablename__ = 'record_daytime' daytime_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.Integer, db.ForeignKey('timer_users.user_id')) time_date = db.Column(db.Date) time_point = db.Column(db.VARCHAR(4), nullable=True) time_count = db.Column(db.VARCHAR(2), nullable=True)
class User(db.Model): __tablename__ = 'user' id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) username = db.Column(db.VARCHAR(100), nullable=False) password = db.Column(db.VARCHAR(100), nullable=False, default='123456', server_default='123456') create_time = db.Column(db.DATETIME, nullable=False, default=datetime.now, server_default=db.func.now()) modify_time = db.Column(db.DATETIME, nullable=False, default=datetime.now, server_default=db.func.now()) avatar_path = db.Column(db.VARCHAR(100), nullable=False, default='images/avatar/default.png')
class UserAuthority(db.Model): __tablename__ = 'user_authority' id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) authority = db.Column(db.VARCHAR(100), nullable=False, default='admin', server_default='admin') user_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=False) user = db.relationship('User', backref=db.backref('user_authorities'))
class Users(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.VARCHAR(50), nullable=False) _password = db.Column(db.VARCHAR(320), nullable=False) join_time = db.Column(db.DateTime, default=datetime.now) def __init__(self, username, password): self.username = username self._password = generate_password_hash(password) @property def password(self): return self._password @password.setter def password(self, raw_password): self._password = generate_password_hash(raw_password) def check_password(self, raw_password): result = check_password_hash(self.password, raw_password) return result
class ProjectCoin(db.Model): """项目方支持的币种""" __tablename__ = 'project_coin' __table_args__ = ( UniqueConstraint( 'project_id', 'coin_id', name='uk_project_id_coin_id'), { 'mysql_engine': "INNODB"}) id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) project_id = db.Column(db.Integer, nullable=False, comment="项目 ID") coin_id = db.Column(db.Integer, nullable=False, comment="主链币 ID") hot_address = db.Column(db.VARCHAR(128), nullable=False, comment="热钱包地址") hot_secret = db.Column(db.VARCHAR(128), nullable=False, comment="热钱包密钥, 保留字段, 未使用") hot_pb = db.Column(db.TEXT, comment="热钱包密钥加密公钥") hot_pk = db.Column(db.TEXT, comment="热钱包密钥加密私钥") gas = db.Column(db.VARCHAR(64), nullable=False, default='150000', comment="gas, 默认150000, 0为自动处理") gas_price = db.Column(db.VARCHAR(64), nullable=False, default=str(20 * 1000 * 1000 * 1000), comment="gasPrice, 默认20G, 0为自动处理") fee = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="真实手续费") cold_address = db.Column(db.VARCHAR(128), default=None, comment="冷钱包地址") fee_address = db.Column(db.VARCHAR(128), default=None, comment="手续费钱包地址") last_collection_time = db.Column(db.DateTime, default=None, comment="最后归集时间", onupdate=datetime.now) create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) project = orm.relationship('Project', primaryjoin="ProjectCoin.project_id==Project.id", foreign_keys="ProjectCoin.project_id", backref="ProjectCoin") coin = orm.relationship('Coin', primaryjoin="ProjectCoin.project_id==Coin.id", foreign_keys="ProjectCoin.project_id", backref="ProjectCoin") def __str__(self): return "{id}-{project_id}".format(id=self.id, project_id=self.project_id) @staticmethod def get_pro_coin_by_pid_cname(project_id, coin_name): """根据币种名称及项目方ID 获取项目方支持币种""" session = db.session() project_coin = session.query( ProjectCoin, Coin).join( Coin, ProjectCoin.coin_id == Coin.id).filter( ProjectCoin.project_id == project_id, Coin.name == coin_name) return project_coin.first()
class Label(db.Model): __tablename__ = 'label' id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) name = db.Column(db.VARCHAR(50), nullable=False, default='', server_default='') parent_id = db.Column(db.BigInteger, db.ForeignKey('label.id')) parent = db.relationship('Label', uselist=False, remote_side=[id], backref=db.backref('children'))
class Block(db.Model): """区块表""" __tablename__ = 'block' __table_args__ = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.Integer, primary_key=True, autoincrement=True) height = db.Column(db.Integer, nullable=False, comment="块高度", unique=True) block_hash = db.Column(db.VARCHAR(128), nullable=False, comment="块hash", unique=True) block_time = db.Column(db.DateTime, nullable=False, comment="块时间") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) def __str__(self): return "{id}-{height}-{block_hash}".format( id=self.id, height=self.height, block_hash=self.block_hash)
class Article(db.Model): __tablename__ = 'article' id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) title = db.Column(db.VARCHAR(100), nullable=False, default='', server_default='') info = db.Column(db.Text, nullable=False, default='') content = db.Column(mysql.LONGTEXT(), nullable=False, default='') create_time = db.Column(db.DATETIME, nullable=False, default=datetime.now, server_default=db.func.now()) modify_time = db.Column(db.DATETIME, nullable=False, default=datetime.now, server_default=db.func.now()) good_count = db.Column(db.BigInteger, nullable=False, default=0, server_default='0') click_count = db.Column(db.BigInteger, nullable=False, default=0, server_default='0') author_id = db.Column(db.BigInteger, db.ForeignKey('user.id'), nullable=False) label_id = db.Column(db.BigInteger, db.ForeignKey('label.id'), nullable=False) author = db.relationship('User', backref=db.backref('articles'), order_by=modify_time.desc()) label = db.relationship('Label', backref=db.backref('articles', order_by=modify_time.desc()))
class Transaction(db.Model): """ 交易表 """ __tablename__ = 'tx' __table_args__ = ( UniqueConstraint('tx_hash', 'coin_id', name='uk_tx_hash_coin_id'), {'mysql_engine': "INNODB"} ) id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) block_id = db.Column(db.Integer, nullable=False, comment="块表关联键", index=True) coin_id = db.Column(db.Integer, nullable=False, comment="币种表关联键", index=True) tx_hash = db.Column(db.VARCHAR(128), nullable=False, comment="交易hash") height = db.Column(db.Integer, nullable=False, comment="交易所在高度", index=True) block_time = db.Column(db.Integer, nullable=False, comment="交易时间戳") amount = db.Column(db.VARCHAR(64), nullable=False, comment="交易金额") sender = db.Column(db.VARCHAR(128), nullable=False, comment="发送人") receiver = db.Column(db.VARCHAR(128), nullable=False, comment="接收人") gas = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额, ETH使用") gas_price = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="手续费金额, ETH使用") fee = db.Column(db.VARCHAR(64), nullable=False, default=0, comment="真手续费金额") contract = db.Column(db.VARCHAR(128), comment="代币名称或地址") status = db.Column(db.SmallInteger, nullable=False, comment="交易是否有效 1)有效 0)无效 2) 未知") type = db.Column(db.SmallInteger, nullable=False, comment="交易类型") is_send = db.Column(db.SmallInteger, nullable=False, comment="是否推送 0:未推 1:已推 2:不用推") create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) update_time = db.Column(db.DateTime, nullable=False, comment="更新时间", default=datetime.now, onupdate=datetime.now) coin = orm.relationship('Coin', primaryjoin="Transaction.coin_id==Coin.id", foreign_keys="Transaction.coin_id", backref="Transaction") def __str__(self): return "{id}-{tx_hash}-{height}-{status}".format( id=self.id, tx_hash=self.tx_hash, height=self.height, status=self.status) @classmethod def get_tx_coin_tx(cls, **params): """获取""" session = db.session() block_tx = session.query( Transaction, Coin).join( Transaction, Transaction.coin_id == Coin.id).filter( **params) return block_tx @classmethod def get_tx_coin_by_tx_hash(cls, tx_hash): """ 根据tx hash 获取获取交易tx 及 币种信息 :param tx_hash: :return: """ session = db.session() txs = session.query( Transaction, Coin).join( Transaction, Transaction.coin_id == Coin.id).filter( Transaction.tx_hash == tx_hash) return txs.first() @classmethod def add_transaction(cls, coin_id, tx_hash, block_time, sender, receiver, amount, status, tx_type, block_id, height, gas=0, gas_price=0, fee=0, contract=None, *, commit=True): """添加交易""" session = db.session() trx = Transaction(coin_id=coin_id, tx_hash=tx_hash, block_time=block_time, sender=sender, receiver=receiver, amount=amount, status=status, type=tx_type, gas=gas, gas_price=gas_price, fee=fee, contract=contract, block_id=block_id, height=height, is_send=SendEnum.NEEDLESS.value) # saved 如果成功情况下是 None saved = session.add(trx) if commit: # 自动提交 session.commit() return saved # 返回 session 等待自行处理 return session @classmethod def add_transaction_or_update(cls, coin_id, tx_hash, block_time, sender, receiver, amount, status, tx_type, block_id, height, gas=0, gas_price=0, fee=0, contract=None, is_send=0, *, commit=True, session=None): """添加交易或更新交易""" session = session or db.session() sql = ( "insert into {table_name} (coin_id, tx_hash, block_time, sender, receiver, amount, " "status, type, gas, gas_price, fee, contract, block_id, height, is_send, " "create_time, update_time) " "values " "({coin_id}, '{tx_hash}', {block_time}, '{sender}', '{receiver}', {amount}, {status}, " "{type}, {gas}, {gas_price}, {fee}, {contract}, {block_id}, {height}, {is_send}, " "'{create_time}', '{update_time}')" "ON DUPLICATE KEY UPDATE block_time=values(block_time), gas=values(gas), " "gas_price=values(gas_price), " "fee=values(fee), block_id=values(block_id), height=values(height)").format( table_name=cls.__tablename__, coin_id=coin_id, tx_hash=tx_hash, block_time=block_time, sender=sender, receiver=receiver, amount=amount, status=status, type=tx_type, gas=gas, gas_price=gas_price, fee=fee, contract="'{}'".format(contract) if contract is not None else 'null', block_id=block_id, height=height, is_send=is_send, create_time=now(), update_time=now()) # saved 如果成功情况下是 None saved = session.execute(sql) if commit: # 自动提交 session.commit() return saved # 返回 session 等待自行处理 return session
class Users(db.Model): """ 用户表 记录用户基本信息的表 @:param account 学号 @:param user_name 姓名 @:param user_password 用户密码 @:param sex 性别 @:param grade 年级 @:param type 用户类型,比如用正式成员,普通成员,退休成员,考核成员,测试人员等 @:param update_time 更新时间,用于判断是否在工作室内,若查询当前时间-更新时间大于90s则代表不在工作室 @:param avatar_path 头像地址 """ __tablename__ = 'timer_users' user_id = db.Column(db.Integer, primary_key=True, autoincrement=True) account = db.Column(db.VARCHAR(11), nullable=True, unique=True) user_name = db.Column(db.VARCHAR(20), nullable=True, unique=True) user_password = db.Column(db.VARCHAR(32), nullable=True) sex = db.Column(db.VARCHAR(6), nullable=True) grade = db.Column(db.VARCHAR(4), nullable=True) type = db.Column(db.VARCHAR(10)) update_time = db.Column(db.Integer) avatar_path = db.Column(db.VARCHAR(200)) def getBaseInformation(self): """ 获取该用户的基本信息 @:return 当前用户头像地址、id、用户名、性别、是否在工作室、现有时间的列表 """ time = db.session.query(func.sum(Times.times_count)).filter( Times.times_date >= Timer.getCurrentWeek(), Times.user_id == self.user_id).group_by(Times.user_id).first() if time is None: time = 0 else: time = time[0] / 60 second = str(100 + int(random.randint(1, 59)))[1:] if self.avatar_path is None: if self.sex == '男': head_path = url_for('static', filename='image/man.jpg') else: head_path = url_for('static', filename='image/women.jpg') else: head_path = self.avatar_path information = { "head": head_path, "user_id": self.user_id, "user_name": self.user_name, "sex": self.sex, "inRoom": self.isOnTheRoom(), "time": { "hours": str(100 + int(time / 60))[1:], "mintus": str(100 + int(time % 60))[1:], "seconds": str(second), }, "type": self.type } return information def isOnTheRoom(self): """ 判断该用户是否在工作室中 @:return 是否在工作室真假值 """ updateTime = self.update_time if updateTime == None: updateTime = 0 if int(time.time()) - updateTime <= 90: return True else: return False def getMacAddress(self): """ 获取该用户MAC地址 @:return 返回手机和电脑的MAC地址 """ user_mobile_mac = Mac.query.filter(Mac.user_id == self.user_id, Mac.type == 1).first() user_computer_mac = Mac.query.filter(Mac.user_id == self.user_id, Mac.type == 2).first() mobile_mac = '' computer_mac = '' if user_mobile_mac != None: mobile_mac = user_mobile_mac.mac if user_computer_mac != None: computer_mac = user_computer_mac.mac return {"mobile": mobile_mac, "computer": computer_mac} # TODO 查询用户当前在线时间 def getOnlineTime(self): pass # TODO 查询该天该用户的计时图 def getDayTime(self, time_date): pass # TODO 查询头像地址 def getAvatarPath(self, file): pass # TODO 增加头像 def setAvatar(self, file): basepath = os.path.dirname(__file__) pic_name = file.filename + str(time.time()) + self.user_name md5 = hashlib.md5() md5.update(str(pic_name).encode('utf-8')) pic_name = md5.hexdigest() + '.jpg' file.save('static/avatar/' + pic_name) print(basepath + 'static/avatar/' + pic_name) if self.avatar_path != None and os.path.exists(self.avatar_path): os.remove(self.avatar_path) self.avatar_path = url_for('static', filename='avatar/' + pic_name) db.session.commit() return self.avatar_path def setMac(self, mobile_mac, computer_mac): """ 设置Mac地址,若不存在Mac地址曾新增 :param mobile_mac: 手机的Mac地址 :param computer_mac: 电脑的Mac地址 :return: """ def upMac(mac): if mac is None: mac = "" return str(mac).upper().replace(":", "-") def isLegal(mac): ac = re.search("(..)-(..)-(..)-(..)-(..)-(..)", mac) if ac is None: return False else: return True mob = upMac(mobile_mac) com = upMac(computer_mac) mobile_mac = Mac.query.filter(Mac.user_id == self.user_id, Mac.type == 1).first() computer_mac = Mac.query.filter(Mac.user_id == self.user_id, Mac.type == 2).first() if mobile_mac is None and isLegal(mob): mobile_mac = Mac(mac=mob, user_id=self.user_id, type='1') db.session.add(mobile_mac) elif mobile_mac and isLegal(mob): mobile_mac.mac = mob if computer_mac is None and isLegal(com): computer_mac = Mac(mac=com, user_id=self.user_id, type='2') db.session.add(computer_mac) elif computer_mac and isLegal(com): computer_mac.mac = com db.session.commit() # TODO 更新时间 def updateTime(self): pass
class Coin(db.Model): """ 币种表 """ __tablename__ = 'coin' __table_args__ = ( UniqueConstraint( 'master_id', 'contract', name='uk_master_id_contract'), { 'mysql_engine': "INNODB"}) id = db.Column(db.Integer, primary_key=True, autoincrement=True) master_id = db.Column(db.Integer, unique=False, default=0, comment="主链ID") name = db.Column(db.String(64), unique=True, comment='币种名称') symbol = db.Column(db.String(64), comment='缩写') decimal = db.Column(db.SmallInteger, nullable=False, default=0, comment='小数位') supply = db.Column(db.BigInteger, comment='发行量') is_master = db.Column(db.SmallInteger, default=1, comment='是否主链币 1 是 0 否') bip44 = db.Column(db.Integer, default=1, comment='bip44 编码') contract = db.Column(db.VARCHAR(128), comment="代币名称", unique=True) create_time = db.Column(db.DateTime, nullable=False, comment="创建时间", default=datetime.now) sync_config = orm.relationship('SyncConfig', primaryjoin="SyncConfig.coin_id==Coin.id", foreign_keys="Coin.id", backref="Coin") address = orm.relationship('Address', primaryjoin="Address.coin_id==Coin.id", foreign_keys="Coin.id", backref="Coin") transaction = orm.relationship('Transaction', primaryjoin="Transaction.coin_id==Coin.id", foreign_keys="Coin.id", backref="Coin") # coin = orm.relationship('Coin', # primaryjoin="Coin.master_id==Coin.id", # foreign_keys="Coin.id", # backref="Coin") def __str__(self): return "{id}-{master_id}-{name}-{symbol}-{is_contract}".format( id=self.id, master_id=self.master_id, name=self.name, symbol=self.symbol, is_contract=self.is_contract and True or False) @staticmethod def get_coin(contract=None, symbol=None, name=None, is_master=1): """从数据库中获取某个币种""" params = {'is_master': is_master} if contract is not None: params['contract'] = contract params['is_master'] = 0 if symbol is not None: params['symbol'] = symbol if name is not None: params['name'] = name coin = Coin.query.filter_by(**params).first() if not coin: return None return coin @staticmethod def get_coin_by_symbol(contract=None, symbol=None, name=None, is_master=1): """根据 symbol 获取币种""" params = {'is_master': is_master} if contract is not None: params['contract'] = contract params['is_master'] = 0 if symbol is not None: params['symbol'] = symbol if name is not None and symbol is None: params['name'] = name coin = Coin.query.filter_by(**params).first() if not coin: return None return coin @staticmethod def get_erc20_usdt_coin(): """获取 ETH 的 ERC20 USDT""" coin = Coin.get_coin_by_symbol(symbol='USDT', is_master=0) if not coin: return None return coin
class SafeNumber(db.Model): __tablename__ = "SafeNumber" DEPT_NAME = db.Column(db.VARCHAR(20), primary_key=True) TIME = db.Column(db.DATETIME, primary_key=True) PROBLEM_TYPE = db.Column(db.VARCHAR(20), primary_key=True) NUMBER = db.Column(db.INT)
class Address(db.Model): """地址表""" __tablename__ = 'address' __table_args__ = ( {'mysql_engine': "INNODB"} ) id = db.Column(db.Integer, primary_key=True, autoincrement=True) coin_id = db.Column(db.Integer, nullable=False, comment="币种ID", index=True) project_id = db.Column(db.Integer, nullable=False, comment="项目方 ID") address = db.Column( db.VARCHAR(128), unique=True, nullable=False, comment="地址") address_type = db.Column(db.SmallInteger, default=0, comment="地址类型,0充 1提") is_send = db.Column( db.SmallInteger, default=0, index=True, comment="是否已给予,0否 1是") status = db.Column(db.SmallInteger, default=1, comment="是否有效,0否 1是") create_time = db.Column( db.DateTime, nullable=False, comment="生成时间", default=datetime.now) coin = orm.relationship('Coin', primaryjoin="Address.coin_id==Coin.id", foreign_keys="Address.coin_id", backref="Address") transaction = orm.relationship( 'Transaction', primaryjoin="Address.address==Transaction.receiver", foreign_keys="Address.address", backref="Address") project = orm.relationship('Project', primaryjoin="Address.project_id==Project.id", foreign_keys="Address.project_id", backref="Address") def __str__(self): return "{id}-{coin_id}-{project_id}-{address}".format( id=self.id, coin_id=self.coin_id, project_id=self.project_id, address=self.address) @staticmethod def add_address(project_id, coin_id, address, address_type=0, is_send=0, *, commit=True): """添加地址""" address = Address(project_id=project_id, coin_id=coin_id, address=address, address_type=address_type, is_send=is_send) session = db.session() saved = session.add(address) if commit: session.commit() return saved return session @staticmethod def add_addresses(addresses: list, *, commit=True): """ 添加多个地址进入数据库, 字段仅是将 address中的拆解, 其他都一样, :param addresses: lidt<dict>, [{project_id, coin_id, address, address_type, is_send}] :param commit: :return: """ session = db.session() try: for address_dict in addresses: address = Address(**address_dict) session.add(address) if commit: session.commit() return None return session except Exception: session.rollback() return None @staticmethod def get_coin_address_by_coin_name(coin_name): """ 这种方式返回的格式固定为 list<tuple<row>> row 取决于 with_entities 里面的字段 :return address, project_id, coin_id, coin_name """ session = db.session() addresses = session.query(Address, Coin).join( Address, Address.coin_id == Coin.id).with_entities( Address.address, Address.project_id, Address.coin_id, Coin.name ).filter(Coin.name == coin_name).all() return addresses