def fake_group(): group1 = Group(capacity=4, creator="Jeff") group2 = Group(capacity=9, creator="Minni") group3 = Group(capacity=5, creator="Larry") group4 = Group(capacity=6, creator="Micky") db.session.add(group1) #adding to our database db.session.add(group2) db.session.add(group3) db.session.add(group4) db.session.commit()
def create_admin(name, email, password, require_empty): logger = log.getLogger() g.request_id = "cli" g.request_start_time = datetime.utcnow() if require_empty: if Group.query.count() > 0 and User.query.count() > 0: logger.info( 'Some users and groups already exist in the database. No changes were made.' ) return try: group = Group(name='public', capabilities=[]) db.session.add(group) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() logger.exception('Group public already exists, no changes were made.') else: logger.info('Succesfully added group public"') try: group = Group(name=name, capabilities=Capabilities.all(), private=True) db.session.add(group) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() logger.exception('Group already exists, no changes were made.') else: logger.info('Succesfully added group %s', name) group = db.session.query(Group).filter(Group.name == name).first() try: user = User(login=name, email=email) user.set_password(password) user.version_uid = '0' * 16 user.identity_ver = '0' * 16 user.password_ver = '0' * 16 user.groups.append(group) user.groups.append(Group.public_group()) db.session.add(user) db.session.commit() except sqlalchemy.exc.IntegrityError: db.session.rollback() logger.exception('User already exists, no changes were made.') else: logger.info('Succesfully added admin user %s', name)
def get_test_selection(self): return [ Group(name=name, header=header, footer=footer) for name in ["", random_string("name", self.name_max_len)] for header in ["", random_string("header", self.data_max_len)] for footer in ["", random_string("footer", self.data_max_len)] ]
def add_group(): form = AddadminForm() if form.validate_on_submit(): name = request.form.get('name') powerlist = request.form.get('powerlist') group = Group(name=name, power=powerlist, addtime=datetime.datetime.now()) group_check = db_session.query(Group).filter( Group.name == name).first() if group_check: flash('用户组已存在') return redirect('/manage/add_group') if len(name) and len(powerlist): try: db_session.add(group) db_session.commit() db_session.close() except: flash("数据库错误!") return redirect('/manage/add_group') flash("添加成功,<span id='time'>3</span>秒后自动跳转管理页。") return redirect('/manage/add_group') return render_template("add_group.html", pagename='manage_group', form=form)
def auto_create_by_instrument_family(class_id, family): """Create band instrument groups.""" # new_group = Group.query.filter_by(class_id=class_id).filter_by(name=family).one() # if new_group is []: new_group = Group(class_id=class_id, name=family) db.session.add(new_group) # new_group = Group(class_id=class_id, name=family) #find students with woodwind instruments all_students = Student.query.filter_by(class_id=class_id).all() for student in all_students: all_instruments = Instrument.query.filter_by( student_id=student.student_id).all() for instrument in all_instruments: if instrument.name.family == family: this_student = StudentGroup(student_id=student.student_id, group_id=new_group.group_id) db.session.add(this_student) db.session.commit() pass
def load_groups(): """Load groups from groups.txt into database.""" print "Groups" Group.query.delete() for row in open("seed_data/groups.txt"): row = row.rstrip() group_id, group_name, group_descrip, group_image, admin_id, vote_timestamp, vote_days, hashtag = row.split( "|") if vote_timestamp == "": vote_timestamp = None if vote_days == "": vote_days = None group = Group(group_id=group_id, group_name=group_name, group_descrip=group_descrip, group_image=group_image, admin_id=admin_id, vote_timestamp=vote_timestamp, vote_days=vote_days, hashtag=hashtag) db.session.add(group) db.session.commit()
def post(self, name): schema = GroupSchema() obj = schema.loads(request.get_data(as_text=True)) if obj.errors: return {"errors": obj.errors}, 400 group_name_obj = GroupNameSchemaBase().load({"name": name}) if group_name_obj.errors: return {"errors": group_name_obj.errors}, 400 if db.session.query(exists().where(Group.name == name)).scalar(): raise Conflict("Group exists yet") group = Group() group.name = name group.capabilities = obj.data.get("capabilities") or [] db.session.add(group) db.session.commit() logger.info('group created', extra={ 'group': group.name, 'capabilities': group.capabilities }) schema = GroupSchema() return schema.dump({"name": obj.data.get("name")})
def parse_json(self, json_list): """ Parses a JSON list and creates a UserAndGroup object. :param json_list: List of JSON objects that represent users and groups. :returns: A user and group container with the users and groups. :rtype: UsersAndGroups """ auag = UsersAndGroups() for value in json_list: if str(value["principalTypeEnum"]).endswith("_USER"): user = User( name=value.get("name", None), display_name=value.get("displayName", None), mail=value.get("mail", None), group_names=value.get("groupNames", None), visibility=value.get("visibility", None), created=value.get("created", None), id=value.get("id", None) ) # TODO remove after testing. if auag.has_user(user.name): print("WARNING: Duplicate user %s already exists." % user.name) else: auag.add_user(user) else: group = Group( name=value.get("name", None), display_name=value.get("displayName", None), description=value.get("description", None), group_names=value.get("groupNames", None), visibility=value.get("visibility", None), ) auag.add_group(group) return auag
def createNewGroup(new_group_name, new_collaborators_user_objs, book_id, translation_language): """ Creates new UserGroups and BookGroup for database. """ new_group_obj = Group(group_name=new_group_name) db.session.add(new_group_obj) # create usergroup db.session.commit() new_usergroup_obj = UserGroup(user_id=session["login"][1], group_id=new_group_obj.group_id) db.session.add(new_usergroup_obj) for a_collaborator in new_collaborators_user_objs: new_usergroup_obj = UserGroup(user_id=a_collaborator.user_id, group_id=new_group_obj.group_id) db.session.add(new_usergroup_obj) db.session.commit() # create bookgroup new_bookgroup_obj = BookGroup(group_id=new_group_obj.group_id, book_id=book_id, language=translation_language) db.session.add(new_bookgroup_obj) db.session.commit() return new_bookgroup_obj
def edit_group(): getid = request.args.get('group_id') groupData = db_session.query(Group).filter(Group.group_id == getid).\ with_entities(Group.name, Group.power, Group.group_id).first() form = EditadminForm() if groupData: form.group_id.data = groupData.group_id form.name.data = groupData.name form.powerlist.data = groupData.power db_session.close() if form.validate_on_submit(): group_id = request.form.get('group_id') name = request.form.get('name') powerlist = request.form.get('powerlist') group = Group(name=name, power=powerlist) db_session.query(Group).filter(Group.group_id == group_id).update({ Group.name: name, Group.power: powerlist }) db_session.commit() db_session.close() flash("修改成功,<span id='time'>3</span>秒后自动跳转管理页。") return redirect('/manage/edit_group') return render_template("edit_group.html", pagename='manage_group', form=form)
def load_groups(): """Load groups from group.txt into database.""" print "Groups" for i, row in enumerate(open("data/group.txt")): row = row.rstrip() group_code, name, description, end, start = row.split(", ") start_date = datetime.datetime.strptime(start, "%m/%d/%Y") if end: end_date = datetime.datetime.strptime(end, "%m/%d/%Y") else: end_date = None group = Group(group_code=group_code, name=name, description=description, start_date=start_date, end_date=end_date) # Add to the session. db.session.add(group) # Commit the session/data to the dbase. db.session.commit()
def get_groups_count(self, count): return [ Group(name=random_string("name", self.name_max_len), header=random_string("header", self.data_max_len), footer=random_string("footer", self.data_max_len)) for _ in range(count) ]
def create_group(group_name): """Create a group""" group = Group(group_name=group_name) db.session.add(group) db.session.commit() return group
def create_group(search_id, user_id): """ Create new group and store group info """ group = Group(search_id=search_id, user_id=user_id) db.session.add(group) db.session.commit() return group.group_id
def createGroup(groupname): if not groupname.isalnum(): raise UserError("Invalid Groupname, Must Be Alphanumeric") elif GROUPS.groupnameExists(groupname): raise UserError("Group Exists") group = Group(groupname) GROUPS.addGroup(group) return group.serialize()
def get_group_list(self): if self.group_cache is None: wd = self.app.wd self.open_groups_page() self.group_cache = [] for element in wd.find_elements_by_css_selector("span.group"): self.group_cache.append( Group(id=element.find_element_by_name( "selected[]").get_attribute("value"), name=element.text)) return self.group_cache
def post(self, login): schema = UserProfileManageInfoSchema() obj = schema.loads(request.get_data(as_text=True)) if obj.errors: return {"errors": obj.errors}, 400 user_login_obj = UserLoginSchemaBase().load({"login": login}) if user_login_obj.errors: return {"errors": user_login_obj.errors}, 400 if db.session.query(exists().where(User.login == login)).scalar(): raise Conflict("User exists yet") if db.session.query(exists().where(Group.name == login)).scalar(): raise Conflict("Group exists yet") user = User() user.login = login user.email = obj.data.get("email") user.additional_info = obj.data.get("additional_info") user.feed_quality = obj.data.get("feed_quality") user.disabled = False user.pending = False user.registered_by = g.auth_user.id user.registered_on = datetime.datetime.now() user.groups.append(Group.public_group()) user.reset_sessions() db.session.add(user) group = Group() group.name = login group.private = True group.users.append(user) db.session.add(group) if obj.data.get("send_email", False): try: send_email_notification("register", "New account registered in Malwarecage", user.email, base_url=app_config.malwarecage.base_url, login=user.login, set_password_token=user.generate_set_password_token().decode("utf-8")) except MailError: logger.exception("Can't send e-mail notification") raise InternalServerError("SMTP server needed to fulfill this request is" " not configured or unavailable.") db.session.commit() logger.info('User created', extra={'user': user.login}) schema = UserSuccessSchema() return schema.dump({"login": user.login})
def get_groups(): """Load groups from list into database.""" groups = ["shelter", "sharing", "unsheltered", "motel"] for item in groups: group = Group(group_name=item) db.session.add(group) db.session.commit()
def get_group_list(self): list = [] with (self.connection.cursor()) as cursor: cursor.execute( "select group_id, group_name, group_header, group_footer from group_list" ) for row in cursor: id, name, header, footer = row list.append( Group(id=str(id), name=name, header=header, footer=footer)) return list
def post(self, name): """ --- summary: Create a new group description: | Creates a new group. Requires `manage_users` capability. security: - bearerAuth: [] tags: - group parameters: - in: path name: name schema: type: string description: Group name responses: 200: description: When group was created successfully 400: description: When group name or request body is invalid 403: description: When user doesn't have `manage_users` capability 409: description: When group exists yet """ schema = GroupSchema() obj = schema.loads(request.get_data(as_text=True)) if obj.errors: return {"errors": obj.errors}, 400 group_name_obj = GroupNameSchemaBase().load({"name": name}) if group_name_obj.errors: return {"errors": group_name_obj.errors}, 400 if db.session.query(exists().where(Group.name == name)).scalar(): raise Conflict("Group exists yet") group = Group() group.name = name group.capabilities = obj.data.get("capabilities") or [] db.session.add(group) db.session.commit() logger.info('group created', extra={ 'group': group.name, 'capabilities': group.capabilities }) schema = GroupSchema() return schema.dump({"name": obj.data.get("name")})
def add_sample_groups(num): """""" for i in range(1, num + 1): group_name = "Group" + str(i) new_group = Group(group_name=group_name, ) print new_group db.session.add(new_group) db.session.commit()
def create_group_process(): """Creates group.""" #get form variables class_id = request.form["class_id"] name = request.form["name"] #create new group object new_group = Group(class_id=class_id, name=name) #add new group to session and commit db.session.add(new_group) db.session.commit() #flash confirmation and redirect to add another group flash("New Group successfully created.") return redirect("/groups")
def _on_register(self): # init variables self._recognized_sensors = {} self._recognized_measurement_containers = {} # init base structure label = 'devices' container = Container(resourceName=label) group = Group(resourceName="test") self._devices_container = self.create_container(None, container, labels=[label], max_nr_of_instances=0) # trigger periodically new data generation self.run_forever(1, self.get_random_data) # log message self.logger.debug('registered')
def register_user(self, **kwargs): """ Register a new user in the database. Either nick or email attributes is required. """ assert ("nick" in kwargs or "email" in kwargs) session = db.Session() group = session.query(Group).filter(Group.name == USERS_GROUP).first() if group is None: group = Group(name=USERS_GROUP, desc="Users") session.add(group) user = User(**kwargs) if user.name is None: user.name = user.nick or user.email user.groups += [group] session.add(user) session.commit() return user
def add_lfg_details(): """Add lfg details to DB.""" user = session['current_user'] user = User.query.filter_by(username=user).first() user_id = user.user_id game = session['lfg'] game = Game.query.filter_by(title=game).first() game_id = game.game_id comment = request.form.get('comment') new_lfg = Group(game_id=game_id, user_id=user_id, comment=comment, lfg=True) db.session.add(new_lfg) db.session.commit() return redirect('/profile')
def add_word(group, w_data): print(w_data['lexicalEntries'][0]['pronunciations'][0]['audioFile']) group_letter = group word = w_data['word'] audio = w_data['lexicalEntries'][0]['pronunciations'][0]['audioFile'] ipa_spelling = w_data['lexicalEntries'][0]['pronunciations'][0][ 'phoneticSpelling'] group = None try: group = session.query(Group).filter_by(letter=group_letter).one() except Exception: print('Go on and add new Group') if not group: group = Group(letter=group_letter) session.add(group) session.flush() session.add( Entry(word=word, audio=audio, ipa_spelling=ipa_spelling, group_id=group.id)) session.commit() session.close()
def create_group(): try: data = json.loads(request.data) print(data["owner_id"], file=sys.stderr) groups = Group.query.filter_by(owner_id=data["owner_id"]).all() for i in groups: if i.restReturn["name"] == data["name"]: return jsonify({ "status": "FAILED", "reason": "User already ownes group with the given name" }) newGroup = Group(owner_id=data["owner_id"], name=data["name"]) db.session.add(newGroup) db.session.commit() user = Users.query.filter_by(id=data["owner_id"]).one() data = user.restReturn data.update({ "status": "SUCCESS" }) return jsonify(data) except: e = sys.exc_info() traceback.print_exception(*e)
def load_groups(): """Load groups from the group.csv file into the database""" print "Loading groups..." # Reads the csv and inserts it. with open('seed_data/group_type.csv') as csvfile: read_line = csv.reader(csvfile) # Must read before for loop for row in read_line: # Skips over the first line of code which has labels on it if row[0] == 'ID': continue else: # Assign parameters to the data and change to the correct datatype group = Group(group_id=int(row[0]), group_name=row[1], min_age=int(row[2]), max_age=int(row[3]), gender=row[4]) db.session.add(group) db.session.commit()
def post(self): """ --- description: Request new user account tags: - auth requestBody: description: User basic information content: application/json: schema: UserRegisterSchema responses: 200: description: User login on successful registration content: application/json: schema: UserSuccessSchema """ if not app_config.malwarecage.enable_registration: raise Forbidden("User registration is not enabled.") schema = UserRegisterSchema() obj = schema.loads(request.get_data(as_text=True)) if obj.errors: return {"errors": obj.errors}, 400 login = obj.data.get("login") if db.session.query(exists().where(User.login == login)).scalar(): raise Conflict("Name already exists") if db.session.query(exists().where(Group.name == login)).scalar(): raise Conflict("Name already exists") recaptcha_secret = app_config.malwarecage.recaptcha_secret if recaptcha_secret: try: recaptcha_token = obj.data.get("recaptcha") recaptcha_response = requests.post( 'https://www.google.com/recaptcha/api/siteverify', data={ 'secret': recaptcha_secret, 'response': recaptcha_token }) recaptcha_response.raise_for_status() except Exception as e: logger.exception("Temporary problem with ReCAPTCHA.") raise InternalServerError( "Temporary problem with ReCAPTCHA.") from e if not recaptcha_response.json().get('success'): raise Forbidden("Wrong ReCAPTCHA, please try again.") user = User() user.login = login user.email = obj.data.get("email") user.additional_info = obj.data.get("additional_info") user.pending = True user.disabled = False user.requested_on = datetime.datetime.now() user.groups.append(Group.public_group()) user.reset_sessions() db.session.add(user) group = Group() group.name = login group.private = True group.users.append(user) db.session.add(group) db.session.commit() try: send_email_notification("pending", "Pending registration in Malwarecage", user.email, base_url=app_config.malwarecage.base_url, login=user.login) except MailError: logger.exception("Can't send e-mail notification") logger.info('User registered', extra={'user': user.login}) schema = UserSuccessSchema() return schema.dump({"login": user.login})
def process_classics_users(): # just to get a sense of timing print_time() # get a list of groups related to our classics keyword groups = gc.find_groups(CLASSICS_GROUP_KEYWORD) # make sure we get all pages gpage = 1 while groups: # while groups and gpage == 1: # for testing print '*' * 10, 'group page', gpage for group_dict in groups: # for group_dict in groups[0:1]: # for testing # skip this group if its already been processed if Group.query.get(group_dict['id']): print '\t\t\talready added group id', group_dict['id'], ', skipping...' continue # get actual group object group = gc.group(group_dict['id']) # group = gc.group(95455) # testing # note: some group names are unicode (greek!) and don't translate well to ascii group_name = group.title.encode('unicode-escape') print '***** processing group', group.gid, group_name # make sure we get all pages of members mpage = 1 member_results = True # keep track of whether it was processed successfully process_success = True while member_results: print '\tmember page', mpage try: member_results = group.get_members(page=mpage) except Exception as e: try: err_string = str(e) except: err_string = '<no error string>' print '~~~~~~~~ ERROR: problem getting members:', err_string print "~~~~~~~~ Moving on." # record that it was not successfully processed process_success=False break for member in member_results: user_id = member['id']['#text'] # skip this user if already processed if User.query.get(user_id): continue # otherwise, add the reviews (and add the user to the db) success = add_reviews_by_user(user_id) mpage += 1 # we're done with this group -- put it in the db so we can skip it # if we re-process group_row = Group(group_id=group.gid, group_name=group_name, process_success=process_success) db.session.add(group_row) db.session.commit() # get the next page gpage += 1 groups = gc.find_groups(CLASSICS_GROUP_KEYWORD, page=gpage)