def add_praise(self, user_id, comment_id): with MysqlTools().session_scope() as session: if user_id == '': self.return_error(20011) if comment_id == '': self.return_error(40003) comment = session.query(MineCommentsModel). \ filter(MineCommentsModel._id == comment_id).first() is_praise = self.get_is_praise(user_id, comment.praise_users) if is_praise == 1: self.return_error(40007) else: comment.praise_number = int(comment.praise_number) + 1 comment.praise_users = comment.praise_users + ',' + str( user_id) session.commit() return {"status": True}
def cancel_robot_config(self, dic): id = dic['id'] with MysqlTools().session_scope() as session: game = session.query(RobotGameConfigRecordModel).filter( RobotGameConfigRecordModel._id == id).first() if game is None: return False game.status = 4 q = session.query(RobotConfigRecordModel).filter( RobotConfigRecordModel.time_stamp == game.time_stamp).all() if len(q) > 0: for robot in q: robot.bet_status = 2 session.commit() return True
def edit_banner(self, banner_id, title, site, auto_online, image, thumbnail, remark=''): with MysqlTools().session_scope() as session: banner = session.query(BannerManageModel). \ filter(BannerManageModel._id == banner_id).first() if banner.status != 0: self.return_error(40013) banner.title = title banner.site = site banner.auto_online = auto_online banner.image = image banner.thumbnail = thumbnail if remark != '': banner.remark = remark session.commit() return { "status": True }
def get_banner_list(self, limit, offset, title='', site='', online_time_start='', online_time_end='', status='', create_time_start='', create_time_end=''): offset = get_offset_by_page(offset, limit) result_dict = { 'limit': limit, 'offset': offset, 'count': 0, 'content': [], 'total': 0 } with MysqlTools().session_scope() as session: q = session.query(BannerManageModel). \ order_by(BannerManageModel.created_at.desc()) if title != '': q = q.filter(BannerManageModel.title == title) if site != '': q = q.filter(BannerManageModel.site == site) if status != '': q = q.filter(BannerManageModel.status == status) if create_time_start != '': q = q.filter(BannerManageModel.created_at >= create_time_start) if create_time_end != '': q = q.filter(BannerManageModel.created_at <= create_time_end) if online_time_start != '': q = q.filter(BannerManageModel.auto_online >= online_time_start) if online_time_end != '': q = q.filter(BannerManageModel.auto_online <= online_time_end) record_count = q.count() result_dict['total'] = record_count result_dict['count'] = get_page_by_offset(record_count, limit) query_result = q.all() if query_result is not None: for i in query_result: result_dict['content'].append({ 'id': i._id, "title": i.title, 'site': i.site, 'status': i.status, 'image': i.image, 'thumbnail': i.thumbnail, 'created_at': str(i.created_at), 'auto_online': str(i.auto_online), 'remark': i.remark }) return result_dict
def dice_records(self, limit, offset, user_id='', start_id=None): offset = get_offset_by_page(offset, limit) result_dict = { 'limit': limit, 'offset': offset, 'count': 0, 'content': [] } account_service = AccountService() with MysqlTools().session_scope() as session: q = session.query(DiceParticipateInModel). \ order_by(DiceParticipateInModel.created_at.desc()) if user_id != '': q = q.filter(DiceParticipateInModel.user_id == user_id) record_count = q.count() result_dict['count'] = get_page_by_offset(record_count, limit) if start_id is not None: start_id = str(start_id) q = q.filter(DiceParticipateInModel._id < start_id) participate_list = q.limit(limit).offset(offset).all() for i in participate_list: user_info = account_service.get_inner_user_account_info( session, i.user_id) user_name = user_info['nick_name'] result = { 'id': i._id, 'user_name': user_name, 'dice_result': i.dice_result, 'dice_time': timestamp_to_str(int(float(i.dice_timestamp)), format_style="%Y-%m-%d %H:%M:%S"), 'reward_token': self.get_coin_name(i.reward_token), 'reward_quantity': decimal_to_str(i.reward_quantity, 6) } if i.reward_token == int(_COIN_ID_USDT): result['reward_quantity'] = decimal_to_str( i.reward_quantity, 4) result_dict['content'].append(result) return result_dict
def modify_model_status(self, dic): id = dic.get("id", "") if id == '': return self.return_error(50001) with MysqlTools().session_scope() as session: model = session.query(GameDigitalTemplateModel).filter( GameDigitalTemplateModel._id == id).with_for_update().first() if model is None == 0: return self.return_error(50001) if model.template_status == 0: model.template_status = 1 else: model.template_status = 0 session.commit() return True
def comment_manage_list(self, limit, offset, user_name='', key_word='', release_time_start='', release_time_end='', status='', picture=''): offset = get_offset_by_page(offset, limit) result_dict = { 'limit': limit, 'offset': offset, 'count': 0, 'content': [], 'total': 0 } with MysqlTools().session_scope() as session: # account_service = AccountService() q = session.query(MineCommentsModel). \ order_by(MineCommentsModel.created_at.desc()) if user_name != '': q = q.filter(MineCommentsModel.user_name == user_name) if key_word != '': q = q.filter(MineCommentsModel.submit_content.like('%' + key_word + '%')) if status != '': q = q.filter(MineCommentsModel.status == status) if release_time_start != '': q = q.filter(MineCommentsModel.created_at >= release_time_start) if release_time_end != '': q = q.filter(MineCommentsModel.created_at <= release_time_end) if picture == '1': q = q.filter(MineCommentsModel.submit_image != '') if picture == '0': q = q.filter(MineCommentsModel.submit_image == '') record_count = q.count() result_dict['total'] = record_count result_dict['count'] = get_page_by_offset(record_count, limit) query_result = q.all() if query_result is not None: for i in query_result: # user_info = account_service.get_inner_user_account_info(session, i.user_id) result_dict['content'].append({ "user_name": i.user_name, 'submit_content': i.submit_content, 'submit_image': i.submit_image, 'submit_thumbnail': i.submit_thumbnail, 'praise_number': i.praise_number, 'status': i.status }) return result_dict
def edit_announce(self, announce_id, title, site, auto_online, auto_offline='', remark=''): if auto_offline <= auto_online: self.return_error(40011) with MysqlTools().session_scope() as session: announce = session.query(AnnouncementManageModel). \ filter(AnnouncementManageModel._id == announce_id).first() if announce.status != 0: self.return_error(40012) announce.title = title announce.site = site announce.auto_online = auto_online if auto_offline != '': announce.auto_offline = auto_offline if remark != '': announce.remark = remark session.commit() return { "status": True }
def get_game_instance_none_user(self): with MysqlTools().session_scope() as session: instance_info = session.query(InstantGameInstanceModel). \ order_by(InstantGameInstanceModel.created_at.desc()).first() if instance_info is None: self.return_error(40005) result = { 'ins_instance': { 'id': instance_info._id, 'game_serial': instance_info.game_serial, 'game_title': instance_info.game_title, 'game_describe': instance_info.game_describe, 'need': instance_info.need, 'max_bet_ratio': instance_info.max_bet_ratio, 'status': instance_info.status, 'bet_token': self.get_coin_name(instance_info.bet_token), } } return result
def get_wallet_mysql(arg): db_conf = { "wallet": { "db": "WalletCenter", "host": "test.cgvynnfmwcpw.ap-northeast-1.rds.amazonaws.com", "port": "3306", "user": "******", "psd": "X88Db3jLBXki" }, "token": { "db": "TokenPark", "host": "test.cgvynnfmwcpw.ap-northeast-1.rds.amazonaws.com", "port": "3306", "user": "******", "psd": "BF1xE960ivNd" } } tools = MysqlTools(db_conf[arg]) return tools
def automatic_release(self, session, template_id): # now = int(time.time()) # time_struct = time.localtime(now) # str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct) template_id = 1 str_time = get_utc_now() with MysqlTools().session_scope() as session: template_info = session.query(InstantGameTemplateModel). \ filter(InstantGameTemplateModel._id == template_id).first() # 判断存在在"启用"状态 且 自动发布的模板 if template_info.template_status == 1 and template_info.auto_release == 1: # 查询btc 与 usdt 转换比 btc_usdt_rate = get_exchange_rate( template_info.reward_token)['price'] if btc_usdt_rate > template_info.need_ceiling or btc_usdt_rate < template_info.need_floor: raise_logger("automatic_release out of rate", 'rs', 'error') return {"status": False} need = btc_usdt_rate * template_info.reward_quantity game_serial = generate_phase(str(template_info.phase_prefix)) digital_instance_model = InstantGameInstanceModel( template_id=template_id, game_serial=game_serial, game_title=template_info.game_title, bet_token=template_info.bet_token, bet_unit=template_info.bet_unit, support_token=template_info.support_token, reward_token=template_info.reward_token, reward_quantity=template_info.reward_quantity, handling_fee=template_info.handling_fee, game_describe=template_info.game_describe, experience=template_info.experience, merge_threshold=template_info.merge_threshold, max_bet_ratio=template_info.max_bet_ratio, release_time=str_time, need=int(need), status=-1, release_type=1, chain_status=0) session.add(digital_instance_model) # session.flush() session.commit() return {"status": True}
def lottery_adduce(cls, game_instance_id, base_time_stamp, lottery_block_add=60, confirm_block_add=200): """ 一元夺宝 外部引用 :param game_instance_id: 游戏实例id 必传 :param base_time_stamp: 传时间戳 float或decimal类型 必须保留小数点后3位 必传 :param lottery_block_add: 根据时间戳找到基础参照区块,加上该参数,即开奖区块号 :param confirm_block_add: 根据开奖区块号,加上该参数,就是确认区块号,脚本找到该区块,即公布开奖,脚本回调 lottery_callback :return: """ lottery_block_add -= _ONE # 根据基础块找,所以需要减1 game_instance_id = int(game_instance_id) try: with MysqlTools().session_scope() as session: lottery_block_info = session.query(GameGetLotteryBlockInfoEosModel).filter(GameGetLotteryBlockInfoEosModel.game_instance_id == game_instance_id).first() if lottery_block_info: base_block_num = lottery_block_info.base_block_num lottery_block = lottery_block_info.block_num confirm_block = lottery_block_info.confirm_block_num else: base_block_num = game_instance_id * -1 lottery_block = lottery_block_add confirm_block = confirm_block_add lottery_block_info = GameGetLotteryBlockInfoEosModel( game_instance_id=game_instance_id, base_block_num=base_block_num, base_time_stamp=base_time_stamp, block_num=lottery_block, confirm_block_num=confirm_block ) session.add(lottery_block_info) session.commit() return { "game_instance_id": game_instance_id, "base_block_num": base_block_num, "block_num": lottery_block, "confirm_block": confirm_block } except Exception as e: raise_logger("lottery_adduce" + str(e), "wallet", "error") return False
def reset_robot_config(self, dic): robots = [] json_robots = dic.get("robots", "") if isinstance(json_robots, str): robots = json.loads(json_robots) if isinstance(json_robots, list): robots = json_robots with MysqlTools().session_scope() as session: for robot in robots: if robot == "": return self.return_error(70001) q = session.query(RobotAccountModel).filter( RobotAccountModel.user_id == robot).first() q.status = 1 session.commit() return True
def indiana_number(self, participate_id): with MysqlTools().session_scope() as session: par = session.query(ParticipateInModel). \ filter(ParticipateInModel._id == participate_id).first() pattern = re.compile(r'[\[\]\s]') merge_total = 0 merge_mine = par.bet_number * par.bet_unit if par.merge_id == -1: award_numbers_list = par.award_numbers indiana_numbers = pattern.sub('', award_numbers_list).split(',') else: indiana_numbers = [] merge_participate_list = session.query(ParticipateInModel). \ filter(ParticipateInModel.merge_id == par.merge_id).all() for merge_participate in merge_participate_list: merge_total += merge_participate.bet_number * merge_participate.bet_unit indiana_numbers += pattern.sub( '', merge_participate.award_numbers).split(',') win_record = session.query(WinningRecordModel). \ filter(WinningRecordModel.game_serial == par.game_serial).first() number_list = [] win_serial = '-1' if win_record is not None: win_serial = win_record.bet_serial for i in indiana_numbers: if i == win_serial: status = True else: status = False number_list.append({'number': i, 'is_win': status}) return { 'game_serial': par.game_serial, 'indiana_time': str(par.created_at), 'indiana_numbers': number_list, 'win_record': win_serial, 'merge_mine': merge_mine, 'merge_total': merge_total, 'merge_id': par.merge_id, 'bet_toekn': self.get_coin_name(par.bet_token), }
def announce_scan(self): now = int(time.time()) time_struct = time.localtime(now) str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct) with MysqlTools().session_scope() as session: announce_list = session.query(AnnouncementManageModel). \ filter(or_(AnnouncementManageModel.status == 0, AnnouncementManageModel.status == 1)).all() # print("len(announce_list)===", len(announce_list)) # print("str_time===", str_time) if len(announce_list) > 0: for announce in announce_list: # print("announce.auto_online===", announce.auto_online) # print("announce.auto_offline===", announce.auto_offline) if announce.status == 0: if str(announce.auto_online) <= str_time: announce.status = 1 else: if str(announce.auto_offline) <= str_time: announce.status = 2 session.commit()
def addGameLotteryBlock(id: str): with MysqlTools().session_scope() as session: model = session.query(GameGetLotteryBlockInfoModel).filter( GameGetLotteryBlockInfoModel.game_instance_id == id).with_for_update().first() if model is None: time_stamp = int(time.time()) block_info = GameGetLotteryBlockInfoModel( game_instance_id=int(id), time_stamp=time_stamp, ) session.add(block_info) session.commit() return time_stamp if model.block_hash is None or model.block_hash == '': return model.time_stamp if model.block_hash: return model.block_hash
def app_version_check(self, version_code): with MysqlTools().session_scope() as session: version_info = session.query(AppUpgradeModel). \ filter(AppUpgradeModel.status == 1). \ order_by(AppUpgradeModel._id.desc()).first() if version_info is None: self.return_error(40020) # 有更新版本 if version_info.version_code > int(version_code): return { 'new_version': True, 'version_info': { 'version_name': version_info.version_name, 'upgrade_describe': version_info.upgrade_describe, 'download_link': version_info.download_link, 'forced_update': version_info.forced_update, 'status': version_info.status } } else: return {'new_version': False}
def dice_info(self, dice_part_id): with MysqlTools().session_scope() as session: dice_info = session.query(DiceParticipateInModel). \ filter(DiceParticipateInModel._id == dice_part_id).first() if dice_info is None: self.return_error(40021) if dice_info.block_timestamp != '0000-00-00T00:00:00.000': block_timestamp = timestamp_to_str( str_to_timestamp(dice_info.block_timestamp, format_style="%Y-%m-%dT%H:%M:%S.%f"), format_style="%Y-%m-%d %H:%M:%S") else: block_timestamp = '' return { 'dice_serial': dice_info.dice_serial, 'dice_time': timestamp_to_str(int(float(dice_info.dice_timestamp)), format_style="%Y-%m-%d %H:%M:%S"), 'reward_token': self.get_coin_name(dice_info.reward_token), 'reward_quantity': str(dice_info.reward_quantity), 'bet_number': str(dice_info.bet_number), 'bet_token': self.get_coin_name(dice_info.bet_token), 'user_dice': dice_info.user_dice, 'banker_dice': dice_info.banker_dice, 'dice_result': dice_info.dice_result, # 'calc': int(dice_info.block_hash, 16) / 3, 'eos_block_info': { 'block_no': dice_info.block_no, 'block_hash': dice_info.block_hash, 'block_timestamp': block_timestamp } }
def search_robot_config(self, dic): limit = int(dic.get('limit', 10)) offset = get_offset_by_page(dic.get('offset', 1), limit) start_id = dic.get("start_id", None) total = 0 count = 0 with MysqlTools().session_scope() as session: game_config = session.query(RobotGameConfigRecordModel).filter( RobotGameConfigRecordModel._id == dic['id']).first() q = session.query(RobotConfigRecordModel).filter( RobotConfigRecordModel.time_stamp == game_config.time_stamp) total = q.count() count = get_page_by_offset(total, limit) if start_id is not None: q = q.filter(RobotConfigRecordModel._id < str(start_id)) query_result = q.order_by(RobotConfigRecordModel._id.asc()).limit( limit).offset(offset).all() content = [] if len(query_result) > 0: for i in query_result: content.append({ 'user_id': str(i.user_id), 'nick_name': i.nick_name, 'bet_number': str(i.bet_number), 'pay_token': str(i.pay_token), 'bet_plan_time': str(i.bet_plan_time), 'bet_status': str(i.bet_status), }) return { 'limit': dic.get('limit', 10), 'offset': dic.get('offset', 1), 'count': count, 'total:': total, 'content': content }
def add_comment(self, content, submit_thumbnail='', submit_image='', user_id='', user_name=''): with MysqlTools().session_scope() as session: if user_id == '': self.return_error(20011) if content == '': self.return_error(40002) comment = MineCommentsModel(user_id=user_id, user_name=user_name, submit_content=content, praise_number=0, praise_users='', submit_image=submit_image, submit_thumbnail=submit_thumbnail, status=1) session.add(comment) session.commit() return {"status": True}
def manual_release(self, template_id, game_serial, need, game_describe): if not need.isdigit(): self.return_error(40008) # now = int(time.time()) # time_struct = time.localtime(now) # str_time = time.strftime("%Y-%m-%d %H:%M:%S", time_struct) str_time = get_utc_now() with MysqlTools().session_scope() as session: template_info = session.query(InstantGameTemplateModel). \ filter(InstantGameTemplateModel._id == template_id).first() if template_info is None: self.return_error(50001) if int(template_info.need_ceiling) < int(template_info.need_floor): self.return_error(40009) need = int(need) * template_info.reward_quantity digital_instance_model = InstantGameInstanceModel( template_id=template_id, game_serial=game_serial, game_title=template_info.game_title, bet_token=template_info.bet_token, bet_unit=template_info.bet_unit, support_token=template_info.support_token, reward_token=template_info.reward_token, reward_quantity=template_info.reward_quantity, handling_fee=template_info.handling_fee, experience=template_info.experience, merge_threshold=template_info.merge_threshold, game_describe=game_describe, release_time=str_time, status=0, need=int(need), release_type=0, chain_status=0) session.add(digital_instance_model) # session.flush() session.commit() return {"status": True}
def get_instant_result(self, part_in_id): with MysqlTools().session_scope() as session: part_in_info = session.query(ParticipateInModel). \ filter(ParticipateInModel._id == part_in_id).first() if part_in_info is None: self.return_error(40016) pattern = re.compile(r'[\[\]\s]') award_numbers_list = part_in_info.award_numbers indiana_numbers = pattern.sub('', award_numbers_list).split(',') number_list = [] is_win = False for i in indiana_numbers: if i == part_in_info.win_number: status = True else: status = False number_list.append({'number': i, 'is_win': status}) if part_in_info.win_number in indiana_numbers: is_win = True return { 'is_win': is_win, 'indiana_numbers': number_list, 'win_number': part_in_info.win_number, 'created_at': str(part_in_info.created_at), 'received_time': timestamp_to_str(str_to_timestamp(part_in_info.received_time), format_style="%Y-%m-%d %H:%M:%S"), 'block_no': part_in_info.block_no, 'bet_hash': part_in_info.bet_hash, }
def check_and_update_tx_flag(self, eth_tx_model, confirm_last_err_days): today = get_day_datetime() with MysqlTools().session_scope() as session: for tx in eth_tx_model: update_time = get_datetime_from_str(str(tx.update_at)) d_val = days_diff(update_time, today) if d_val > confirm_last_err_days: tx.listen_flag = _ZERO record_no = tx.record_no # 更改 提现流水 单笔 状态失败 withdraw_order_record = self.get_foreign_withdraw_order_record(session, record_no) if withdraw_order_record: withdraw_order_record.withdraw_status = self.withdraw_fail if tx.withdraw_type in self.account_withdraw_type_list: # 更改 批量提现流水 单笔 状态部分失败 multi_withdraw_record = self.get_foreign_multi_withdraw_order_record(session, withdraw_order_record.relate_flow_no) if multi_withdraw_record: multi_withdraw_record.withdraw_status = self.withdraw_part_success elif tx.withdraw_type in self.gather_withdraw_type_list: # 更改 归集操作流水 单笔 状态部分失败 gather_record = self.get_foreign_gather_record(session, withdraw_order_record.relate_flow_no) if gather_record: gather_record.gather_status = self.withdraw_part_success session.commit() # 如果是用户提现或者中奖 代码待更改 # if tx.withdraw_type in self.account_withdraw_type_list: # listening_value_ether = get_decimal("0") # listening_gas_ether = get_decimal("0") # # 告诉账户 提现失败 # do_withdraw_result = WalletCallbackService.withdraw_notify_callback(session, withdraw_order_record.req_no, \ # withdraw_order_record.order_no, self.callback_account_withdraw_fail, listening_value_ether, listening_gas_ether, withdraw_remain_fee) # withdraw_order_record.do_withdraw_result = do_withdraw_result return True
def manual_creat_robot(self, dic): count = 0 number = int(dic.get('number', "0")) if number <= 0: return with MysqlTools().session_scope() as session: name_list = session.query(RobotInfoLibModel). \ filter(RobotInfoLibModel.uid == ''). \ limit(number).all() # while number > 0: # print('name_==-=-=', name_list[number - 1].name) # number -= 1 while number > 0: count += 1 model = RobotAccountModel() model.nick_name = name_list[number - 1].name, model.score = dic.get('score', 0), model.id_card = dic.get('id_card', ''), model.source = int(dic.get('source', '1')), model.avatar = dic.get('avatar', ''), model.user_mobile = dic.get('user_mobile', ''), model.email = dic.get('email', ''), model.mobile_country_code = dic.get('mobile_country_code', ''), model.user_name = dic.get('user_name', 'user_name'), model.status = dic.get("status", 0), session.add(model) name_list[number - 1].uid = 1 # print('robot_name==', model.nick_name) number -= 1 if count == 100: session.flush() count = 0 session.commit() return True
def createNumbers(self, dic): game_serial = dic.get("game_serial", "") total = dic.get("total", 0) with MysqlTools().session_scope() as session: model = session.query(GameNumbersSetModel).filter( GameNumbersSetModel.game_serial == game_serial).first() if model: return False i = 0 while total > 0: session.add( GameNumbersSetModel( game_serial=game_serial, number=total, )) i += 1 if i == 100: session.commit() i = 0 total -= 1 session.commit() return True
from pathlib import Path from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig sys.path.append(str(Path(__file__).resolve().parent.parent)) from tools.mysql_tool import MysqlTools from models import base_model from models import __alembic__ __alembic__.call_dynamic() config = context.config fileConfig(config.config_file_name) connect_string = MysqlTools().get_connect_string() config.set_main_option('sqlalchemy.url', connect_string) target_metadata = base_model.BaseModel.metadata def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
class TokenSyncBlockEosManualScript(object): ec = None sync_success = _ONE sync_fail = _ZERO eos_coin_id = _COIN_ID_EOS slog = Slog("token_sync_block_eos_script") mysql_tool = MysqlTools() wait_lottery_dict = {} def __init__(self): self.ec = TokenNodeConfModel.get_eos_node_script( script_unit=_ZERO_S) # 获取eos connect连接 # pass def get_local_block_num(self): """ 获取本地区块的高度 :return: """ with self.mysql_tool.session_scope() as session: f_filter = { "status": self.sync_success, "coin_id": self.eos_coin_id } local_block = session.query(SyncBlockModel).filter_by( **f_filter).first() if not local_block: raise Exception( "Mysql database SyncBlockModel lacks configuration data") local_block_num = local_block.block_no return local_block_num def get_remote_block_num(self): """ 获取远端节点的最新区块高度 :return: """ remote_block = self.ec.http_get_latest_block() remote_block_num = remote_block.get("block_num", "") if not remote_block_num: raise Exception("Remote eos node has error") return remote_block_num def async_block_multi(self, begin=None, end=None, sync_block_num_list=None): block_data_dict = {} thread_list = [] if not sync_block_num_list: for j in range(begin, end): t = threading.Thread(target=self._get_block_detail, args=(block_data_dict, j)) t.setDaemon(True) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() else: for j in sync_block_num_list: t = threading.Thread(target=self._get_block_detail, args=(block_data_dict, j)) t.setDaemon(True) thread_list.append(t) for t in thread_list: t.start() for t in thread_list: t.join() return block_data_dict def _get_block_detail(self, block_data_dict, temp_remote_block_num): temp_insert_block_data = self.ec.http_get_block_detail( temp_remote_block_num) block_data_dict[str(temp_remote_block_num)] = temp_insert_block_data def sync_block(self, local_block_num, remote_block_num, interval=8): """ 同步区块,默认每8个块创建一个session scope,防止长连接 同步到SyncEosModel 同步到SyncBlockModel :param local_block_num: 本地block num :param remote_block_num: 远程block num :param interval: 创建MySQL链接的块数间隔 :return: """ for i in range(local_block_num + 1, remote_block_num, interval): temp_remote_block_num = i + interval if temp_remote_block_num > remote_block_num: temp_remote_block_num = remote_block_num sync_eos_model_list = [] temp_last_sync_block_no = None temp_last_sync_block_hash = "" # 调用协程读取 block_data_dict = self.async_block_multi(i, temp_remote_block_num) btime = time.time() with self.mysql_tool.session_scope() as session_select: for block_no_item in range(i, temp_remote_block_num): temp_last_sync_block_no = block_no_item temp_insert_block_data = block_data_dict.get( str(block_no_item), {}) if not temp_insert_block_data: time_stamp_decimal = get_decimal(block_no_item, digits=3) * -1 temp_last_sync_block_hash = "" eos_model = SyncEosModel( block_num=int(block_no_item), time_stamp_decimal=time_stamp_decimal, status=self.sync_fail) sync_eos_model_list.append(eos_model) else: time_stamp = temp_insert_block_data.get( "timestamp", "") time_stamp_decimal = get_decimal( str_to_timestamp(time_stamp), digits=3) temp_last_sync_block_hash = temp_insert_block_data.get( "id") eos_model = SyncEosModel( block_num=temp_insert_block_data.get("block_num"), block_hash=temp_last_sync_block_hash, time_stamp=time_stamp, time_stamp_decimal=time_stamp_decimal, previous=temp_insert_block_data.get("previous"), status=self.sync_success) sync_eos_model_list.append(eos_model) self.slog.info("sync block_num:", temp_last_sync_block_no, "sync block_hash:", temp_last_sync_block_hash) if sync_eos_model_list: session_select.add_all(sync_eos_model_list) try: session_select.query(SyncBlockModel).filter( SyncBlockModel.coin_id == self.eos_coin_id).update({ SyncBlockModel.block_no: temp_last_sync_block_no, SyncBlockModel.block_hash: temp_last_sync_block_hash }) session_select.commit() except Exception as e: self.slog.error(str(e)) print("insert time " + str(time.time() - btime)) return True def process_game_list(self): f_filters = {"block_hash": "", "status": _ZERO} with self.mysql_tool.session_scope() as session: base_block_num_not_have_model_list = session.query( GameGetLotteryBlockInfoEosModel).filter( GameGetLotteryBlockInfoEosModel.base_block_num < _ZERO ).all() if base_block_num_not_have_model_list: for base_block_num_not_have_model in base_block_num_not_have_model_list: base_time_stamp = base_block_num_not_have_model.base_time_stamp lottery_block_add = base_block_num_not_have_model.block_num confirm_block_add = base_block_num_not_have_model.confirm_block_num base_block = session.query(SyncEosModel).filter( SyncEosModel.time_stamp_decimal >= base_time_stamp ).order_by(SyncEosModel.block_num.asc()).first() if base_block and base_block.time_stamp_decimal - base_time_stamp <= _SIXTY: base_block_num = base_block.block_num base_block_num_not_have_model.base_block_num = base_block_num base_block_num_not_have_model.block_num = base_block_num + lottery_block_add base_block_num_not_have_model.confirm_block_num = base_block_num + lottery_block_add + confirm_block_add session.commit() wait_lottery_model_list = session.query( GameGetLotteryBlockInfoEosModel).filter_by(**f_filters).filter( GameGetLotteryBlockInfoEosModel.base_block_num > _ZERO ).all() if wait_lottery_model_list: wait_lottery_dict = {} wait_lottery_list = [] for lottery_info_model in wait_lottery_model_list: wait_lottery_dict[str( lottery_info_model.confirm_block_num)] = { "game_instance_id": lottery_info_model.game_instance_id, "block_num": lottery_info_model.block_num } wait_lottery_list.append( lottery_info_model.confirm_block_num) sync_eos_model_list = session.query(SyncEosModel).filter( SyncEosModel.block_num.in_(wait_lottery_list), SyncEosModel.status == self.sync_success).all() if sync_eos_model_list: for sync_eos_model in sync_eos_model_list: confirm_block_num = sync_eos_model.block_num game_instance_id = wait_lottery_dict[str( confirm_block_num)]["game_instance_id"] block_no = wait_lottery_dict[str( confirm_block_num)]["block_num"] lottery_eos_model = session.query(SyncEosModel).filter( SyncEosModel.block_num == block_no).first() if lottery_eos_model: block_hash = lottery_eos_model.block_hash sync_eos = self.update_sync_eos( session, block_no, block_hash) if sync_eos: block_hash = sync_eos["block_hash"] received_time = timestamp = sync_eos[ "time_stamp"] TokenSyncBlockEosScript.lottery_callback( session, game_instance_id, block_no, block_hash, timestamp, received_time) if str(confirm_block_num) in wait_lottery_dict: del wait_lottery_dict[str( confirm_block_num)] session.commit() self.wait_lottery_dict = wait_lottery_dict return True def update_sync_eos(self, session, block_num, block_hash): """ 开奖时,如果再次查询节点上的该区块,如果hash有变化,说明回滚,取最新区块详情,修改该区块 :param session: :param block_num: :param block_hash: :return: """ block_detail = self.ec.http_get_block_detail(block_num) if block_detail: remote_block_hash = block_detail.get("id", "") time_stamp = block_detail.get("timestamp", "") if remote_block_hash: if remote_block_hash != block_hash: sync_eos_model = session.query(SyncEosModel).filter( SyncEosModel.block_num == block_num).first() if sync_eos_model: time_stamp_decimal = get_decimal( str_to_timestamp(time_stamp), digits=3) previous = block_detail.get("previous", "") sync_eos_model.block_hash = remote_block_hash sync_eos_model.time_stamp = time_stamp sync_eos_model.time_stamp_decimal = time_stamp_decimal sync_eos_model.previous = previous sync_eos_model.status = self.sync_success self.slog.info("lottery block_num:", block_num, "lottery block_hash:", remote_block_hash) return { "block_hash": remote_block_hash, "time_stamp": time_stamp, } return {} @staticmethod def lottery_callback(session, game_instance_id, block_no, block_hash, timestamp, received_time): """ :param session: :param game_instance_id: :param block_no: :param block_hash: :param timestamp: :param received_time: :return: """ process_res = WalletEosService.lottery_callback( game_instance_id, block_no, block_hash, timestamp, received_time) session.query(GameGetLotteryBlockInfoEosModel).filter( GameGetLotteryBlockInfoEosModel.game_instance_id == game_instance_id).update({ GameGetLotteryBlockInfoEosModel.block_hash: block_hash, GameGetLotteryBlockInfoEosModel.time_stamp: timestamp, GameGetLotteryBlockInfoEosModel.status: process_res }) return True def work(self): # 1.查询已经同步的区块高度 local_block_num = self.get_local_block_num() # 2.查询当前节点的区块最新高度 remote_block_num = self.get_remote_block_num() # local_block_num, remote_block_num = 37657192, 37657202 # 3.遍历区块号,8个块创建一个session scope sync_res = self.sync_block(local_block_num, remote_block_num) return sync_res
def __init__(self): self.mysql_tool = MysqlTools() mysql_dev_conf = get_mysql_conf(env="dev") # mysql_dev_conf["host"] = "luckypark0121.cnzvcx1qv3xd.us-east-2.rds.amazonaws.com" self.mysql_dev_tool = MysqlTools(mysql_dev_conf)
def gather_record_all(self, user_name, from_address, operate_at_start, operate_at_end, withdraw_address, coin_id, confirm_at_start, confirm_at_end, withdraw_status, offset, limit): """ 归集操作记录详情 :param user_name: 用户名 :param from_address: 用户钱包地址 :param operate_at_start: 操作时间start :param operate_at_end: 操作时间end :param withdraw_address: 归集地址 :param coin_id: 币种 :param confirm_at_start: 结束时间start :param confirm_at_end: 结束时间end :param withdraw_status: 状态: 1-归集中, 2-成功, 3-失败 :param offset: 当前页数 :param limit: 每页条数 :return: """ u_filters = {} if user_name: u_filters["user_name"] = user_name f_filters = {} f_filters["withdraw_type"] = _TWO_S if from_address: f_filters["from_address"] = from_address if withdraw_address: f_filters["withdraw_address"] = withdraw_address if coin_id: f_filters["coin_id"] = coin_id if withdraw_status: f_filters["withdraw_status"] = withdraw_status if not operate_at_start: operate_at_start = "0000-00-00" else: operate_at_start = operate_at_start if not operate_at_end: operate_at_end = "2999-12-31" else: operate_at_end = operate_at_end if not confirm_at_start: confirm_at_start = "0000-00-00" else: confirm_at_start = confirm_at_start if not confirm_at_end: confirm_at_end = "2999-12-31" else: confirm_at_end = confirm_at_end with MysqlTools().session_scope() as session: g = session.query(ForeignWithdrawOrderRecordModel, UserAccountModel).filter_by( **f_filters).filter( ForeignWithdrawOrderRecordModel.created_at >= operate_at_start, ForeignWithdrawOrderRecordModel.created_at <= operate_at_end, ForeignWithdrawOrderRecordModel.confirm_at >= confirm_at_start, ForeignWithdrawOrderRecordModel.confirm_at <= confirm_at_end).outerjoin( UserAccountModel, ForeignWithdrawOrderRecordModel.account_id == UserAccountModel.account_id).filter_by(**u_filters) count = g.count() gather_list = g.order_by(desc(ForeignWithdrawOrderRecordModel._id)).limit( limit).offset(get_offset_by_page(offset, limit)) result_map = {} list = [] for g in gather_list: map = {} map["user_name"] = "" try: map["user_name"] = str(g.UserAccountModel.user_name) # 用户名 except: pass map["order_no"] = str(g.ForeignWithdrawOrderRecordModel.order_no) map["from_address"] = str(g.ForeignWithdrawOrderRecordModel.from_address) # 用户钱包地址 map["created_at"] = str(g.ForeignWithdrawOrderRecordModel.created_at) # 操作时间 map["coin_id"] = str(g.ForeignWithdrawOrderRecordModel.coin_id) # 归集币种 map["withdraw_amount"] = decimal_to_str(g.ForeignWithdrawOrderRecordModel.withdraw_amount) # 数量 map["withdraw_fee"] = decimal_to_str(g.ForeignWithdrawOrderRecordModel.withdraw_fee) # 手续费 map["confirm_at"] = str(g.ForeignWithdrawOrderRecordModel.confirm_at) # 结束时间 map["withdraw_address"] = str(g.ForeignWithdrawOrderRecordModel.withdraw_address) # 归集地址 map["withdraw_status"] = str(g.ForeignWithdrawOrderRecordModel.withdraw_status) list.append(map) result_map["count"] = count result_map["list"] = list return result_map
def gather_address_record(self, sub_public_address, relevant_address, transfer_at_start, transfer_at_end, operation_type, offset, limit): """ 归集地址流水 :param sub_public_address: 地址(必填) :param relevant_address: 相关地址 :param transfer_at_start: 操作时间start :param transfer_at_end: 操作时间end :param operation_type: 操作类型:1-收款, 2-出款[提现类型: 0-用户提现, 1-用户中奖, 2-归集, 3-归集转归集] :param offset: 当前页数 :param limit: 每页条数 :return: """ if not transfer_at_start: transfer_at_start = "0000-00-00" else: transfer_at_start = transfer_at_start if not transfer_at_end: transfer_at_end = "2999-12-31" else: transfer_at_end = transfer_at_end with MysqlTools().session_scope() as session: coin_id = _ZERO_S gather = session.query(WalletBtcGatherModel).filter( WalletBtcGatherModel.sub_public_address == sub_public_address).first() if gather is None: coin_id = _SIXTY_S f = session.query(ForeignWithdrawOrderRecordModel, UserAccountModel).filter( ForeignWithdrawOrderRecordModel.transfer_at >= transfer_at_start, ForeignWithdrawOrderRecordModel.transfer_at <= transfer_at_end) if relevant_address: f = f.filter(or_( ForeignWithdrawOrderRecordModel.from_address == relevant_address, ForeignWithdrawOrderRecordModel.withdraw_address == relevant_address)) if not operation_type: # 全部 fw = f.outerjoin( UserAccountModel, ForeignWithdrawOrderRecordModel.account_id == UserAccountModel.account_id) elif operation_type == _ONE_S: # 收款 fw = f.filter( ForeignWithdrawOrderRecordModel.withdraw_type == _TWO_S).outerjoin( UserAccountModel, ForeignWithdrawOrderRecordModel.account_id == UserAccountModel.account_id) elif operation_type == _TWO_S: # 出款 fw = f.filter( ForeignWithdrawOrderRecordModel.withdraw_type == _ZERO_S).outerjoin( UserAccountModel, ForeignWithdrawOrderRecordModel.account_id == UserAccountModel.account_id) count = fw.count() record_list = fw.order_by(desc(ForeignWithdrawOrderRecordModel.transfer_at)).limit( limit).offset(get_offset_by_page(offset, limit)) result_list = [] for r in record_list: map = {} map["order_no"] = str(r.ForeignWithdrawOrderRecordModel.order_no) map["user_name"] = "" try: map["user_name"] = str(r.UserAccountModel.user_name) except: pass map["transfer_at"] = str(r.ForeignWithdrawOrderRecordModel.transfer_at) map["withdraw_amount"] = decimal_to_str(r.ForeignWithdrawOrderRecordModel.withdraw_amount) map["withdraw_fee"] = decimal_to_str(r.ForeignWithdrawOrderRecordModel.withdraw_fee) map["operation_type"] = "" map["relevant_address"] = "" withdraw_type = str(r.ForeignWithdrawOrderRecordModel.withdraw_type) from_address = str(r.ForeignWithdrawOrderRecordModel.from_address) withdraw_address = str(r.ForeignWithdrawOrderRecordModel.withdraw_address) if withdraw_type == _ZERO_S: # 提现 map["operation_type"] = "2" # 出款 map["relevant_address"] = withdraw_address elif withdraw_type == _TWO_S: # 归集 map["operation_type"] = "1" # 收款 map["relevant_address"] = from_address map["operation_user"] = str(r.ForeignWithdrawOrderRecordModel.operation_user) result_list.append(map) result_map = {} result_map["count"] = str(count) result_map["list"] = result_list return result_map