def addUser(user_name, user_age, user_id): leader = User(user_name=user_name, user_age=user_age, user_id=user_id) db.session.add(leader) try: db.session.commit() print("user添加成功!") except Exception as e: print(e) db.session().rollback() return False return True
def release(): if request.method == 'GET': return render_template('release.html') else: title = request.form.get('title') content = request.form.get('content') Release(title=title, content=content) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() release.author = user db.session(release) db.session.commit() return redirect(url_for('index'))
def register(): if request.method == 'GET': return render_template('register.html') elif request.method == 'POST': name = request.form.get('name', None) user_list = User.query.filter(User.name==name).all() if user_list: return render_template('register.html', register_info='<div class="alert alert-danger" role="alert">账号已存在</div>') else: password = request.form.get('password', None) password = hashlib.sha1(password).hexdigest() user = User(name=name, password=password) db.session(user) db.session.commit() return redirect(url_for('index'))
def __init__(self, save_path=""): super(Baksql, self).__init__() self.s = db.session() self.save_path = save_path self.baksql_name = datetime.datetime.now().strftime( "%Y%m%d%H%M%S") + ".sql" self.begtime = time.time()
def deposit(self): self.logger.info("开始上账进程") with runtime.app.app_context(): no_push_txs = Transaction.query.filter( Transaction.is_send == SendEnum.NOT_PUSH.value) for tx in no_push_txs: receiver = tx.receiver project_addr = runtime.project_address.get(receiver) if not project_addr: continue project = self.project.get(project_addr['project_id']) tx_hash = tx.tx_hash url = project['url'] params = { "txHash": tx.tx_hash, "blockHeight": tx.height, "amount": tx.amount, "address": tx.receiver, "orderid": uuid.uuid4().hex } try: rsp = requests.post(url, params=params) except Exception as e: self.logger.error("请求为 {} 上账不成功, 内容 {}, 错误: {}".format( project['name'], params, e)) continue if rsp.status_code == 200: session = db.session() session.query(Transaction).filter( tx.hash == tx_hash).update( {'is_send': SendEnum.PUSHED.value}) session.commit() self.logger.info("结束上账进程")
def query_city_list(): query = db.session().query(CityName).all() result = {} for i in query: if not (i.first_letter in result.keys()): result[i.first_letter] = [] result[i.first_letter].append(i.to_json()) return result
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
def get_sync_info(coin_name): """获取同步信息""" session = db.session() coin_sync = session.query( SyncConfig, Coin).join( SyncConfig, SyncConfig.coin_id == Coin.id).filter( Coin.name == coin_name).first() return coin_sync
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
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()
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
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()
def query_count_fo_all(): daydata = DayData.query.count() monthdata = MonthData.query.count() least_time = db.session.query(func.max(DayData.time_point)).scalar() provinces_list = db.session().query(Provinces).all() year_list = [str(i + 2013) for i in range(7)] return { 'year_list': year_list, 'daydata': daydata, 'monthdata': monthdata, 'least_time': least_time, 'provinces_list': provinces_list }
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
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
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
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
class Article(db.Model): __tablename__ = 'article' id = db.Column(db.Integer, autoincrement=True, primary_key=True) title = db.Column(db.String(100)) #标题 excerpt = db.Column(db.session(200)) #摘要 category_id = db.Column(db.Integer, db.ForeignKey('category.id')) #文章与分类是一对多的关系 category = db.relationship("Category", backref='categorys') #分类表可以通过查询文章 tags = db.relationship("Tag", secondary=article_tag_table, backref='tags') #标签与文章是多对多的关系 #user 是通过取出用户表中用户字段 user_id = db.Column(db.Integer, db.ForeignKey('cms_user.id')) user = db.relationship('CMSUser', backref='cmsusers') views = db.Column(db.Integer) #tui 推荐位与文章表是一对多的关系 tui_id = db.Column(db.Integer, db.ForeignKey('tui.id')) tui = db.relationship("Tui", backref='tuis') created_time = db.Column(db.DateTime, default=datetime.now) modified_time = db.Column(db.DateTime, default=datetime.now)
def scan(self): self.block_info = self.rpc.get_block_height() self.newest_height = self.block_info.current_height self.highest_height = self.block_info.highest_height # 延迟扫 SCAN_DELAY_NUMBER 个块 need_to_height = self.newest_height - self.SCAN_DELAY_NUMBER self.logger.info('起始扫块高度:{} 最新高度:{} 需要同步:{}'.format( self.current_scan_height, self.newest_height, need_to_height - self.current_scan_height)) while self.current_scan_height < need_to_height: self.logger.info('当前已扫块高度:{} 最新高度:{} 需要同步:{} 节点最高高度:{}'.format( self.current_scan_height, self.newest_height, need_to_height - self.current_scan_height, self.highest_height)) for height in range(self.current_scan_height, need_to_height, self.SCAN_HEIGHT_NUMBER): # 分批处理, 一次处理 SCAN_HEIGHT_NUMBER 或 剩余要处理的块 block_batch = min(self.SCAN_HEIGHT_NUMBER, need_to_height - self.current_scan_height) blocks = self.rpc.get_block_by_number([ digit.int_to_hex(height) for height in range(height, height + block_batch) ]) save_tx_count = 0 with runtime.app.app_context(): # 一次处理一批 session = db.session() try: for block in blocks: if block is None: return block_height = digit.hex_to_int(block['number']) block_hash = block['hash'] block_timestamp = digit.hex_to_int( block['timestamp']) block_time = datetime.fromtimestamp( block_timestamp) session.begin(subtransactions=True) db_block = Block(height=block_height, block_hash=block_hash, block_time=block_time) session.add(db_block) session.commit() for transaction in block.get('transactions', []): tx = EthereumResolver.resolver_transaction( transaction) if tx.sender in runtime.project_address: # 提现的暂时不要 continue if tx.receiver in runtime.project_address: receipt_raw_tx = self.rpc.get_transaction_receipt( tx.tx_hash) if tx.contract: coin = runtime.coins.get(tx.contract) else: coin = runtime.coins.get( self.COIN_NAME) if coin is None: continue if receipt_raw_tx: receipt_tx = EthereumResolver.resolver_receipt( receipt_raw_tx) else: self.logger.error( '请求 {} receipt 错误, 重新处理') raise tx.status = receipt_tx.status # session.begin(subtransactions=True) # db_tx = Transaction(block_id=db_block.id, coin_id=coin['coin_id'], # tx_hash=tx.tx_hash, height=db_block.height, # block_time=block_timestamp, # amount=tx.value, sender=tx.sender, receiver=tx.receiver, # gas=tx.gas, gas_price=tx.gas_price, # is_send=SendEnum.NOT_PUSH.value, # fee=receipt_tx.gas_used * tx.gas_price, # contract=tx.contract, status=receipt_tx.status, # type=TxTypeEnum.DEPOSIT.value) Transaction.add_transaction_or_update( block_id=db_block.id, coin_id=coin['coin_id'], tx_hash=tx.tx_hash, height=db_block.height, block_time=block_timestamp, amount=tx.value, sender=tx.sender, receiver=tx.receiver, gas=tx.gas, gas_price=tx.gas_price, is_send=SendEnum.NOT_PUSH.value, fee=receipt_tx.gas_used * tx.gas_price, contract=tx.contract, status=receipt_tx.status, type=TxTypeEnum.DEPOSIT.value, session=session, commit=False) save_tx_count += 1 # session.add(db_tx) # session.commit() # 添加推送信息 session.query(SyncConfig).filter( SyncConfig.id == self.config_id).update({ 'synced_height': height + block_batch, 'highest_height': self.highest_height }) self.current_scan_height = height + block_batch session.commit() self.logger.info("本次同步高度为:{} -- {}, 保存交易: {} 笔".format( height, height + block_batch, save_tx_count)) except Exception as e: self.logger.error('同步块出现异常, 事务回滚. {}'.format(e)) session.rollback() return self.logger.info("扫链结束, 本次同步")
def query_month_data(city): query = db.session().query(MonthData).filter_by(cityName=city).all() return {'city': city, 'result': [i.to_json() for i in query]}
def index(): dataList = db.session().execute("SHOW TABLE STATUS").fetchall() return render_template('/admin/database/index.html', data=dataList)
def query_day_data(city, month): query = db.session().query(DayData).filter(DayData.time_point.ilike(month + '%')).filter_by( cityName=city).all() return {'city': city, 'month': month, 'result': [i.to_json() for i in query]}
def query_provinces_data(provinces): query = db.session().query(CityName).filter(CityName.regionid.ilike(provinces + '%')) return {'provinces': provinces, 'result': [i.to_json() for i in query]}
def query_day_data(day): query = db.session().query(DayData).filter(DayData.time_point == day).all() temp = [i.to_json() for i in query] return json.dumps(temp, ensure_ascii=False)
from flask import Flask from exts import db from config.config import config from key.generate_key import generate_rsa_key, generate_ack from models.models import * app = Flask(__name__) app.config.from_object(config) db.init_app(app) app.app_context().push() db.create_all() session = db.session() sign_key = generate_ack() rsa_key = generate_rsa_key() # session.begin(subtransactions=True) # 币种相关 # 添加 ETH eth_coin = Coin() eth_coin.id = 1 eth_coin.name = "Ethereum" eth_coin.symbol = "ETH" eth_coin.decimal = 18 eth_coin.supply = 20000000 eth_coin.is_master = 1 eth_coin.bip44 = 100 session.add(eth_coin)
def query_provinces_list(): query = db.session().query(Provinces).all() return [i.to_json() for i in query]