def add_user(**kwargs): user = User() user.u_name = kwargs.get('u_name') user.u_passwd = kwargs.get('u_passwd') user.u_email = kwargs.get('u_email') user.u_sex = kwargs.get('u_sex') user.u_mobilephone = kwargs.get('u_mobilephone') dbsession.add(user) dbsession.commit() logging.debug('SVC_userinfo 注册用户:%s', user) # 处理用户资产信息 user_money = user.u_money user_mv = 0 uid = user.id sql = 'insert into tb_user_assets ' \ 'set user_id=%s, user_money=%.2f, user_mv=%.2f' \ % (uid, user_money, user_mv) dbsession.execute(sql) dbsession.commit() return user
def get_stock_list(uid, cid, page=1, lmt=100): """ 列出用戶的持股信息,默認100條 return: a list, :param uid: :param cid: :param page: :param lmt: """ if not all((uid, cid)): logging.error("uid err", uid) raise Exception("parameter err") sql = "select * from tb_user_contest_positions where user_id = %s and stock_count > 0 and contest_id=%d" \ " order by updated_at desc" \ " limit %d, %d" % (uid, cid, (page-1)*lmt, lmt) result = [] try: query_res = dbsession.execute(sql) dbsession.commit() query_res = query_res.fetchall() except Exception as e: dbsession.rollback() logging.error(e) raise # table column headers = ("id", "created_at", "updated_at", "deleted_at", "uid", "name", "code", "count", "price", "freeze", "cid") for item in query_res: dct = dict(zip(headers, item)) tm = dct['created_at'] dct['created_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['updated_at'] dct['updated_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['deleted_at'] dct['deleted_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None dct['price'] = float(dct['price']) dct['freeze'] = float(dct['freeze']) result.append(dct) return result
def list_orders(uid, cid, type=None, page=1, count=40, finished=None): """ 获取订单列表. :param uid: 用户id :param cid: 比赛id (0为非比赛委托单) :param page: :param count: :param type: 交易类型 TRADE_TYPE_NONE = iota TRADE_TYPE_BUY # 买入 TRADE_TYPE_SALE # 卖出 :return: """ uid = (int)(uid) cid = (int)(cid) page = (int)(page) count = (int)(count) sql = 'select * from tb_orders where ' where_cond = [ 'user_id=%d' % uid, 'contest_id=%d' % cid, ] order_by = ' order by updated_at desc ' limit_sql = ' limit %d, %d ' % ((page - 1) * count, count) if type is not None: # 交易类型过滤 where_cond.append('trade_type=%d' % type) if finished == 'finished': where_cond.append('order_status!=0') elif finished == 'unfinished': where_cond.append('order_status=0') # 执行sql sql = sql + ' and '.join(where_cond) + \ order_by + limit_sql logging.debug('sql: %s' % sql) raws = dbsession.execute(sql).fetchall() dbsession.commit() if not raws: dbsession.rollback() return [] # table colume colums = ('id', 'submit_time', 'updated_at', 'deleted_at', 'uid', 'name', 'code', 'price', 'amount', 'transfer_fee', 'brokerage', 'volume', 'trade_type', 'type', 'status', 'cid') result = [] for item in raws: dct = dict(zip(colums, item)) tm = dct['submit_time'] dct['submit_time'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['updated_at'] dct['updated_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['deleted_at'] dct['deleted_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None dct['price'] = float(dct['price']) dct['brokerage'] = float(dct['brokerage']) dct['transfer_fee'] = float(dct['transfer_fee']) dct['volume'] = float(dct['volume']) result.append(dct) return result
def revoke_order(uid, order_id, contest_id=0): """ 撤銷一個訂單: :param uid: 用戶id :param order_id: 訂單id號 :param contest_id: 比赛id, 0表示非比赛(代码耦合了) :return: """ if not isinstance(order_id, int): logging.error("id not a int object %s", id) raise Exception("參數錯誤") # recode = None # try: # recode = dbsession.query(TradeRecode).filter_by(id=id).filter_by(u_id=uid).one() # except NoResultFound as e: # logging.warning(e) # dbsession.rollback() # raise e # # except Exception as e: # logging.error(e) # dbsession.rollback() # raise e # # ## 判斷用記錄的狀態是否對 # if recode.t_status != 0: # logging.error("記錄的狀態不對, 不能撤銷該訂單: %s" %(recode.to_json()) ) # raise Exception("記錄的狀態不對, 不能撤銷該訂單") # # user = None # ### 取出用戶的數據,檢測是否餘額是否足夠 # try: # user = dbsession.query(User).filter_by(id=uid).one() # except NoResultFound as e: # 包括了NoResultFound異常, 用戶的數據都找不到了,還處理個毛綫 # logging.error(e) # raise e # except Exception as e: # dbsession.rollback() # logging.error(e) # raise e # # if recode.t_type == 1: # 買入 # user.u_money = (float)(user.u_money) + (float)(recode.t_volume) + (float)(recode.t_charge) # 用戶的錢返還回去 # elif recode.t_type == 2: # 賣出 退還凍結的手續費 # user.u_money = (float)(user.u_money) + (float)(recode.t_charge) # # recode.t_status = 2 # 記錄狀態設置為撤單 # try: # dbsession.merge(recode) # dbsession.merge(user) # dbsession.commit() # except Exception as e: # dbsession.rollback() # logging.error(e) # raise e # 检测订单数据 sql = 'select * from tb_orders where user_id=%d and id=%d ' % ( uid, order_id) try: result = dbsession.execute(sql).fetchall() dbsession.commit() if not result: raise Exception("订单数据不存在. order_id: %d, user_id: %d" % (order_id, uid)) except Exception as e: dbsession.rollback() logging.error("数据库错误:%s", e) raise # 拼接数据 colums = ("id", "created_at", "updated_at", "deleted_at", "uid", "name", "code", "price", "count", "transfer_fee", "brokerage", "freeze_amount", "trade_type", "type", "status", "contest_id") record = dict(zip(colums, result[0])) # 检查订单状态 # enum: # ORDER_STATUS_TBD = iota # ORDER_STATUS_FINISH # ORDER_STATUS_REVOKE if record['status'] != 0: raise Exception("撤销订单失败,订单状态不对.") # 构造请求,发送到交易服务器 now = str(time.time()) sign = ''.join(sorted(str(uid) + now + config.RPC_REQUEST_SALT)) md5 = hashlib.md5() md5.update(sign.encode()) sign = md5.hexdigest() request_body = { "method": "orderService.RevokeOrder", "params": [{ "user_id": uid, "sign": sign, "order_id": order_id, "req_time": now, "contest_id": contest_id, }] } try: resp = requests.post(config.RPC_SERVICE_URL, json=request_body, headers={'Content-Type': 'application/json'}) except Exception as e: raise if not resp.ok: raise Exception("请求失败, 请稍后再试!") content = resp.content.decode() content = json.loads(content)['result'] if content['ret_code'] != 0: raise Exception(content['err_msg']) # 添加用户动态. data = { 'uid': record['uid'], 'order_id': record['id'], 'code': record['code'], 'name': record['name'], 'contest_id': record['contest_id'], 'type': record['type'], } try: SVC_Dongtai.add_dongtai_revoke(uid, json.dumps(data)) except Exception as e: logging.error(e) raise e
def get_recode_list(uid, type=0, page=1, count=100, cid=0, finished=None): """ 獲取用戶的交易記錄: 已成交 :param uid: :param type: 0:所有的 1買入 2 賣出 :param page: 頁 :param count: 每頁加載數據量 :param cid: 比赛id :param finished: 已完成 :return: a list container all objects """ if not all([ isinstance(type, int), isinstance(page, int), isinstance(count, int) ]): logging.error("parameter type err:") raise Exception("parameter type err:") sql = "select * from tb_trade_details " where = " where " limit = " limit %d, %d " % ((page - 1) * count, count) # where 条件 where_cond = ["user_id=%d" % uid, "contest_id=%d" % cid] try: if type != 0: where_cond.append("trade_type=%d" % type) if finished == 'finished': where_cond.append("order_status != 0") elif finished == 'unfinished': where_cond.append("order_status = 0") # 组装where条件 where += " and ".join(where_cond) sql += where + " order by updated_at desc " + limit # 执行sql logging.debug(sql) result = dbsession.execute(sql).fetchall() except Exception as e: dbsession.rollback() logging.error(e) raise res = [] if result is None: return res # 组装数据 colums = ("id", "submit_time", "updated_at", "deleted_at", "order_id", "uid", "name", "code", "price", "amount", "type", "charge", "cid") for item in result: dct = dict(zip(colums, item)) dct['volume'] = round( (float)(dct['price']) * (float)(dct['amount']), 2) tm = dct['submit_time'] dct['submit_time'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['updated_at'] dct['updated_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None tm = dct['deleted_at'] dct['deleted_at'] = tm.strftime( "%Y-%m-%d %H:%M:%S") if tm else None dct['price'] = float(dct['price']) dct['charge'] = float(dct['charge']) res.append(dct) logging.debug(res) return res