Exemple #1
0
 def stat_all(self):
     """统计某天订单相关数据"""
     price, order_count = self.stat_price_count_for_all()
     total_price, total_order_count = self.stat_total_price_count_for_all()
     member_count = Member.stat_total_by_date(self.one_date)
     total_member_count = Member.stat_total(self.date_to)
     access = AppAccessLog.stat_total_by_date(self.one_date)
     total_access = AppAccessLog.stat_total(self.date_to)
     # StatAllDaily.create(
     #     date=self.one_date,
     #     price=price,
     #     total_price=total_price,
     #     order_count=order_count,
     #     total_order_count=total_order_count,
     #     member_count=member_count,
     #     total_member_count=total_member_count,
     #     access=access,
     #     total_access=total_access,
     #     commit=True
     # )
     # 测试数据
     StatAllDaily.create(date=self.one_date,
                         price=Decimal(f'{randint(1, 999)}.34'),
                         total_price=Decimal(f'{randint(1, 9999)}.34'),
                         order_count=randint(1, 999),
                         total_order_count=randint(1, 9999),
                         member_count=randint(1, 999),
                         total_member_count=randint(1, 9999),
                         access=randint(1, 999),
                         total_access=randint(1, 9999),
                         commit=True)
     return True
def createTeam():
    if session.get("id") is None:
        return redirect("/user/login")
    name = session.get("name")
    if request.method == "GET":
        return render_template('student_templates/createTeam.html', name=name)
    else:
        name = request.form.get("name")
        userId = session.get("id")
        course = CourseAndStudent.query.filter(
            CourseAndStudent.studentId == userId).first()
        with db.auto_commit():
            team = Team()
            team.courseId = course.CourseId
            team.TeamName = name
            team.isFinish = 0
            db.session.add(team)
            team = Team.query.filter(
                Team.courseId == course.CourseId).order_by(
                    Team.TeamNumber.desc()).first()

            member = Member()
            member.studentId = userId
            member.teamId = team.TeamNumber
            member.votenum = 0

            db.session.add(member)

        return redirect('/student/display')
Exemple #3
0
 def get(self):
     result = []
     len_sysonline = Member().getAll()[0]
     len_sysonline = dict(len_sysonline)
     for keys, values in len_sysonline.items():
         args = {}
         args['id'] = keys
         args['numbers'] = values
         result.append(args)
     results = {"success": True, "data": result}
     return results
Exemple #4
0
 def get(self, id):
     sysonline = SysadminOnline().getdate(id)
     bank = SystemBankAccount().getdate(id)
     # len_sysonline = Member().getLen(id)[0][0][0]
     len_sysonline = Member().getLen(id)[0]
     len_sysonline = dict(len_sysonline)
     sysonline = dict(sysonline[0])
     bank = dict(bank[0])
     result_sysonline = []
     sysonline_args = {}
     result_bank = []
     bank_args = {}
     result_numbers = []
     numbers_args = {}
     for key, values in sysonline.items():
         result_one = {}
         result_one['id'] = key
         result_one['names'] = values
         result_sysonline.append(result_one)
     sysonline_args['sysonline'] = result_sysonline
     for key, values in bank.items():
         result_one = {}
         result_one['id'] = key
         result_one['names'] = values
         result_bank.append(result_one)
     bank_args['bank'] = result_bank
     keys = []
     result_one = {}
     for key, values in len_sysonline.items():
         keys.append(key)
         if 1 not in keys:
             result_one['numbers1'] = 0
             result_numbers.append(result_one)
         if 0 not in keys:
             result_one['numbers0'] = 0
             result_numbers.append(result_one)
         if 9 not in keys:
             result_one['numbers9'] = 0
             result_numbers.append(result_one)
         if 10 not in keys:
             result_one['numbers10'] = 0
             result_numbers.append(result_one)
         if 11 not in keys:
             result_one['numbers11'] = 0
             result_numbers.append(result_one)
         numbers = 'numbers{}'.format(key)
         result_one[numbers] = values
     result = {
         "success": True,
         "data": [sysonline_args, bank_args, result_one]
     }
     return result
Exemple #5
0
 def create_default_member():
     from app.models import db
     from app.models.member import Member
     member = Member()
     member.type = 9
     member.username = '******'
     member.password = '******'
     try:
         db.session.add(member)
         db.session.commit()
     except:
         db.session.rollback()
         db.session.remove()
Exemple #6
0
def verify_token(token=None):
	from flask import current_app
	if not token:
# 		user = User.query.filter(User.username == 'default').first()
# 		g.current_user = Object()
# 		g.current_user.id = user.id
# 		g.current_user.username = user.username
#  
# 		member = Member.query.filter(Member.username == 'KK').first()
# 		g.current_member = Object()
# 		g.current_member.id = member.id
# 		g.current_member.username = member.username
		return False
	user = User.verify_token(token)
	g.current_user = None
	if user:
		g.current_user = Object()
		g.current_user.id = user.id
		g.current_user.username = user.username

	member = Member.verify_token(token)
	g.current_member = None
	if member:
		g.current_member = Object()
		g.current_member.id = member.id
		g.current_member.username = member.username
		g.current_member.isTsetPLay = member.isTsetPLay
		g.current_member.auto_change = member.auto_change
	return g.current_user is not None or g.current_member is not None
Exemple #7
0
def login():
    resp = {'code':1,'msg':'成功','data':{}}

    data = request.values
    # print(data)
    code = data.get('code') if 'code' in data else ''
    nickname = data.get('nickName') if 'nickName' in data else ''
    avatar = data.get('avatarUrl') if 'avatarUrl' in data else ''
    gender = data.get('gender') if 'gender' in data else 1

    # print(nickname)

    if not code or len(code) <1:
        resp['code'] = -1
        resp['msg'] = 'code无效'
        return jsonify(resp)
    openid = MemberService.getOpenid(code)
    oauthmemberbind = OauthMemberBind.query.filter_by(openid=openid).first()
    if not oauthmemberbind:
        member = Member(nickname=nickname,gender=gender,avatar=avatar,salt=MemberService.getSalt())
        db.session.add(member)
        db.session.commit()

        oauthmemberbind = OauthMemberBind(openid=openid,type=1,client_type='weixin',extra='',member_id=member.id)
        db.session.add(oauthmemberbind)
        db.session.commit()
    member = Member.query.get(oauthmemberbind.member_id)
    token = '%s#%s'%(MemberService.geneAuthCode(member),member.id)
    resp['data'] = {'token': token}
    return jsonify(resp)
Exemple #8
0
    def post(self):
        try:
            username = request.json['username']
            password = request.json['password']
        except:
            abort(400)

        member = Member.query.filter(Member.username == username).first()
        if not member or not member.verify_password(password):
            abort(401)
        if member.status == 0:
            return jsonify({
                'success': False,
                'errorCode': 403,
                'errorMsg': '该用户已被停用'
            })

        g.current_member = Object()
        g.current_member.id = member.id
        g.current_member.username = member.username
        g.current_member.isTsetPLay = member.isTsetPLay
        return jsonify({
            'success': True,
            'token': Member.generate_token(member),
            'currentMember': {
                'id': g.current_member.id,
                'username': g.current_member.username
            }
        })
Exemple #9
0
def get_member():
    with Student.auto_commit():
        member = Member("Mario", 3.0, '*****@*****.**', 'A', '123456')
        # 数据库的insert操作
        Student.session.add(member)

    return 'hello member'
def sign_up():
    username = request.values.get('userName')
    pwd = request.values.get('pwd')
    nickname = request.values.get('nickname')
    sex = request.values.get('sex')
    mobile = request.values.get('mobile')
    birthday = request.values.get('birthday')
    portrait = request.values.get('portrait')

    with db.Session() as session:

        rs = session.query(Member.username).filter(
            db.and_(Member.username == username)).all()

        if len(rs) != 0:
            return jsonify(dict(statusCode="401"))
        else:
            session.add(
                Member(
                    username=username,
                    password=pwd,
                    nickname=nickname,
                    sex=Member.SEX_FEMALE if sex == "F" else Member.SEX_MALE,
                    mobile=mobile,
                    birthday=datetime.datetime.strptime(birthday, "%Y-%m--%d"),
                    portrait=portrait,  # 应当是一个图片
                    created_dt=datetime.datetime.now(),
                    valid=Member.VALID_VALID))
            session.add(
                MemberLog(username=username, action=MemberLog.ACTION_INSERT))
            return jsonify(dict(statusCode="200", sessionKey=""))
Exemple #11
0
def join():
    if session.get("id") is None:
        return redirect("/user/login")
    name = session.get("name")
    teamId = request.args.get("id")
    team = Team.query.filter_by(TeamNumber=teamId).first()
    #查询该成员是否满员,如果满员禁止加入

    if team.isFinish == 1:
        return render_template('student_templates/viewinvitation.html',
                               name=name,
                               message="该小组满员了")

    courseId = CourseAndStudent.query.filter_by(
        studentId=session.get("id")).first().CourseId
    totalNum = Course.query.filter_by(CourseId=courseId).first().numofmember
    with db.auto_commit():
        memberr = Member()
        memberr.teamId = teamId
        memberr.studentId = session.get("id")
        memberr.votenum = 0
        db.session.add(memberr)

    countMember = Member.query.filter_by(teamId=teamId).count()
    if totalNum == countMember:

        team.isFinish = 1
        db.session.commit()

    invitelst = Invite.query.filter_by(inviteId=session.get("id")).delete()

    #检查该小组是否满员,满员则设置为isFInish=1
    #如果成功加入小组,则清除邀请信息
    invitelst = Invite.query.filter(Invite.inviteId == session.get("id"))

    result = []
    for i in invitelst:
        dict1 = {}
        studentname = Student.query.filter(
            Student.id == i.inviteeId).first().name
        dict1['info'] = studentname
        dict1['teamId'] = i.teamId
        result.append(dict1)

    return render_template('student_templates/viewinvitation.html',
                           name=name,
                           result=result)
Exemple #12
0
    def get(self, member_id):
        try:
            find_member = Member.objects(id=member_id).first()
            member_detail = MemberSchema().dump(find_member)
        except ValidationError as err:
            return err

        return jsonify(member_detail), 200
Exemple #13
0
    def delete(self, member_id):
        try:
            find_member = Member.objects(id=member_id).first()
            find_member.soft_delete()
        except ValidationError as err:
            return err

        return jsonify(message='회원탈퇴가 정상처리 되었습니다.'), 200
Exemple #14
0
    def index(self):
        try:
            members = Member.objects(deleted=False).order_by(
                '+created_time', '-email')
            result = SimpleMemberSchema().dump(members, many=True)
        except ValidationError as err:
            return err

        return jsonify(result), 200
Exemple #15
0
def get():
    form = MemberLoginForm().validate_for_api()
    openid = WxHelper.get_openid(form.code.data)
    if openid:
        member = Member.get(one=True, openid=openid)
        if not member:
            member = Member.create(openid=openid,
                                   nickName=form.nickName.data,
                                   avatarUrl=form.avatarUrl.data,
                                   gender=form.gender.data,
                                   country=form.country.data,
                                   province=form.province.data,
                                   city=form.city.data,
                                   commit=True)
        access_token, refresh_token = get_member_tokens(member)
    else:
        raise WxCodeException()

    return jsonify({
        'access_token': access_token,
        'refresh_token': refresh_token
    })
Exemple #16
0
    def post(self):
        try:
            form = JoinSchema().load(json.loads(request.data))

            if Member.objects(email=form['email']).first():
                return jsonify(message='이미 가입된 아이디 입니다.'), 409

            form['password'] = bcrypt.hashpw(form['password'].encode('utf-8'),
                                             bcrypt.gensalt()).decode('utf-8')
            form.save()
        except ValidationError as err:
            return jsonify(err.messages), 422

        return jsonify(message='회원가입이 완료되었습니다.'), 200
Exemple #17
0
def get_current_member():
    identity = get_jwt_identity()
    if identity['scope'] != 'zcx':
        raise AuthFailed()
    remote_addr = identity.get('remote_addr')
    if remote_addr and remote_addr != request.remote_addr:
        raise AuthFailed()
    # token is granted , member must be exit
    # 如果token已经被颁发,则该用户一定存在
    member = Member.get(id=identity['uid'], one=True)
    if member is None:
        raise NotFound(msg='会员不存在')
    if not member.is_active:
        raise AuthFailed(msg='您目前处于未激活状态,请联系超级管理员')
    return member
Exemple #18
0
def login():
    ctx = {'code': 1, 'msg': "成功",'data': {}}
    nickname = request.form.get("nickname")


    gender = request.form.get("gender")
    avatarurl = request.form.get("avatarur")
    code = request.form.get("code")

    if not code or len(code) <1:
        ctx['code']  = -1
        ctx['msg'] = '获取openid出错'
        return jsonify(ctx)
    opneid  =MemberService.getOpenId(code)

    if not opneid:
        ctx['code'] = -1
        ctx['msg'] = 'code无效'
        return jsonify(ctx)
    app_id = current_app.config.get('APP_ID')
    app_secret= current_app.config.get('app_secret')
    ctx['data']['nickname'] = nickname

    url =  'https://api.weixin.qq.com/sns/jscode2session?appid=%swx4503a4f6af272145&secret=%s&js_code=%s&grant_type=authorization_code'%(code,app_id,app_secret)
    response = request.get(url)
    opneid = response.json().get('openid')

    oauthmemberbind = OauthMemberBind.query.filter_by(opneid=opneid).first()
    #存数据库

    if not oauthmemberbind:
        member = Member()
        member.nickname = nickname
        member.avatar =avatarurl
        member.gender =gender
        member.salt =MemberService.getSalt()
        db.session.add(member)
        db.session.commit()

        oauthmemberbind=  OauthMemberBind
        oauthmemberbind.openid = opneid
        oauthmemberbind.client_type = 'wx'
        oauthmemberbind.type = 1
        oauthmemberbind.member_id = member.id
        db.session.add(oauthmemberbind)
        db.session.commit()
        token = MemberService.geneAuthCode(member)
        ctx['data']['token'] = '%s#%s'%(member.id,token)
        return jsonify(ctx)

    else:
        member = Member.query.get(oauthmemberbind.member_id)
        token = MemberService.geneAuthCode(member)
        ctx['data']['token'] = '%s#%s' % (member.id, token)
        return jsonify(ctx)
Exemple #19
0
    def login(self):
        form = LoginSchema().load(json.loads(request.data))

        find_member = Member.objects(email=form.get('email')).first()

        if not find_member:
            return jsonify(message='존재하지 않는 이메일 입니다.'), 422
        if not find_member.check_password(form.get('password')):
            return jsonify(message='비밀번호가 틀렸습니다.'), 422

        find_member.update_last_login_time()

        token = jwt.encode({"member_id": dumps(find_member.id)},
                           current_app.config['SECRET'],
                           current_app.config['ALGORITHM'])

        return jsonify(token.decode('utf-8')), 200
Exemple #20
0
def login():
    res = {'code': 1, 'msg': '成功', 'data': {}}
    nickName = request.form.get('nickName')
    avataUrl = request.form.get('avataUrl')
    gender = request.form.get('gender')
    code = request.form.get('code')
    print(nickName, avataUrl, gender, code)

    if len(code) < 1:
        res['code'] = -1
        res['msg'] = 'code有误'
        return jsonify(res)

    if not all([nickName, avataUrl, gender, code]):
        res['code'] = -1
        res['msg'] = '参数有误'
        return jsonify(res)

    # 获取open_id
    open_id = memberService.getOpenid(code)
    if not open_id:
        res['code'] = -1
        res['msg'] = '获取open_id出错'
        return jsonify(res)

    #存数据库去重
    oauthMemberBind = OauthMemberBind.query.filter_by(openid=open_id).first()
    if not oauthMemberBind:
        member = Member()
        member.nickname = nickName
        member.avatar = avataUrl
        member.gender = gender
        member.salt = memberService.getSalt()

        db.session.add(member)
        db.session.commit()

        Oauth_member_bind = OauthMemberBind()
        Oauth_member_bind.openid = open_id
        Oauth_member_bind.client_type = 'wx'
        Oauth_member_bind.type = 1
        Oauth_member_bind.member_id = member.id

        db.session.add(Oauth_member_bind)
        db.session.commit()

    member = Member.query.get(oauthMemberBind.member_id)
    #生成前端所需要的token
    token = "%s#%s" % (memberService.geneAuthCode(member), member.id)
    res['data']['token'] = token
    return jsonify(res)
Exemple #21
0
 def deposit(self):
     if 'member' not in self.context:
         return self.validateAndReturn(None, 3002, "存款余额失败,用户未登录")
     member = self.context['member']
     amount = self.context['amount']
     last_ce = self.context['last_ce']
     try:
         new_Member = Member.amountToMemberAccount(member.username, amount)
     except Exception as e:
         current_app.logger.exception(e)
         current_app.logger.error("%s向主账户存款失败,内部错误%s" %
                                  (member.username, e))
         current_app.logger.error(
             "%s从%s娱乐城取款%s已经完成,但是将金额存回主账户时错误,请查看详细日志。" %
             (member.username, self.context['last_ce'], amount))
         current_app.logger.error(
             {
                 "success": False,
                 'errorCode': 9001,
                 'errorMsg':
                 "%s从%s娱乐城取款%s已经完成,但是将金额存回主账户时错误,这是一个严重错误,需要人工存入"
             } % (member.username, self.context['last_ce'], amount))
         return {"success": False, 'errorCode': 3001, 'errorMsg': "转账失败"}
Exemple #22
0
	def post(self):
		parser = RequestParser(trim=True)
		parser.add_argument('username', type=str, required=True)
		args = parser.parse_args(strict=True)

		try:
			member = Member()
			member.type = 9
			member.username = args['username']
			member.registrationTime = time_to_value()
			member.registrationHost = host_to_value(request.remote_addr)

			db.session.add(member)
			db.session.commit()
		except:
			db.session.rollback()
			db.session.remove()
			abort(500)
		return make_response([]), 201
Exemple #23
0
 def withdrawalToAccount(context, kargs):
     uid = context['member'].id
     username = context['member'].username
     isTsetPLay = context['member'].isTsetPLay
     actionTime = int(time.time())
     last_ce = None
     ecTradeDao = None
     if 'isDemo' in kargs:
         if kargs['isDemo'] == '1' or isTsetPLay == 1:
             current_app.logger.info('%s试玩账号不需要额度转换' % (username))
             return {"success": True}
     if 'fromEC' in kargs and kargs['fromEC'] is not None:
         last_ce = kargs['fromEC']
     else:
         #获取上一次用户登录的娱乐城
         ecLogDao = EntertainmentCityLog()
         last_ce = ecLogDao.getLastLogin(uid)
     if last_ce is None:
         return {"success": True}
     current_app.logger.info("%s本次娱乐城:%s" % (username, context['loginEC']))
     current_app.logger.info("%s上次娱乐城:%s" % (username, last_ce))
     #如果本次与上一次登录的是同一个娱乐城或者上一次在kk。则不用转账
     if (last_ce == "MAIN") or (last_ce == context['loginEC']):
         current_app.logger.info('%s不需要取款' % (username))
         return {"success": True}
     amount = None
     lastEC = EntertainmentCityFactory.getEntertainmentCity(last_ce)
     lastEC.context["member"] = context["member"]
     #去上一个娱乐城查询余额
     try:
         m_res = lastEC.balance(kargs)
         if m_res['success'] == False:
             current_app.logger.error("%s查询余额错误:%s" % (username, m_res))
             return {
                 "success": False,
                 'errorCode': 3001,
                 'errorMsg': "查询余额错误"
             }
     except Exception as e:
         current_app.logger.exception(format(e))
         current_app.logger.error("%s查询余额错误:%s" % (username, m_res))
         return {"success": False, 'errorCode': 3001, 'errorMsg': "查询余额错误"}
     #娱乐城的余额
     balance = float(m_res['data']['balance'])
     current_app.logger.info('%s在%s余额:%s' % (username, last_ce, balance))
     if 'amount' in kargs:
         amount = kargs['amount']
         current_app.logger.info('%s从%s取款:%s' % (username, last_ce, amount))
         if amount > balance:
             current_app.logger.info("%s取款金额大于娱乐城余额,余额是%s" %
                                     (username, balance))
             return {
                 "success": False,
                 'errorCode': 3001,
                 'errorMsg': "转账失败"
             }
         else:
             balance = amount
     lastEC.context["amount"] = balance
     orderid = createECOrderId(uid)
     lastEC.context['orderid'] = orderid
     wjorderId = None
     #取款
     if balance >= 1:
         current_app.logger.info('开始取款')
         #生成交易记录
         ecTradeDao = AmountTransfer.saveECTradeLog(uid, username, balance,
                                                    actionTime, 'MAIN',
                                                    last_ce, orderid, None,
                                                    context['real_ip'], 0,
                                                    0)
         try:
             m_res = lastEC.withdrawal(None)
         except Exception as e:
             current_app.logger.exception(e)
             current_app.logger.error('%s从%s取款失败' % (username, last_ce))
             AmountTransfer.updateECTradeLog(ecTradeDao, None, 0, 0, 0)
             #生成交易明细
             AmountTransfer.saveECTradeDetail(uid, username, actionTime,
                                              balance, orderid, last_ce,
                                              None, 0, '娱乐城取款失败,不用额度确认',
                                              None)
             #                 AmountTransfer.saveECTradeLog(uid, username, balance, actionTime, 'MAIN',last_ce, orderid, wjorderId, context['real_ip'],2,0,'娱乐城转账失败,余额已从娱乐城转出,需要人工审核结案')
             return {
                 "success": False,
                 'errorCode': 3001,
                 'errorMsg': "转账失败"
             }
         if m_res['success'] == False:
             current_app.logger.error('%s从%s取款失败:%s' %
                                      (username, last_ce, m_res))
             AmountTransfer.updateECTradeLog(ecTradeDao, None, 0, 0, 0)
             AmountTransfer.saveECTradeDetail(uid, username, actionTime,
                                              balance, orderid, last_ce,
                                              None, 0, '娱乐城取款失败,不用额度确认',
                                              None)
             return {
                 "success": False,
                 'errorCode': 3001,
                 'errorMsg': "转账失败"
             }
         wjorderId = AmountTransfer.getWjorderId(m_res, last_ce)
         AmountTransfer.updateECTradeLog(ecTradeDao, wjorderId, 0, 1, 2)
         AmountTransfer.saveECTradeDetail(uid, username, actionTime,
                                          balance, orderid, last_ce, None,
                                          1, '交易成功', None)
         current_app.logger.info('%s结束取款' % (username))
         current_app.logger.info('%s取出余额:%s' % (username, balance))
     else:
         current_app.logger.info('%s结束取款取款金额小于1元' % (username))
         return {"success": True}
     #将余额存回主账户
     current_app.logger.info("%s转回主账户开始" % (username))
     #如果钱已经从娱乐城取出,但是更新主账户金额时发生错误(例如数据库链接不上),需要日志记录,否前钱不回来
     try:
         member = Member.amountToMemberAccount(username, balance)
     except Exception as e:
         current_app.logger.exception(e)
         current_app.logger.error("%s转回主账户失败,内部错误%s" % (username, e))
         current_app.logger.error(
             "%s从%s娱乐城取款%s已经完成,但是将金额更新回主账户时错误,请查看详细日志。" %
             (username, last_ce, balance))
         current_app.logger.error({
             "success":
             False,
             'errorCode':
             9001,
             'errorMsg':
             "%s从%s娱乐城取款%s已经完成,但是将金额更新回主账户时错误,这是一个严重错误,需要人工存入" %
             (username, last_ce, balance)
         })
         AmountTransfer.updateECTradeLog(
             ecTradeDao, wjorderId, 0, 1, 2, 0,
             "%s从%s娱乐城取款%s已经完成,将余额存入回主账户的过程中发生错误,这是一个严重错误,需要人工存入" %
             (username, last_ce, balance),
             '确认转账状态与判断不符而造成掉额度,开始进行补额度 - [系統]')
         AmountTransfer.saveECTradeDetail(
             uid, username, actionTime, balance, orderid, 'MAIN', 1, 2,
             '交易失败', '确认转账状态与判断不符而造成掉额度,开始进行补额度 - [系統]')
         return {"success": False, 'errorCode': 3001, 'errorMsg': "转账失败"}
     current_app.logger.info("转回主账户完成")
     AmountTransfer.updateECTradeLog(ecTradeDao, wjorderId, 1, 1, 1, None,
                                     '转账成功', None)
     AmountTransfer.saveCoinlog(uid, balance, member, actionTime, orderid,
                                wjorderId, 'MAIN', last_ce, context['ip'],
                                400, '转回主账户完成')
     AmountTransfer.saveECTradeDetail(uid, username, actionTime, balance,
                                      orderid, 'MAIN', None, 1, '交易成功',
                                      None)
     return {"success": True}
Exemple #24
0
 def make_member(self, data, **kwargs):
     return Member(**data)
Exemple #25
0
def get_paginate():
    start, count = paginate()
    q = request.args.get('q', None)
    models = Member.get_paginate_models(start, count, q, throw=True)
    return models
def byStudent():
    if session.get("id") is None:
        return redirect("/user/login")
    name=session.get("name")
    courseId=request.args.get("courseId")

    studentList=CourseAndStudent.query.filter_by(CourseId=courseId).all()
    list=[]
    for i in studentList:

        student=Student.query.filter_by(id=i.studentId).first()
        if student is not None:
            list.append(student)


    #每组的人数
    totalNum=Course.query.filter_by(CourseId=courseId).first().numofmember


    #组的数量
    # teamNum=len(list)/totalNum+1
    # print(teamNum)
    #
    # if teamNum==1:
    #     list2=[]
    #     list2.append(list)
    #     pass
    # else:
    from random import shuffle

    shuffle(list)  # 重排序
    list2 = []
    for i in range(0, len(list), totalNum):
        list2.append(list[i:i + totalNum])

    result=[]

    for i in list2:
        dict1 = dict()

        nameTeam=random.randint(100,1000)
        dict1["name"]=str(nameTeam)
        dict1["value"]=i
        print(i)
        result.append(dict1)

        with db.auto_commit():
            team = Team()
            team.TeamName=str(nameTeam)
            team.courseId=courseId
            # 数据库的insert操作
            db.session.add(team)

        team=Team.query.filter(Team.courseId==courseId).filter(Team.TeamName==nameTeam).first()
        with db.auto_commit():
            for x in i:
                member=Member()
                member.teamId=team.TeamNumber
                member.studentId=x.id
                db.session.add(member)


    Course.query.filter(Course.CourseId == courseId).update({"teamType": 2})
    db.session.commit()
    return render_template("teacher_templates/displaygroup.html",name=name,courseId=courseId,result=result)
Exemple #27
0
def insert_member(room_id, user_id):
    member = Member(room_id=room_id, user_id=user_id)

    session.add(member)
    session.commit()
Exemple #28
0
def get_members():
    start, count = paginate()
    q = request.args.get('q', None)
    members = Member.get_paginate_models(start, count, q, err_msg='相关会员不存在')
    return jsonify(members)
Exemple #29
0
 def test_db에_저장된다(self, subject, email, name):
     member = Member.objects(email=email).get()
     assert member.name == name
Exemple #30
0
	def post(self):
		member_parser = RequestParser(trim=True)
		member_parser.add_argument('username', type=str)
		member_parser.add_argument('password', type=str, default=DEFAULT_MEMBER_PASSWORD)
		member_parser.add_argument('fundPassword', type=str, default=DEFAULT_MEMBER_FUND_PASSWORD)
		member_parser.add_argument('parentUsername', type=str)
		member_parser.add_argument('commissionConfig', type=int)
		member_parser.add_argument('defaultRebateConfig', type=int)
		member_parser.add_argument('defaultLevelConfig', type=int)
		member_parser.add_argument('type', type=int)
		member_parser.add_argument('rebateRate', type=float)
		member_args = member_parser.parse_args()

		member_personal_info_parser = RequestParser(trim=True)
		member_personal_info_parser.add_argument('name', type=str)
		member_personal_info_parser.add_argument('birthdate', type=str)
		member_personal_info_parser.add_argument('gender', type=int)
		member_personal_info_parser.add_argument('phone', type=str)
		member_personal_info_parser.add_argument('email', type=str)
		member_personal_info_parser.add_argument('tencentQQ', type=str)
		member_personal_info_parser.add_argument('tencentWeChat', type=str)
		member_personal_info_parser.add_argument('personalInfoRemark', type=str, dest='remark')
		member_personal_info_args = member_personal_info_parser.parse_args()

		pattern = "^[A-Za-z0-9\\u4e00-\\u9fa5][A-Za-z0-9\\u4e00-\\u9fa5-_]{4,13}[A-Za-z0-9\\u4e00-\\u9fa5]$"
		if member_args['type'] is not None:
			if member_args['type'] == 1:
				re_result = re.match(pattern, member_args['username'])
				if re_result is None:
					return make_response(error_code=400, error_message="账号必须为6-15位字母和数字组合")
		if member_personal_info_args['birthdate'] is None or len(member_personal_info_args['birthdate']) == 0:
			member_personal_info_args['birthdate'] = None
		else:
			timeArray = time.strptime(member_personal_info_args['birthdate'], "%Y-%m-%d")
			timestamp = time.mktime(timeArray)
			member_personal_info_args['birthdate'] = int(timestamp)
		member_personal_info_args = {key: value for key, value in member_personal_info_args.items() if value}

		member_bank_account_parser = RequestParser(trim=True)
		member_bank_account_parser.add_argument('bankId', type=str)
		member_bank_account_parser.add_argument('accountNumber', type=str)
		member_bank_account_parser.add_argument('accountName', type=str)
		member_bank_account_parser.add_argument('subbranchName', type=str)
		member_bank_account_parser.add_argument('province', type=str)
		member_bank_account_parser.add_argument('city', type=str)
		member_bank_account_parser.add_argument('bankAccountRemark', type=str, dest='remark')
		member_bank_account_args = member_bank_account_parser.parse_args()
		if member_args['type'] is None or member_args['type']=='' or  member_args['type']=="":
			return {
				'errorCode': "9998",
				'errorMsg': "代理层级不能为空",
				'success': False
			}
		if member_args['username'] is None or member_args['username']=='' or  member_args['username']=="":
			return {
				'errorCode': "9998",
				'errorMsg': "用户名不能为空",
				'success': False
			}
		if member_args['type'] != 11:
			if member_args['parentUsername'] is None or member_args['parentUsername']=='' or  member_args['parentUsername']=="":
				return {
					'errorCode': "9998",
					'errorMsg': "上层代理不能为空",
					'success': False
				}
		if member_args['commissionConfig'] is None or member_args['commissionConfig']=='' or  member_args['commissionConfig']=="":
			return {
				'errorCode': "9998",
				'errorMsg': "佣金设定不能为空",
				'success': False
			}
		if member_args['type'] == 1:
			if member_args['defaultRebateConfig'] is None or member_args['defaultRebateConfig']=='' or  member_args['defaultRebateConfig']=="":
				return {
					'errorCode': "9998",
					'errorMsg': "预设反水不能为空",
					'success': False
				}
			if member_args['defaultLevelConfig'] is None or member_args['defaultLevelConfig']=='' or  member_args['defaultLevelConfig']=="":
				return {
					'errorCode': "9998",
					'errorMsg': "预设会员等级不能为空",
					'success': False
				}

		if member_args['type'] == 1:

			parent = Member.query.filter(Member.username == member_args['parentUsername'],Member.type==9).first()
			if parent is None:
				return {
				'errorCode': "9998",
				'errorMsg': "上层代理错误",
				'success': False
			}
		if member_args['type'] == 9:
			if 'defaultRebateConfig' in member_args:
				del member_args['defaultRebateConfig']
			if 'defaultLevelConfig' in member_args:
				del member_args['defaultLevelConfig']
			parent = Member.query.filter(Member.username == member_args['parentUsername'],Member.type==10).first()
			if parent is None:
				return {
				'errorCode': "9998",
				'errorMsg': "上层代理错误",
				'success': False
			}
		if member_args['type'] == 10:
			if 'defaultRebateConfig' in member_args:
				del member_args['defaultRebateConfig']
			if 'defaultLevelConfig' in member_args:
				del member_args['defaultLevelConfig']
			parent = Member.query.filter(Member.username == member_args['parentUsername'],Member.type==11).first()
			if parent is None:
				return {
				'errorCode': "9998",
				'errorMsg': "上层代理错误",
				'success': False
			}
		if member_args['type'] == 11:
			if 'defaultRebateConfig' in member_args:
				del member_args['defaultRebateConfig']
			if 'defaultLevelConfig' in member_args:
				del member_args['defaultLevelConfig']
			if member_args['parentUsername'] is not None:
				return {
					'errorCode': "9998",
					'errorMsg': "该级没有上层代理,不可设置",
					'success': False
				}
		if member_bank_account_args['bankId'] is None or len(member_bank_account_args['bankId']) == 0:
			member_bank_account_args['bankId'] = None
		else:
			member_bank_account_args['bankId'] = int(member_bank_account_args['bankId'])
		member_bank_account_args = {key: value for key, value in member_bank_account_args.items() if value}

		member = Member.query.filter(Member.username == member_args['username']).first()
		if member:
			return make_response(error_message='用户名已存在')
		if member_args['parentUsername'] is not None:
			parent = Member.query.filter(Member.username == member_args.pop('parentUsername')).first()
			if parent.status == 0:
				return jsonify({
					'success': False,
					'errorCode': 403,
					'errorMsg': '该代理已被停用'
				})
			if member_args['rebateRate']:
				m_boolean = member_args['rebateRate'] <= parent.rebateRate or member_args['rebateRate']==0
				if not m_boolean:
					return make_response(error_code=400, error_message="返点率不能超过" + str(float(parent.rebateRate)) + "%")
			else:
				return make_response(error_code=400, error_message="请设置返点")
			if member_args['type'] != 11:
				if not parent or not parent.type:
					return make_response(error_message='上级用户名错误')
				if parent.parents is None:
					parents = '%s' % parent.id
					parentsInfo =  '%s' % parent.username
				else:
					parents = parent.parents + ',%s' % parent.id
					parentsInfo = parent.parentsInfo + ',%s' % parent.username
				member_args['parent'] = parent.id
				member_args['parents'] = parents
				member_args['parentsInfo'] = parentsInfo
				member_args['levelConfig'] = parent.defaultLevelConfig
				member_args['rebateConfig'] = parent.defaultRebateConfig
				# #暂时以这种情况新增反水设定
				# member_args['defaultLevelConfig'] = parent.defaultLevelConfig
				# member_args['defaultLevelConfig'] = parent.defaultLevelConfig
			else:
				member_args['parent'] = None
				member_args['parents'] = None
				member_args['parentsInfo'] = None
				member_args['levelConfig'] = None
				member_args['rebateConfig'] = None
		else:
			member_args.pop('parentUsername')

		try:

			member_args['registrationTime'] = time_to_value()
			member_args['agentsTime'] = time_to_value()
			member_args['registrationHost'] = host_to_value(request.remote_addr)
			member = Member(**member_args)

			db.session.add(member)
			db.session.commit()
			OperationHistory().PublicMemberDatasApply(2001, member.id)

			try:
					member_personal_info_args['id'] = member.id
					member_personal_info = MemberPersonalInfo(**member_personal_info_args)


					if any(member_bank_account_args.values()):
						member_bank_account_args['memberId'] = member.id
						member_bank_account = MemberBankAccount(**member_bank_account_args)

						member_bank_account_args['userId'] = g.current_user.id
						member_bank_account_args['time'] = time_to_value()
						member_bank_account_modification_log = MemberBankAccountModificationLog(**member_bank_account_args)

						db.session.add(member_bank_account)
						db.session.add(member_bank_account_modification_log)

					db.session.add(member_personal_info)

					db.session.commit()
					OperationHistory().PublicMemberDatasApply(1002, member.id)
					OperationHistory().PublicMemberDatasApply(1003, member.id)
			except:
				db.session.rollback()
				db.session.remove()
				db.session.delete(member)
				db.session.commit()
				abort(500)
		except:
			db.session.rollback()
			db.session.remove()
			abort(500)
		return make_response([]), 201