def membership_add_subscription(user, membership_type, active=False): valid_from = timezone.now() valid_to = valid_from + timedelta(days=membership_type.day_to_live) membership = Membership(user=user, membership_type=membership_type, valid_to=valid_to, valid_from=valid_from, updated_at=valid_from, active=active) membership.save()
def seed_memberships(): membership_low = Membership(type='Standard', price=10) membership_mid = Membership(type='Deluxe', price=15) membership_high = Membership(type='Premium', price=20) db.session.add(membership_low) db.session.add(membership_mid) db.session.add(membership_high) db.session.commit()
def get_cnt_of_new_members_in_past(hub=None, days=30): """ Returns a count of a new members in a given past days """ base_date = decrement_date(get_current_date_obj(), days=-days).isoformat() query = and_(Membership.confirmed_at >= base_date) # if hub's instance then return count of new members of a hub if isinstance(hub, Hub): query = and_(Membership.hub == hub, query) return int(Membership.count(query))
def get_cnt_of_leave_members_in_past(hub=None, days=30): """ Returns a count of a leave members in a given past days """ base_date = decrement_date(get_current_date_obj(), days=-days).isoformat() query = and_(Membership.canceled_to >= base_date) # if hub's instance then return count of new members of a hub if isinstance(hub, Hub): query = and_(Membership.hub == hub, query) return int(Membership.count(query))
def subscribe(request, groupname): login = login_verify(request, None, True) if login: return login group = Group.objects.get(name=groupname) if request.method == 'POST': uid = request.POST.get('uid', '') expiration_date = request.POST.get('expiration_date', '') user = User.objects.get(uid=uid) membership = Membership(user=user, expiration_date=expiration_date) membership.save() group.members.add(membership) group.save() return HttpResponseRedirect('/view_group/' + groupname + '/') else: form = SubscribeForm() all_users = User.objects.all() user_list = [] for user in all_users: if user not in group.members.all(): user_list += [user] context = {'form': form, 'groupname': group.name, 'group': group, 'user_list': user_list} return render(request, 'app/subscribe.html', context)
def get_cnt_of_active_members_in_past(hub=None, days=0): """ Returns a number of active members in a hub on a given date date should be in `YYYY-MM-DD` format. """ base_date = decrement_date(get_current_date_obj(), days=-days).isoformat() query = or_(Membership.canceled_to == None, Membership.canceled_to >= base_date) # if hub's instance then return count of active members of a hub if isinstance(hub, Hub): query = and_(Membership.hub == hub, query) return int(Membership.count(query))
def create_zone(zone_id): if zone_id: """拷贝""" title = "拷贝区服" membership = Membership.query.filter_by(zone_id=zone_id).first() zone = Zones.query.get(zone_id) form = AEZoneForm(game=membership.game_id, channel=membership.channel_id, zonenum=zone.zonenum, zonename=zone.zonename, zoneip=zone.zoneip, dblink=zone.dblink, dbport=zone.dbport, db_A=zone.db_A, db_B=zone.db_B, db_C=zone.db_C) else: """新增""" title = "新增区服" form = AEZoneForm() if form.validate_on_submit(): game = Games.query.get(form.game.data) channel = Channels.query.get(form.channel.data) zones = Zones(zonenum=form.zonenum.data, zonename=form.zonename.data, zoneip=form.zoneip.data, dblink=form.dblink.data, dbport=form.dbport.data, db_A=form.db_A.data, db_B=form.db_B.data, db_C=form.db_C.data) try: # 先保存区服对象 db.session.add(zones) db.session.commit() membership = Membership(game, channel, zones) db.session.add(membership) db.session.commit() flash("操作成功", "alert-info") return redirect(url_for(".zones_list")) except Exception as e: db.session.rollback() flash(e, "alert-danger") return render_template("createdit_module.html", form=form, title=title)
def createGroup(request, username): assert isinstance(request, HttpRequest) # If the method is a POST request, check if it is a valid Create Group form if request.method == 'POST': form = CreateGroupForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] # If the group already exists, do nothing if Group.objects.filter(name=name).exists(): return render( request, 'app/createGroup.html', { 'title': username, 'form': CreateGroupForm(), 'error': 'Group already exists' }) # If the group does not exists, make a new group else: user = User.objects.get_by_natural_key(username) gDrive = GoogleDrive() # Create a folder in the drive and get its id folderId = gDrive.createGroup(name) # Create a group in the db, setting the owner to be the user who created the group, # and the gdriveid to be the id of the newly created folder group = Group() group.name = name group.owner = user group.gdriveid = folderId # Create a random 16 byte key that will be used for encryption/decryption group.key = get_random_bytes(16) group.save() # Create a membership relationship between the new group and the user who created it membership = Membership() membership.group = group membership.user = user membership.save() # Redirect back to the user page return redirect('/userpage/' + username) else: # If there was no POST request, just render the userpage as normal return render(request, 'app/createGroup.html', { 'title': username, 'form': CreateGroupForm() })
def manageUsers(request, groupId): assert isinstance(request, HttpRequest) group = Group.objects.get(id=groupId) # If the method is a POST request, check if it is a valid Add User form if request.method == 'POST': form = AddUserForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] # If the user doesn't exist, render an informative message if not User.objects.filter(username=name).exists(): return render( request, 'app/manageUsers.html', { 'title': 'ManageUsers', 'form': AddUserForm(), 'error': 'User doesn\'t exist', 'group': group }) user = User.objects.get_by_natural_key(name) # If the user is already a member of the group, render an informative message if Membership.objects.filter(user=user, group=group).exists(): return render( request, 'app/manageUsers.html', { 'title': 'ManageUsers', 'form': AddUserForm(), 'error': 'User is already a member', 'group': group }) else: # Otherwise, create a membership realtionship between the user and the group membership = Membership() membership.group = group membership.user = user membership.save() return render(request, 'app/manageUsers.html', { 'title': 'ManageUsers', 'form': AddUserForm(), 'group': group }) else: # If the request is not a POST request, renser the page as normal return render(request, 'app/manageUsers.html', { 'title': 'ManageUsers', 'form': AddUserForm(), 'group': group })
def process_data_of_hub(hub, data, date_of_crawl=None): """ Process data given by cobot api """ # check if date of crawl is set or not # if not then set it with current date if date_of_crawl is None: date_of_crawl = get_current_date_str() for index, membership_data in enumerate(data): try: # preprocess a membership data in a model suitable # form m_data = preprocess_membership_data(membership_data) # check user exists or not if not create user else get it's # instance user = User.create_or_get(**m_data["user"]) # check membership exists or not if not create membership else # get it's instance membership = Membership.create_or_get(**m_data['membership']) # assign a hub to this membership if not else do nothing membership.assign_hub(hub) # assign a user to this membership if not else do nothing membership.assign_user(user) # check plan exists or not if not create plan else get it's # instance plan = Plan.create_or_get(**m_data['plan']) # check hub_plan exists or not if not create hub_plan else get # it's instance context = {'hub': hub, 'plan': plan} hub_plan = HubPlan.create_or_get(**context) # check if plan of a membership changed or not if is_membership_plan_changed(membership, hub_plan): # if plan changed then set end_date of last active plan of # a membership as date_of_crawl, if any last_membership_plan = set_end_date_of_last_membership_plan( membership, date_of_crawl) # create a new membership plan instance context = { 'membership': membership, 'hub_plan': hub_plan, 'start_date': get_date_obj_from_str(date_of_crawl) } # and, also set `start_date` of membership plan depending upon # last_membership_plan existence if not last_membership_plan: context['start_date'] = \ m_data['membership']['confirmed_at'] # create a new membership plan membership_plan = MembershipPlan.create(**context) else: # nothing to do pass # check if membership ended or not and, if yes set canceled_to date # of membership and also set end_date of last membership_plan of # this membership_plan m_canceled_date = get_date_obj_from_str( membership_data['canceled_to']) membership.set_canceled_date(m_canceled_date) except Exception as e: logger.error(e, exc_info=True) logger.info("Total {0} Memberships processed on {1} of hub {2}".format( len(data), date_of_crawl, hub.name))
def reseed_main_database(): # Add and commit users. user1 = User( first_name='Matthew', last_name='Eckes', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='he', object_pronoun='him', profile_image_id='klb9kosj3x73zfatbhurp95tw', role='administrator', api_token=User.generate_api_token()) user2 = User( first_name='John', last_name='Latchaw', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='he', object_pronoun='him', profile_image_id='nxew011f4kcr7ngcbhjedrwdy', header_image_url= 'https://images.unsplash.com/photo-1479502806991-251c94be6b15?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MTN8fHxlbnwwfHx8&auto=format&fit=crop&w=500&q=60', api_token=User.generate_api_token()) user3 = User( first_name='Laura', last_name='Eckes', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='she', object_pronoun='her', # profile_image_id='uploads/Laura Eckes.jpg', header_image_url= 'https://images.unsplash.com/photo-1542293787938-c9e299b880cc?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxleHBsb3JlLWZlZWR8N3x8fGVufDB8fHw%3D&auto=format&fit=crop&w=500&q=60', api_token=User.generate_api_token()) user4 = User( first_name='Grace', last_name='Thomson', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='she', object_pronoun='her', # profile_image_id='uploads/Grace Thomson.jpg', api_token=User.generate_api_token()) user5 = User( first_name='Avi', last_name='Steinbach', email_address='*****@*****.**', is_email_confirmed=True, username='******', profile_image_id='8j53bk7qqjpaui9gfbip692p0', password='******', subject_pronoun='he', object_pronoun='him', api_token=User.generate_api_token()) user6 = User( first_name='Penny', last_name='Rosenberg', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='she', object_pronoun='her', api_token=User.generate_api_token()) user7 = User( first_name='Sue', last_name='Young', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='she', object_pronoun='her', api_token=User.generate_api_token()) user8 = User( first_name='John', last_name='Eckes', email_address='*****@*****.**', is_email_confirmed=True, username='******', password='******', subject_pronoun='he', object_pronoun='him', api_token=User.generate_api_token()) db.session.add_all( [user1, user2, user3, user4, user5, user6, user7, user8]) db.session.commit() # Add and commit groups. group1 = Group( owner_id=user1.id, name='Eckes Family', description='The Eckes family and their significant others.') group2 = Group(owner_id=user3.id, name='PBML', description='Pots by Matt & Laura') group3 = Group( owner_id=user2.id, name='Ahlgren/Latchaw Family', description='The Ahlgren/Latchaw family and their significant others.') group4 = Group( owner_id=user4.id, name='Alaska Bound!', description='Solely devoted to remembering our trip to Alaska.') db.session.add_all([group1, group2, group3, group4]) db.session.commit() # Add and commit memberships. membership1 = Membership(member_id=user1.id, group_id=group1.id, member_type='owner', invited_by_id=user1.id, joined=func.now()) membership2 = Membership(member_id=user2.id, group_id=group1.id, member_type='member', invited_by_id=user1.id, joined=func.now()) membership3 = Membership(member_id=user3.id, group_id=group1.id, member_type='member', invited_by_id=user1.id, joined=func.now()) membership4 = Membership(member_id=user1.id, group_id=group3.id, member_type='member', invited_by_id=user2.id, joined=func.now()) membership5 = Membership(member_id=user2.id, group_id=group3.id, member_type='owner', invited_by_id=user2.id, joined=func.now()) membership6 = Membership(member_id=user3.id, group_id=group2.id, member_type='owner', invited_by_id=user3.id, joined=func.now()) membership7 = Membership(member_id=user1.id, group_id=group2.id, member_type='member', invited_by_id=user3.id, joined=func.now()) membership8 = Membership(member_id=user5.id, group_id=group1.id, member_type='invited', invited_by_id=user1.id, joined=func.now()) membership9 = Membership(member_id=user6.id, group_id=group1.id, member_type='invited', invited_by_id=user1.id, joined=func.now()) membership10 = Membership(member_id=user4.id, group_id=group4.id, member_type='owner', invited_by_id=user4.id, joined=func.now()) membership11 = Membership(member_id=user1.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership12 = Membership(member_id=user2.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership13 = Membership(member_id=user3.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership14 = Membership(member_id=user5.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership15 = Membership(member_id=user6.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership16 = Membership(member_id=user7.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) membership17 = Membership(member_id=user8.id, group_id=group1.id, member_type='member', invited_by_id=user1.id, joined=func.now()) membership18 = Membership(member_id=user8.id, group_id=group4.id, member_type='member', invited_by_id=user4.id, joined=func.now()) db.session.add_all([ membership1, membership2, membership3, membership4, membership5, membership6, membership7, membership8, membership9, membership10, membership11, membership12, membership13, membership14, membership15, membership16, membership17, membership18 ]) db.session.commit() # Add and commit posts post1 = Post(owner_id=user1.id, group_id=group1.id, content="We should do something for Penny's 65th birthday!") post2 = Post(owner_id=user3.id, group_id=group1.id, content="Agreed--she will be disappointed if we don't.") post3 = Post(owner_id=user2.id, group_id=group1.id, content="I'm in!") post4 = Post( owner_id=user1.id, group_id=group1.id, content= "Okay I will talk to John Eckes about it and see if we can figure something out. Hopefully he has some ideas and is willing to do something fun at the house." ) post5 = Post(owner_id=user2.id, group_id=group1.id, content="I will pick up a cake on my way over.") post6 = Post( owner_id=user3.id, group_id=group1.id, content= "Oh wait! I think this is actually just her 64th birthday. So maybe it's not such a big deal if it's not like a big party???" ) post7 = Post( owner_id=user1.id, group_id=group1.id, content= "Hmm... okay well then maybe we just go over for dinner and be really nice to her. She normally appreciates when we are uncharacteristically nice for extended periods of time haha." ) post8 = Post(owner_id=user2.id, group_id=group1.id, content="Hahahahaha") db.session.add_all( [post1, post2, post3, post4, post5, post6, post7, post8]) db.session.commit() image1 = AWSFileStorage( id='klb9kosj3x73zfatbhurp95tw', owner_id=user1.id, url= 'https://mre-platform.s3.us-east-2.amazonaws.com/klb9kosj3x73zfatbhurp95tw.jpg', file_type='image', category='profile-picture') image2 = AWSFileStorage( id='nxew011f4kcr7ngcbhjedrwdy', owner_id=user2.id, url= 'https://mre-platform.s3.us-east-2.amazonaws.com/nxew011f4kcr7ngcbhjedrwdy.jpg', file_type='image', category='profile-picture') image3 = AWSFileStorage( id='8j53bk7qqjpaui9gfbip692p0', owner_id=user4.id, url= 'https://mre-platform.s3.us-east-2.amazonaws.com/8j53bk7qqjpaui9gfbip692p0.jpg', file_type='image', category='profile-picture') db.session.add_all([image1, image2, image3]) db.session.commit()
def batch_import(): form = BatchImportForm() msg = [] if form.validate_on_submit(): filehandler = form.excelfile.data wb = xlrd.open_workbook(file_contents=filehandler.read()) table = wb.sheets()[0] nrows = table.nrows ncole = table.ncols title = table.row_values(0) try: moduletitle = [title[col].strip() for col in range(ncole)] module = ["序号","游戏","渠道","区服号","区服名称","区服IP","数据库链接","数据库端口","数据库A","数据库B","数据库C"] if not moduletitle == module: raise Exception("模板格式错误!") for i in range(1,nrows): rowvalues = table.row_values(i) game = rowvalues[1].strip() channel = rowvalues[2].strip() if isinstance(rowvalues[3],float): zonenum = int(rowvalues[3]) else: zonenum = rowvalues[3].strip() if isinstance(rowvalues[7],float): DB_port = int(rowvalues[7]) else: DB_port = rowvalues[7].strip() gameobj = Games.query.filter_by(name=game).first() channelobj = Channels.query.filter_by(name=channel).first() if not gameobj: msg.append("第 {i} 行导入错误:没有该游戏!".format(i=i)) continue if not channelobj: msg.append("第 {i} 行导入错误:没有该渠道!".format(i=i)) continue if not zonenum: msg.append("第 {i} 行导入错误:区服号不能为空!".format(i=i)) continue if not rowvalues[4].strip(): msg.append("第 {i} 行导入错误:区服名称不能为空!".format(i=i)) continue if not rowvalues[5].strip(): msg.append("第 {i} 行导入错误:区服IP不能为空!".format(i=i)) continue zoneobj = Zones(zonenum=zonenum,zonename=rowvalues[4].strip(), zoneip=rowvalues[5].strip(), dblink=rowvalues[6].strip(), dbport=DB_port, db_A=rowvalues[8].strip(), db_B=rowvalues[9].strip(), db_C=rowvalues[10].strip(), ) db.session.add(zoneobj) db.session.commit() membership = Membership(game=gameobj,channel=channelobj,zone=zoneobj) db.session.add(membership) db.session.commit() msg.append("第 {i} 行导入成功!".format(i=i)) except Exception as e: msg.append(str(e)) return render_template("game/batch_import.html", form=form, title="批量导入",msg=msg)
def process_data_of_hub(hub, data, date_of_crawl=None): """ Process data given by cobot api """ # check if date of crawl is set or not # if not then set it with current date if date_of_crawl is None: date_of_crawl = get_current_date_str() for index, membership_data in enumerate(data): try: # preprocess a membership data in a model suitable # form m_data = preprocess_membership_data(membership_data) # check user exists or not if not create user else get it's # instance user = User.create_or_get(**m_data["user"]) # check membership exists or not if not create membership else # get it's instance membership = Membership.create_or_get(**m_data['membership']) # assign a hub to this membership if not else do nothing membership.assign_hub(hub) # assign a user to this membership if not else do nothing membership.assign_user(user) # check plan exists or not if not create plan else get it's # instance plan = Plan.create_or_get(**m_data['plan']) # check hub_plan exists or not if not create hub_plan else get # it's instance context = { 'hub': hub, 'plan': plan } hub_plan = HubPlan.create_or_get(**context) # check if plan of a membership changed or not if is_membership_plan_changed(membership, hub_plan): # if plan changed then set end_date of last active plan of # a membership as date_of_crawl, if any last_membership_plan = set_end_date_of_last_membership_plan( membership, date_of_crawl) # create a new membership plan instance context = { 'membership': membership, 'hub_plan': hub_plan, 'start_date': get_date_obj_from_str(date_of_crawl) } # and, also set `start_date` of membership plan depending upon # last_membership_plan existence if not last_membership_plan: context['start_date'] = \ m_data['membership']['confirmed_at'] # create a new membership plan membership_plan = MembershipPlan.create(**context) else: # nothing to do pass # check if membership ended or not and, if yes set canceled_to date # of membership and also set end_date of last membership_plan of # this membership_plan m_canceled_date = get_date_obj_from_str( membership_data['canceled_to']) membership.set_canceled_date(m_canceled_date) except Exception as e: logger.error(e, exc_info=True) logger.info("Total {0} Memberships processed on {1} of hub {2}".format( len(data), date_of_crawl, hub.name))
def registration(): if request.method == 'GET': payload = { 'teams': [team.name for team in Teams.query.all()] } response = jsonify(payload) response.status_code = 200 return response elif request.method == 'POST': data = request.get_json() or {} if type(data) == str: data = json.loads(data) payload = { 'message': '', 'validation_errors': [] } if len(data) >= 10: if not login_validating(data['login']): payload['message'] += 'Login validating failed. Login is already using. ' payload['validation_errors'].append('login') if not email_validating(data['email']): payload['message'] += 'Email validating failed. Email is already using.' payload['validation_errors'].append('email') if len(payload['validation_errors']) > 0: response = jsonify(payload) response.status_code = 400 return response data['birthday'] = datetime.datetime.strptime(data['birthday'], '%d-%m-%Y') token_word = # СУПЕР СЕКРЕТНЫЙ И СЛОЖНЫЙ АЛГОРИТМ token_word = hashlib.sha256(token_word.encode()).hexdigest() user = User( data['email'], data['login'], data['tg_nickname'], data['courses'], data['birthday'], data['education'], data['work_exp'], data['sex'], data['name'], data['surname'], token_word ) user.set_password(data['password']) db.session.add(user) db.session.commit() user = User.query.filter_by(email=data['email']).first() if 'team' in data: for team in data['team']: user_team = Membership(user_id=user.id, team_id=Teams.query.filter_by(name=team).first().id, role_id=0) db.session.add(user_team) user_status = UserStatuses(user_id=user.id, status_id=3) db.session.add(user_status) db.session.commit() payload['message'] = 'Registered' payload['token'] = token_word response = jsonify(payload) response.status_code = 200 return response else: return bad_request('Got not enough DATA')
permission_created = True break if not permission_created: p = Permission(value="ICanHaz.access", description="Access to the permission system") p.save() group.permissions.add(p) group.save() names = [] uids = [] for line in codecs.open('admins_to_add.txt', 'r', 'utf-8'): names.append(" ".join(line.split()[:-1])) uids.append(line.split()[-1]) for g, i, j, index in [[v,v,v,v] for v in range(0,len(names))]: try: i = User(name=names[index], uid=uids[index]) i.save() year = str(datetime.now().year) j = Membership(expiration_date=year+'-12-31', user=i) j.save() g = Group.objects.get(name='ICanHaz') g.members.add(j) g.save() print(i.name + " " + i.uid) except Exception as e: print("Failed on user number " + str(index) + " " + e.message, file=sys.stderr)