コード例 #1
0
ファイル: views.py プロジェクト: said1573/management
def register(request):
    if request.method == 'GET':
        return render(request, 'app/register.html', {})
    else:
        result_dict = {}
        user_email = request.POST['user_email']
        user_id = request.POST['user_id']
        user_pw = request.POST['user_pw']
        user_name = request.POST['user_name']
        user_confirm_pw = request.POST['user_confirm_pw']
        if user_email == '' or user_id == '' or user_name == '' or user_pw == '' or user_confirm_pw == '':
            result_dict['result'] = '공백은 사용할 수 없습니다.'
            return JsonResponse(result_dict)

        elif user_pw != user_confirm_pw:
            result_dict['result'] = '비밀번호 매치 실패'
            return JsonResponse(result_dict)

        else:
            try:
                Member.objects.get(user_id=user_id)
                result_dict['result'] = '이미 가입된 아이디가 있습니다.'
            except Member.DoesNotExist:
                member = Member(
                    user_id=user_id,
                    user_pw=user_pw,
                    user_email=user_email,
                    user_name=user_name,
                )
                member.save()
                result_dict['result'] = '가입완료'
            return JsonResponse(result_dict)
コード例 #2
0
def subscribe_member():
    data = request.get_json(force=True)

    current_app.logger.info('Subscribe member: {}'.format(data))

    validate(data, post_subscribe_member_schema)

    member = dao_get_member_by_email(data.get('email'))

    if member:
        return jsonify(
            {'error':
             'member already subscribed: {}'.format(member.email)}), 400

    member = Member(name=data['name'],
                    email=data['email'],
                    marketing_id=data['marketing_id'],
                    active=True)

    dao_create_member(member)

    send_ga_event(f"Subscribed {member.id}", "members", "subscribe",
                  f"{member.id}")

    basic_html = get_email_html(
        email_type=BASIC,
        title='Subscription',
        message=
        "Thank you{} for subscribing to New Acropolis events and magazines".
        format(' {}'.format(data.get('name', '')) if 'name' in data else ''),
        member_id=member.id)
    response = send_email(data['email'], 'New Acropolis subscription',
                          basic_html)

    return jsonify(member.serialize())
コード例 #3
0
def test_borrow_book(mocker):
    # Testing with Invalid member
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    mocker_model_get_by_id.side_effect = [None, None]
    with pytest.raises(MemberNotFound):
        borrow_book(1, 2)

    # Testing with Invalid Book
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    mocker_model_get_by_id.side_effect = [Member(), None]
    with pytest.raises(BookNotFound):
        borrow_book(1, 2)

    # Testing with Already Taken Book
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    mocker_model_get_by_id.side_effect = [Member(), Book(taken=True)]
    with pytest.raises(BookAlreadyTaken):
        borrow_book(1, 2)

    # Testing proper calling of function
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    book = Book(taken=False)
    mocker_model_get_by_id.side_effect = [Member(), book]
    mocker_model_put = mocker.patch('google.cloud.ndb.Model.put')
    borrow_book(1, 2)
    assert book.taken == True
    mocker_model_put.assert_called_once()
コード例 #4
0
ファイル: member.py プロジェクト: zcxyun/food_shop
def login():
    form = LoginForm().validate()
    openid = get_openid(form.code.data)
    if openid is None:
        raise NotFound('找不到openid')
    member_client = MemberClient.query.filter_by(openid=openid,
                                                 client_type=1).first()
    if not member_client:
        with db.auto_commit():
            member = Member()
            member.nickname = form.nickName.data
            member.sex = form.gender.data
            member.avatar = form.avatarUrl.data
            db.session.add(member)
        with db.auto_commit():
            member_client = MemberClient()
            member_client.member_id = member.id
            member_client.client_type = 1
            member_client.openid = openid
            db.session.add(member_client)
    else:
        member = member_client.member
    scope = 'UserScope' if member.auth == 1 and member.status == 1 else 'AdminScope'
    token = gene_token(id=member.id, scope=scope)
    return jsonify({'token': token})
コード例 #5
0
ファイル: member.py プロジェクト: rayandas/tuesday
def update(id, **mod_data):
    updatables = ('uid', 'username', 'name', 'enabled', 'badges', 'bio', 'web',
                  'verified', 'groups')
    update_dict = dict(
        (k, v) for (k, v) in list(mod_data.items()) if k in updatables)

    Member.update(**update_dict).where(Member.id == id).execute()
    if groups in mod_data:
        sso.update_user_groups(id, mod_data['groups'])
コード例 #6
0
def create_members():
    member1 = Member("Mohammed", 20)
    member2 = Member("Omar", 22)
    member3 = Member("Abdo", 25)
    print(member1)
    print(member2)
    print(member3)
    print("=" * 30)
    return member1, member2, member3
コード例 #7
0
def update_should_modify_object(member_store, member3):
    member3_copy = Member(member3.name, member3.age)
    member3_copy.id = 3

    if member3_copy is not member3:
        print("member3 and member3_copy are not the same !")

    print(member3_copy)
    member3_copy.name = "john"
    member_store.update(member3_copy)
    print(member_store.get_by_id(member3.id))
コード例 #8
0
def seed_members():

    db.session.add(
        Member(name="Jeff Hardy",
               notes="The Charismatic Enigma",
               created_at="2021-03-01 14:00:00"))
    db.session.add(
        Member(name="Edge",
               notes="The Rated-R Superstar",
               created_at="2021-03-01 14:00:00"))

    db.session.commit()
コード例 #9
0
ファイル: views.py プロジェクト: wns133244/Djangoproject
def join(request):
     if request.method == 'GET':
         return render(request, 'app/join.html', {})
     else:
         user_name = request.POST['user_name']
         user_mail = request.POST['user_mail']
         user_birth = request.POST['user_birth']

         member = Member(user_name=user_name, user_mail=user_mail, user_birth=user_birth)
         member.c_date = timezone.now()
         member.save()
     return HttpResponse('로그인 완료' + user_name + user_mail + user_birth)
コード例 #10
0
ファイル: rest.py プロジェクト: kentsanggds/api
def import_members():
    text = request.get_data(as_text=True)
    text = text.replace('"EmailAdd": "anon"', '"EmailAdd": null')
    text = text.replace('"EmailAdd": ""', '"EmailAdd": null')
    text = text.replace('"CreationDate": "0000-00-00"', '"CreationDate": null')
    data = json.loads(text)

    validate(data, post_import_members_schema)

    errors = []
    members = []
    for item in data:
        err = ''
        member = Member.query.filter(Member.old_id == item['id']).first()

        if member:
            err = u'member already exists: {}'.format(member.old_id)
            current_app.logger.info(err)
            errors.append(err)
        else:
            member = Member(old_id=item['id'],
                            name=item['Name'],
                            email=item['EmailAdd'],
                            active=item["Active"] == "y",
                            created_at=item["CreationDate"],
                            old_marketing_id=item["Marketing"],
                            is_course_member=item["IsMember"] == "y",
                            last_updated=item["LastUpdated"])

            marketing = Marketing.query.filter(
                Marketing.old_id == item['Marketing']).first()
            if not marketing:
                err = "Cannot find marketing: {}".format(item['Marketing'])
                current_app.logger.error(err)
                errors.append(err)
                continue
            else:
                member.marketing_id = marketing.id

            dao_create_member(member)
            members.append(member)

            current_app.logger.info('Creating member: %d, %s', member.old_id,
                                    member.name)

    res = {"members": [m.serialize() for m in members]}

    if errors:
        res['errors'] = errors

    return jsonify(res), 201 if members else 400 if errors else 200
コード例 #11
0
def create_member(old_id=1,
                  name='Joe Blue',
                  email='*****@*****.**',
                  active=True,
                  old_marketing_id=1,
                  is_course_member=False,
                  last_updated=None,
                  marketing_id=None):
    if not marketing_id:
        search_marketing = Marketing.query.filter_by(
            description='Search').first()
        if not search_marketing:
            marketing = create_marketing(description='Search')
            marketing_id = str(marketing.id)
        else:
            marketing_id = str(search_marketing.id)

    data = {
        'old_id': old_id,
        'name': name,
        'email': email,
        'active': active,
        'old_marketing_id': old_marketing_id,
        'is_course_member': is_course_member,
        'last_updated': last_updated,
        'marketing_id': marketing_id
    }

    member = Member(**data)

    dao_create_member(member)

    return member
コード例 #12
0
def create_group(user_id):
    print(f"{user_id} making post request to /group")

    post_data = request.get_json()

    group_name = post_data['group_name']

    print(group_name)

    #TODO: there is no need for group to have unique name
    group = Group.query.filter_by(name=group_name).first()
    if group:
        return make_response(
            jsonify({
                "success": False,
                "message": "group already exists. Try a different name"
            })), 409

    # TODO: add the member in a transaction
    group = Group(name=group_name)
    db.session.add(group)
    db.session.commit()

    group = group.query.filter_by(name=group_name).first()

    member = Member(user_id, group.id, False)

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

    return make_response(
        jsonify({
            "success": True,
            "message": "group created successfully"
        })), 200
コード例 #13
0
def scrap():
    url = "https://www.garrisoninv.com/senior-investment-professionals.php"

    scrap = Scrapping()
    scrap.start(url)

    for memb in scrap.members_info:

        u = Member(full_name=memb["full_name"],
                   role=memb["role"],
                   company=memb["company"],
                   division=memb["division"],
                   location=memb["location"],
                   phone_number=memb["phone_number"],
                   email=memb["email"],
                   link_vcf=memb["link_vcf"])
        try:
            db.session.add(u)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()

    db_members = Member.query.all()

    return render_template('app/scraped.html', members=db_members)
コード例 #14
0
def add_member_team(user,link,position='player'):
    try:
        team = Team.query.filter_by(link=link).first()
        article_member = Member(user_id=user.id, team_id=team.id, position=position, name=user.username)
        db.session.add(article_member)
        db.session.commit()
        return True
    except:
        return False
コード例 #15
0
def wx_login():
    req = request.values  # 接受数据

    nickname = req['nickname'] if 'nickname' in req else ''
    avatar = req['avatar'] if 'avatar' in req else ''
    # 判断code 是否存在
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        result = {
            "code": -1,
            "msg": "需要微信授权code",
            "data": {}
        }
        return jsonify(result)

    # 根据code,获取openid
    openid = MemberService.getWeChatOpenId(code)
    if openid is None:
        result = {
            "code": -1,
            "msg": "调用微信出错",
            "data": {}
        }
        return jsonify(result)

    # 如果用户存在,写入member表中
    member = Member.query.filter_by(openid=openid).first()
    if not member:
        member = Member(
            openid=openid,
            nickname=nickname,
            avatar=avatar,
            sesion=sesion,
        )
        db.session.add(member)  # 添加数据
        db.session.commit()  # 提交数据库
    sesionTotal = db.session.query(Exam).count()  # 设置最大问题数

    token = serializer.dumps({'user_id': member.id})  # 生成token

    # 返回结果
    result = {
        "code": 1,
        "msg": "登录成功",
        "data":
            {"userInfo":
                {
                    "userId": member.id,
                    "nickName": member.nickname,
                    "avatar": member.avatar,
                    "sesion": member.sesion,
                },
                "sesionTotal": sesionTotal,
                "token": token.decode(),  # byte 转化为string
            }
    }
    return jsonify(result)  # 以json格式返回小程序客户端
コード例 #16
0
 def save_to_db(self):
     if self.id.data:
         member = Member.query.get(int(self.id.data))
     else:
         member = Member()
     member.name = self.name.data
     member.display_name = self.display_name.data
     member.bio = self.bio.data
     member.email = self.email.data
     member.facebook = self.facebook.data
     member.phone = self.phone.data
     if self.member_avatar.data:
         member.avatar = upload(self.member_avatar.data)
     db.session.add(member)
     db.session.commit()
コード例 #17
0
def add_member(pid, uid):
    """Add a user as a member to a program."""
    member = Member(
        program_id=pid,
        member_id=uid,
        stamper_id=uid,
    )
    db.session.add(member)
    db.session.commit()
    return jsonify(member_schema.dump(member))
コード例 #18
0
ファイル: routes.py プロジェクト: pfbouquet/barycenter
def groups():

    if request.method == 'POST':
        if 'new_group_name' in request.form:
            group = Group(name=get_post_result('new_group_name'),
                          creator=current_user.username)
            db.session.add(group)
            member = Member(user_id=current_user.id, group_id=group.id)
            db.session.add(member)
            db.session.commit()
            return redirect(url_for('group', group_id=group.id))
        if 'accept_group' in request.form:
            member = Member(user_id=current_user.id,
                            group_id=request.form['accept_group'])
            db.session.add(member)
            db.session.commit()
            if session.get('subscribe'):
                session.pop('subscribe')
            return redirect(
                url_for('group', group_id=request.form['accept_group']))
        if 'refuse_group' in request.form:
            if session.get('subscribe'):
                session.pop('subscribe')
            return redirect(url_for('groups'))

    form = GroupCreationForm()
    groups = Group.query.join(Member).filter(
        Member.user_id == current_user.id).all()
    subscribe_id = request.args.get('subscribe') or session.get('subscribe')
    if subscribe_id:
        if subscribe_id not in [
                member.group_id for member in Member.query.filter_by(
                    user_id=current_user.id).all()
        ]:
            subscribe = Group.query.filter_by(id=subscribe_id).first()
            return render_template('groups.html',
                                   groups=groups,
                                   subscribe=subscribe,
                                   form=form)

    return render_template('groups.html', groups=groups, form=form)
コード例 #19
0
def register_team():
    form = TeamForm()
    if form.validate_on_submit():
        team = Team.query.filter_by(name=form.team_name.data).first()
        if team is not None:
            flash('This team already exists')
            return redirect(url_for('register_team'))

        members = [Member(name=form.team_member_1.data)]
        if form.team_member_2.data != '':
            members.append(Member(name=form.team_member_2.data))
        if form.team_member_3.data != '':
            members.append(Member(name=form.team_member_3.data))
        if form.team_member_4.data != '':
            members.append(Member(name=form.team_member_4.data))

        team = Team(name=form.team_name.data, members=members)
        db.session.add(team)
        db.session.commit()
        return redirect(url_for('overview'))
    return render_template('register_team.html', title='Sign In', form=form)
コード例 #20
0
def test_return_book(mocker):
    # Testing with Invalid member
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    mocker_model_get_by_id.side_effect = [None, None]
    with pytest.raises(MemberNotFound):
        return_book(1, 2)

    # Testing with Invalid Book
    mocker_model_get_by_id = mocker.patch('google.cloud.ndb.Model.get_by_id')
    mocker_model_get_by_id.side_effect = [Member(), None]
    with pytest.raises(BookNotFound):
        return_book(1, 2)
コード例 #21
0
def create_team(data,article):
    try:
        name = data['name']
        user_id = article.id
        article_team = Team(name=name,user_id=user_id)
        db.session.add(article_team)
        article_team = Team.query.filter_by(user_id=article.id).first()
        article_member = Member(user_id=article.id, team_id=article_team.id, position='Creater', name=article.username)
        db.session.add(article_member)
        db.session.commit()
        return True
    except:
        return False
コード例 #22
0
def sign_up():
    form = SignUpForm(request.form)
    if form.validate_on_submit():
        member = Member(username=form.username.data,
                        email=form.email.data,
                        first_name=form.first_name.data,
                        last_name=form.last_name.data)
        member.member_type = "member"
        member.set_password(form.password.data)
        try:
            db.session.add(member)
            db.session.commit()
            response = make_response(redirect(url_for('auth.login')))
            response.set_cookie("username", form.username.data)
            flash(f'Account successfully created for {member.username}',
                  'success')
            return response
        except IntegrityError as e:
            print(e)
            db.session.rollback()
            flash(f'Unable to register {member.username}. Please try again.',
                  'danger')
    return render_template('signup.html', form=form)
コード例 #23
0
    def test_prepare_database(self, json_file_name: str):
        """ Testing preparation of the database and important functions.

        :param str json_file_name: Path to the test JSON file, parametrised.
        """

        db = prepare_database(data_source=json_file_name)

        assert db.members == {
            Member(member_id='member-123', accounts=set(), name='member-123'),
            Member(member_id='member-124', accounts=set(), name='member-124')
        }
        assert db.accounts == [
            Account(account_id='account-abc', member_id='member-123'),
            Account(account_id='account-abd', member_id='member-123'),
            Account(account_id='account-bcd', member_id='member-124'),
            Account(account_id='account-bce', member_id='member-124')
        ]

        assert db.electricity_bills == \
               TEST_PREPARE_DATABASE_DB_ELECTRICITY_BILLS

        assert db.gas_bills == TEST_PREPARE_DATABASE_DB_GAS_BILLS
コード例 #24
0
def wx_login():
    req = request.values  # 接收数据
    nickname = req['nickname'] if 'nickname' in req else ''  # 获取用户昵称
    avatar = req['avatar'] if 'avatar' in req else ''  # 获取头像
    sesion = req['sesion'] if 'sesion' in req else 0  # 获取关卡
    # 判断code 是否存在
    code = req['code'] if 'code' in req else ''
    if not code or len(code) < 1:
        result = {"code": -1, "msg": "需要微信授权code", "data": {}}
        return jsonify(result)

    # 根据code 获取openid
    openid = MenberService.getWeChatOpenId(code)
    print(code)
    print(openid)
    if openid is None:
        result = {"code": -1, "msg": "调用微信出错", "data": {}}
        return jsonify(result)

    # 如果用户不存在, 将用户信息写入member表中
    print("用户登入")
    member = Member.query.filter_by(openid=openid).first()
    if not member:
        member = Member(
            openid=openid,
            nickname=nickname,
            avatar=avatar,
            sesion=sesion,
        )
        db.session.add(member)
        db.session.commit()
    sesionTotal = db.session.query(Exam).count()
    token = serializer.dumps({'user_id': member.id})  # 生成Token
    # 返回结果
    result = {
        "code": 1,
        "msg": "登入成功",
        "data": {
            "userInfo": {
                "userId": member.id,
                "nickName": member.nickname,
                "avatar": member.avatar,
                "sesion": member.sesion,
            },
            "sesionTotal": sesionTotal,
            "token": token.decode(),  # byt转化为string
        }
    }
    return jsonify(result)
コード例 #25
0
ファイル: views.py プロジェクト: itgsodbojo/ifk
    def get(self):
        """List of all members"""

        with db_session:

            return {

               member.id: {
                    'name': member.name,
                    'phpne':member.phone
                }
                for member in Member.select()  # 2


            }
コード例 #26
0
    def test_unicode(self):

        ## No user set
        member = Member(name="Firstname")
        self.assertEquals(
            unicode(member),
            'Firstname'
        )

        ## User names set, but blank
        member.user = User(first_name="", last_name="")

        self.assertEquals(
            unicode(member),
            'Firstname'
        )

        ## User names set
        member.user = User(first_name="Firstname", last_name="Lastname")

        self.assertEquals(
            unicode(member),
            'Firstname Lastname'
        )
コード例 #27
0
    def test_models(self, member_id: str, name: str, accounts: [Account]):
        """ Testing models and their functions.

        :param str member_id: Member identifier, parametrised.
        :param str name: Member name, parametrised.
        :param [Account] accounts: Account model instances, parametrised.
        """

        test_member = Member(member_id=member_id, name=name, accounts=set())
        assert test_member is not None
        assert test_member.member_id == member_id
        assert test_member.name == name

        db = BillDatabase(members={test_member},
                          accounts=list(),
                          electricity_bills={},
                          gas_bills={})
        for account in accounts:
            db.add_account(account=account)

        if accounts:
            assert len(
                db.get_member_accounts(member_id=member_id)) == len(accounts)

        test_account = Account(account_id='account-abc',
                               member_id='member-123')

        assert test_account.__hash__() == hash('account-abc_member-123')

        test_electricity_bill = ElectricityBill(member=test_member,
                                                account=test_account,
                                                bill_date='2017-08-31',
                                                units=0,
                                                total=0.0)

        assert test_electricity_bill.__hash__() == \
               hash('member-123_account-abc_2017-08-31')

        test_gas_bill = GasBill(member=test_member,
                                account=test_account,
                                bill_date='2017-08-31',
                                units=0,
                                total=0.0)

        assert test_gas_bill.__hash__() == \
               hash('member-123_account-abc_2017-08-31')
コード例 #28
0
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST':
        if form.validate():
            user = Member(username=form.username.data,
                          email=form.email.data,
                          password=generate_password_hash(form.password.data),
                          avatar=url_for('static',
                                         filename='img/avatars/default.jpg'))
            db.session.add(user)
            db.session.commit()
            return redirect(
                request.args.get('next') or url_for('member.login'))

        else:
            flash('may username already exists.')
    return render_template('member/register.html', form=form)
コード例 #29
0
    def save(self):
        try:
            # Create new member
            member = Member(username=self.username, email=self.email)
            db.session.add(member)
            db.session.commit()
            return True, 'created'

        except InterfaceError:
            logging.error("Got exception while creating new member: {}".format(
                traceback.format_exc()))
            return False, e.message.split(')')[1].strip()

        except IntegrityError as e:
            logging.error(
                "Got Integrity error while creating new member: {}".format(
                    traceback.format_exc()))
            return False, e.message.split(')')[1].strip()
コード例 #30
0
def form_for_new_members():
    print("REQUEST!", request.data)
    form = MemberCreateForm()
    if request.method == "POST":
        print("ATTEMPTING TO POST!!")
        if form.validate_on_submit:
            data = form.data
            print("DATA!!!!!", data)
            new_member = Member(name=data['name'],
                                notes=data['notes'],
                                created_at=datetime.now())
            print("MEMBER NAME!!!!!!!!!!!", new_member.name, new_member.notes)
            db.session.add(new_member)
            db.session.commit()
            return {"Message": "Member Created Successfully!"}, 200

            # return redirect("/members")
        else:
            print("NO!!")
コード例 #31
0
ファイル: routes.py プロジェクト: atharvameshram/VI-Clubs
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = SRegistrationForm()
    if form.validate_on_submit():
        mem = Member(name=form.name.data)
        role = Role.query.filter_by(name='member').first()
        user = User(username=form.username.data,
                    email=form.email.data,
                    member=mem)
        user.set_password(form.password.data)
        user.roles = [role]
        db.session.add(mem)
        db.session.add(user)
        db.session.commit()
        flash('Congratulations, you are now a registered user!', 'success')
        return redirect(url_for('login'))
    return render_template('register.html',
                           form=form,
                           title="VI Clubs - Sign up!")
コード例 #32
0
ファイル: member.py プロジェクト: rayandas/tuesday
def create(id,
           name=None,
           email=None,
           groups=None,
           username=None,
           bio=None,
           web=None):
    if name is None or email is None:
        userinfo = sessiondb.get_for(id)
        email = email or userinfo['email']
        name = name or userinfo['name']
    username = username or generate_username(name)
    groups = groups or []
    user = Member.create(id=id,
                         email=email,
                         username=username,
                         name=name,
                         groups=groups,
                         bio=bio,
                         web=web)
    return user.id