def test_fellow_load_state(self): path = "db/" file_name = "mydb" file_ = file_name + ".db" #clean up to avoid conflict between tests os.remove(path + file_) #clear memory stores self.clear_stores() #memory fellow1 = Fellow("osdflkjsd", "eksdlkfjk", "774881228", "Y") fellow1.register() Person.save_state(file_name) #clear memory stores self.clear_stores() #memory Person.load_state(file_name) fellow = Fellow.from_phone("774881228") #db engine = create_engine("sqlite:///" + path + file_, echo=False) Session = sessionmaker(bind=engine) session = Session() db_fellow = session.query(Person).filter_by( phonenumber="774881228").first() session.close() #compare full_fellow = [ fellow.first_name, fellow.last_name, fellow.phone, fellow.type_, fellow.opt_in ] full_db_fellow = [ db_fellow.firstname, db_fellow.lastname, db_fellow.phonenumber, db_fellow.role, db_fellow.optin ] self.assertEqual(full_db_fellow, full_fellow)
async def get_by_ids(self, person_ids: List[UUID]) -> Optional[List[Person]]: """ Возвращает персоны по списку id. """ persons = OrderedDict.fromkeys(person_ids, None) # проверяем есть ли полученные жанры в кеше по их ID for person_id in persons.keys(): data = await self.cache.get(person_id) if data: persons[person_id] = Person.parse_raw(data) # не найденные в кеше персоны запрашиваем в эластике и кладём в кеш not_found = [ person_id for person_id in persons.keys() if persons[person_id] is None ] if not_found: docs = await self.storage.get_by_ids(self._index, not_found) for doc in docs: person = Person(**doc) await self.cache.put(person.id, person.json()) persons[person.id] = person return list(persons.values())
def test_staff_save_state(self): path = "db/" file_name = "mydb" file_ = file_name + ".db" #clean up to avoid conflict between tests os.remove(path + file_) self.clear_stores() #memory staff = Staff("onsn", "edsk", "46546412") staff.register() Person.save_state(file_name) #db engine = create_engine("sqlite:///" + path + file_, echo=False) Session = sessionmaker(bind=engine) session = Session() db_staff = session.query(Person).filter_by( phonenumber="46546412").first() #compare full_staff = [ staff.first_name, staff.last_name, staff.phone, staff.type_, staff.opt_in ] full_db_staff = [ db_staff.firstname, db_staff.lastname, db_staff.phonenumber, db_staff.role, db_staff.optin ] session.close() self.assertEqual(full_staff, full_db_staff)
def add(task_dict): """ task_dict: { 'owner_token' : str(64) -> person.token, 'due': datetime.datetime, 'title': str(), 'body': str(), 'important': bool(), 'done': bool() } """ p = Person.get(task_dict['owner_token']) if not p: raise Exception('Owner does not exist!') try: t = Task( owner_id= p.id, due= task_dict['due'], title= task_dict['title'], body= task_dict['body'], important= task_dict['important'], done= task_dict['done'], token=token_urlsafe(32) ) except: raise Exception('Problem in request dict') redis_client.delete(Person.get_id(t.owner_id).token + '-tasks') db.session.add(t) db.session.commit() redis_client.set(t.token, json.dumps(t.to_dict()), ex=1800) return t
def generate(population=100): print("Genereerin {} inimest".format(population)) print("Loen andmed sisse ...") model = get_model() print("Andmed loetud, hakkan genereerima") data = [] first_time = True for i in range(population): start_date = date(1920, 1, 1) end_date = date(2020, 1, 1) time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_date + timedelta(days=random_number_of_days) person = Person(i + 1, random.choice(['M', 'F']), random_date) person.live(model) data.append(person) print(i + 1) if (i + 1) % 1000 == 0: print("Lisan andmed faili") save_into_file(data, first_time) first_time = False data = [] if len(data) != 0: print("Lisan andmed faili") save_into_file(data, first_time)
def test_person_model_get_all_objects(self): person1 = self.person.copy() person2 = self.person.copy() del person1['uuid'] del person2['uuid'] Person.load(**person1).save() Person.load(**person2).save() self.assertEqual(len(Person.get_all()), 2)
def create(self): person = Person(parent=self.account, name=self.params["name"], identifiers=map(unicode.lower, self.params["identifiers"]), circles=map(unicode.lower, self.params["circles"])) person.put() self.account.people.append(person.key()) self.account.put() self.redirect("/p")
def __init__(self, first_name, last_name, wants_accomodation=False, office_name='', living_space_name=''): Person.__init__(self, first_name, last_name, 'fellow', wants_accomodation) self.office_name = office_name self.living_space_name = living_space_name
def test_list_user_story(self): person_1 = Person("Ilahiya", "Musayeva", '123421') person_2 = Person("Amar", "Musayev", "265571") pb = PhoneBook() pb.add_person(person_1) pb.add_person(person_2) keyword = "show_list" List = ListUserStory(pb) resualt = List.run(keyword) return self.assertTrue([person_1, person_2], resualt)
def test_person_model_to_snake_case(self): example1 = Person.to_snake_case('mydata') self.assertEqual(example1, 'mydata') example2 = Person.to_snake_case('myData') self.assertEqual(example2, 'my_data') example3 = Person.to_snake_case('myExtraData') self.assertEqual(example3, 'my_extra_data') example4 = Person.to_snake_case('convert2Dict') self.assertEqual(example4, 'convert2_dict') example5 = Person.to_snake_case('route53Testing') self.assertEqual(example5, 'route53_testing')
def test_get_ids_by_last_name(): mock_store = mockredis.mock_redis_client(strict=True) person_index = PersonIndex(mock_store) person1 = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person1) person2 = Person(2, 'first', 'last', 30, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person2) ids = person_index.get_ids_by_last_name(person1.last_name) assert ids is not None assert str(1) in ids assert str(2) in ids
def create(): person = Person() person.id = uuid.uuid4() person.vorname = request.json["vorname"] person.nachname = request.json["nachname"] person.email = request.json["email"] person.handy = request.json["handy"] person.save(force_insert=True) return json.dumps(map_to_dict(person), indent=4)
def investor_person(): """ Display investors subscription for a person form """ if request.method == "POST": info = request.form obj = User() obj.username = info['username'] obj.email = info['email'] obj.psswd = info['password'] obj.status = "active" data = Person() data.user = obj.id data.first_name = info['fname'] data.last_name = info['lname'] data.type_id = info['tipo-identificacion'] data.number_identification = info['numberID'] data.born_date = info['date'] inv = Investor() inv.investor = data.id mka = storage mka.reload() mka.new(obj) mka.save() mka.new(data) mka.save() mka.new(inv) mka.save() mka.close() return redirect('/profile-investor/{}'.format(obj.id), code=302) return render_template('signup_naturalperson.html', id=str(uuid.uuid4()))
def report_create_new(): """Создание нового или редактирование отчета""" answer = dict(error='yes', message=u'Произошла ошибка') arg = get_post_arg(request, True) if 'id' not in arg: abort(405) arg['firm_id'] = g.firm_info['id'] report_stack = ReportStack.query.get(arg['id']) if not report_stack: report_stack = ReportStack() if 'details' in arg and 'person' in arg['details']: name = arg['details']['person'] person = Person.get_by_name(g.firm_info['id'], name, 1) if not person: del arg['details']['person'] else: arg['details']['person'] = person[0].id for key in arg: setattr(report_stack, key, arg[key]) if report_stack.save(): answer['error'] = 'no' answer['message'] = u'Отчет сохранен' return jsonify(answer)
def createListOfPpl(self, usr, num): i = 0 usr.listOfPpl = [] while i < num: usr.listOfPpl.append(Person(i)) i += 1 logging.info(len(usr.listOfPpl))
def test_person_model_refresh_object(self): person = Person.load(**self.person) person.save() person.name = 'Tom' self.assertEqual(person.name, 'Tom') person.refresh() self.assertEqual(person.name, self.person['name'])
def get_person_list(): """Получаем список сотрудников фирмы""" arg = json.loads(request.stream.read()) answer = Person.select_list(g.firm_info['id'], **arg) return jsonify(answer)
def query_person(id): is_admin = get_jwt()['is_admin'] print(is_admin) currentUserId = get_jwt_identity() persons = mongo.db.person.find_one_or_404({'_id': id}) person = Person(entries=persons) print(person.family) family = mongo.db.family.find_one_or_404({"_id": person.family}) family = Family(entries=family) print(currentUserId) if person.user_id == currentUserId or check_family_read_auth( family, currentUserId, is_admin): return person.serialize() else: raise ApiError(NO_AUTH, 403)
def check_for_first(self, person): print("--Checking for first_name--") self.first_name = person[0].strip() self.establish_new_connection() try: self.cursor.execute(queries.check_for_person_first( self.first_name)) except Exception as e: print("Exception has occured 99: " + str(e)) result = self.cursor.fetchall() person_to_check = 0 list_result = [list(i) for i in result] if self.check_exists_result(list_result): person = list_result[0] person_dictionary = self.create_person_dict(person) self.person = Person(person_dictionary) user_input = input( f"Oh is this {self.person.first_name} {self.person.last_name}? " ) word_or_phrase = user_input.split()[0] if Word_Manager.is_confirmation( word_or_phrase) or Phrase_Manager.is_confirmation( word_or_phrase): self.update_latest_interaction(self.person) else: return False else: return False
def update(self, key): person = Person.get(key) person.name=self.params["name"] person.identifiers=map(unicode.lower, self.params["identifiers"]) person.circles=map(unicode.lower, self.params["circles"]) person.put() self.redirect("/p")
def test_with_person(self): person_a = Person("User", "1", None) person_b = Person("User", "2", person_a) print_depth({ 'key1': 1, 'key2': { 'key3': 1, 'key4': { 'key5': 4, 'user': person_b } } }) value = self.capturedOutput.getvalue() value = value.strip().split('\n')[-1] self.assertEqual(value, 'father 5', "Should pass with person")
def stuffInfo(): try: if request.method == "POST": raise Exception("method must be get") hr_id = request.values.get("hr_id") if not hr_id: raise Exception("hr_id can not be empty") retrieve_list = [ "user_id", "username", "password", "name", "sex", "identitycard", "tags", "edubackground", "eduschool", "briefintro", "tel", "email", "politicsstatus", "address", "postcode", "workaddress" ] querylist = Person.get_obj(retrieve_list) msg = db.session.query(*querylist, Stafflist.corporation_id, Stafflist.user_id, Hr.corporation_id, Hr.hr_id). \ filter(Hr.hr_id == hr_id, Stafflist.corporation_id == Hr.corporation_id, Stafflist.user_id == Person.user_id) return_msg = [] for line in msg: temp = zip(retrieve_list, line) return_msg.append(dict(temp)) return dict(status=1, message="success", data=return_msg) except Exception as e: return dict(status=0, message=str(e), data="none")
def get_person_profile(token): try: p = Person.get(token) tasks = Task.get_all(token) cnt_tasks = len(tasks) imp_tasks = 0 done_tasks = 0 for t in tasks: if t['done']: done_tasks += 1 if t['important']: imp_tasks += 1 imp_p = 0 done_p = 0 if cnt_tasks != 0: imp_p = imp_tasks / cnt_tasks done_p = done_tasks / cnt_tasks res = { 'tasks': cnt_tasks, 'imp_tasks': imp_tasks, 'done_tasks': done_tasks, 'imp_p': imp_p, 'done_p': done_p, 'user': p.username } return jsonify(res), 200 except Exception as e: return jsonify({'e': e.__str__()}), 500
def get(self): # 통계 데이터 data = {} person = {} visit = {} person["person_statistics"] = Person.person_statistics() person["gender_person_statistics"] = [] for i in Person.gender_person_statistics(): person["gender_person_statistics"].append(i._asdict()) person["race_person_statistics"] = [] for i in Person.race_person_statistics(): person["race_person_statistics"].append(i._asdict()) person["ethnicity_person_statistics"] = [] for i in Person.ethnicity_person_statistics(): person["ethnicity_person_statistics"].append(i._asdict()) person["death_person_statistics"] = Person.death_person_statistics() data["pserson"] = person visit["concept_visit_statistics"] = [] for i in VisitOccurrence.concept_visit_statistics(): visit["concept_visit_statistics"].append(i._asdict()) visit["gender_visit_statistics"] = [] for i in VisitOccurrence.gender_visit_statistics(): visit["gender_visit_statistics"].append(i._asdict()) visit["race_visit_statistics"] = [] for i in VisitOccurrence.race_visit_statistics(): visit["race_visit_statistics"].append(i._asdict()) visit["ethnicity_visit_statistics"] = [] for i in VisitOccurrence.ethnicity_visit_statistics(): visit["ethnicity_visit_statistics"].append(i._asdict()) visit["age_visit_statistics"] = [] for i in VisitOccurrence.age_visit_statistics(): visit["age_visit_statistics"].append(i._asdict()) data['visit'] = visit return jsonify(data)
def test_get_ids_by_last_name_none(): mock_store = mockredis.mock_redis_client(strict=True) person_index = PersonIndex(mock_store) person = Person(1, 'first', 'last', 20, 'github_account', '3rd_grade_grad_date', mock_store) person_index.add_person_to_index(person) ids = PersonIndex(mock_store).get_ids_by_last_name('some_other_id') assert len(ids) is 0
def circles(self): """docstring for circles""" cs = dict() peeps = Person.get(self.people) for person in peeps: for circle in person.circles: cs.setdefault(circle, []).append(person) return cs
def get(self, type, value): param = PersonConcept.parser.parse_args() data = {} data['person_concept'] = person_search_schema.dump( Person.search_person(type, value, param['start'], param['limit'])) return jsonify(data)
def add_by_user_loyalty_id(user_id, loyalty_id): answer = -1 loyalty = PaymentLoyalty.query.filter_by( id=loyalty_id).first() if not loyalty: return False user_wallets = PaymentWallet.query.filter_by(user_id=user_id).all() for wallet in user_wallets: wl = WalletLoyalty.query.filter_by( loyalty_id=loyalty_id, status=WalletLoyalty.STATUS_ON, wallet_id=wallet.id).first() if not wl: continue person = Person.query.filter_by( firm_id=loyalty.firm_id, payment_id=wallet.payment_id).first() if not person: person = Person() person.name = 'Участник промо-кампании' person.firm_id = loyalty.firm_id person.hard_id = wallet.hard_id person.payment_id = wallet.payment_id person.save() if not loyalty.terms_id: continue timeout = PersonEvent.LIKE_TIMEOUT if loyalty.timeout: timeout = loyalty.timeout terms = json.loads(loyalty.terms_id) for term in terms: event = PersonEvent.query.filter_by( person_id=person.id, term_id=term, event_id=loyalty.event_id, firm_id=loyalty.firm_id).first() if event: if event.timeout > timeout: event.status = PersonEvent.STATUS_BANNED event.save() else: event = PersonEvent() event.person_id = person.id event.term_id = term event.event_id = loyalty.event_id event.firm_id = loyalty.firm_id event.timeout = PersonEvent.LIKE_TIMEOUT if loyalty.timeout: event.timeout = loyalty.timeout event.save() answer = event.id return answer
def create_person(name, sid): person = Person(person_id=Game.person_id, name=name, position=flask_app.config.get('SPAWN')) Game.person_id += 1 Game.people.append(person) Game.sid_to_person[sid] = person return person
def init_table_values(self): Person.drop_table(self.database) Person.create_table(self.database) for i in range(self.rows): response_id = int(self.df['respid'][i]) book_count = int(self.df['books1'][i]) state = int(self.df['state'][i]) person = Person(response_id, book_count, state, self.database) person.save()
def edit(): person = Person.get_by_id(request.json["id"]) person.vorname = request.json["vorname"] person.nachname = request.json["nachname"] person.email = request.json["email"] person.handy = request.json["handy"] person.save() return json.dumps(map_to_dict(person), indent=4)
async def get_by_id(self, person_id: UUID) -> List[Person]: """ Возвращает объект персоны. Он опционален, так как персона может отсутствовать в базе """ data = await self.cache.get(person_id) if data: return Person.parse_raw(data) docs = await self.storage.get_by_ids(self._index, [ person_id, ]) if not docs: return None person = Person(**docs[0]) await self.cache.put(person.id, person.json()) return person
def createNewPerson(self, name, lastName, phone, login, password, calification): self.lastPersonId += 1 person = Person(self.lastOrderId, name, lastName, phone, login, password, 0, "no eny role") jsonString = json.dumps(person) with open("Person" + str(person.id) + ".txt", "w") as text_file: text_file.write(jsonString) return person
def all(self): ''' Gets all Person objects in the system, sorted by age :return: collection of Person objects ''' people = [] for id in self._store.zrange(self._age_index, 0, -1): people.append(Person.get_by_id(id)) return people
def person_save(person_id): """Добавляем или редактируем человека""" answer = dict(error='yes', message=u'Произошла ошибка', person_id=0) arg = json.loads(request.stream.read()) form = PersonAddForm.from_json(arg) if person_id == 0: code = arg['card_code'] if 'card_code' in arg else False card_hard_id = arg['card_hard_id'] if 'card_hard_id' in arg else False person = Person() if code or card_hard_id: if code: bind_card = set_person_card(code) else: bind_card = set_person_card_by_hid(card_hard_id) if not bind_card['wallet']: answer['message'] = bind_card['message'] return jsonify(answer) else: wallet = bind_card['wallet'] person.hard_id = wallet.hard_id person.payment_id = bind_card['payment_id'] else: person = Person.query.get(person_id) if not person: abort(404) if not form.validate(): answer['message'] = u"""Форма заполнена неверно, проверьте формат полей""" return jsonify(answer) form.populate_obj(person) if person.save(): answer['person_id'] = person.id answer['error'] = 'no' answer['message'] = u'Данные сохранены' return jsonify(answer) return jsonify(answer)
def person_search(): """Поиск человека""" arg = get_post_arg(request, True) answer = dict(error='yes', content='') if 'person_name' not in arg: abort(400) answer['content'] = 'no' answer['content'] = Person.get_by_firm_id_search( g.firm_info['id'], arg['person_name']) return jsonify(answer)
def show(self, circle): people = None if circle == '*': people = Person.get(self.account.people) else: people = self.account.people_in(circle) people = map( lambda person: dict(key=str(person.key()), name=person.name, identifiers=person.identifiers, circles=person.circles), people) self.write(simplejson.dumps(dict(people=people)));
def person_parse_xls(): """Получение списка сотрудников из *.xls для импорта""" answer = dict( error='yes', message=u'Неверный формат файла', employers=[] ) filepath = Person.save_import_file(request) if not filepath: abort(405) answer['employers'] = Person.excel_to_json_import(filepath) if(os.path.exists(filepath)): os.remove(filepath) if len(answer['employers']) > 0: answer['error'] = 'no' answer['message'] = 'Файл успешно загружен' return jsonify(answer)
def get_person_search_result(): """Поиск сотрудников по запросу""" answer = dict(error='yes', result={}) arg = json.loads(request.stream.read()) if 'request' not in arg: abort(400) limit = arg['limit'] if 'limit' in arg else 5 result = Person.get_by_name(g.firm_info['id'], arg['request'], limit) answer['error'] = 'no' answer['result'] = [row.name for row in result] return jsonify(answer)
def _get_corp(self, result): '''Формируем отчет по пользователям с корпоративными кошельками''' result.col_keys = ReportResult.get_corp_keys() result.col_name = ReportResult.get_corp_col_name() persons = Person.get_dict_by_firm_id(result.firm.id) corp_wallets = TermCorpWallet().get_dict_by_firm_id( result.firm.id) for row in result.report: result.set_terms(row[2]) if row.person_id not in result.persons: result.persons.append(row.person_id) if row[0] not in result.data: tabel_id = persons[row[0]]['tabel_id'] or '' card = persons[row[0]]['card'] or '' result.data[row[0]] = { 'amount': 0, 'name': persons[row[0]]['name'], 'tabel_id': tabel_id, 'card': card } data = result.data[row[0]] if row[0] in corp_wallets: data['wallet_interval'] = corp_wallets[row[0]]['interval'] data['wallet_limit'] = corp_wallets[row[0]]['limit'] / 100 amount = row[1] / 100 data['amount'] = data['amount'] + amount result.all['summ'] += amount result.terms[row[2]]['amount'] = result.terms[ row[2]]['amount'] + amount if 'term' not in data: data['term'] = {} data['term'][row[2]] = row[1] / 100 result.data[row[0]] = data return result
def _get_person(self, result): '''Формируем отчет по всем пользователям из белого списка''' result.col_keys = ReportResult.get_person_keys() result.col_name = ReportResult.get_person_col_name() persons = Person.get_dict_by_firm_id(result.firm.id) for row in result.report: result.set_terms(row[2]) if row.person_id not in result.persons: result.persons.append(row.person_id) if row[0] not in result.data: if row[0] in persons: result.data[row[0]] = { 'amount': 0, 'name': persons[row[0]]['name'], 'tabel_id': persons[row[0]]['tabel_id'], 'card': persons[row[0]]['card'] } else: result.data[row[0]] = { 'amount': 0, 'name': row[3], 'tabel_id': 0, 'card': 0 } data = result.data[row[0]] amount = row[1] / 100 data['amount'] = data['amount'] + amount result.all['summ'] += amount result.terms[row[2]]['amount'] = result.terms[ row[2]]['amount'] + amount if 'term' not in data: data['term'] = {} data['term'][row[2]] = row[1] / 100 result.data[row[0]] = data return result
def get_dict_by_firm_id(self, firm_id): corp_wallet_interval = self.get_interval_list() persons = Person.get_dict_by_firm_id(firm_id) result = {} for key in persons: wallet = self.query.filter_by(person_id=key).first() if not wallet: continue result[key] = dict( interval=corp_wallet_interval[ wallet.interval][ 'name'], limit=wallet.limit, balance=wallet.balance ) return result
class TestPerson(unittest.TestCase): """Tests the person class""" def setUp(self): self._person = Person() def test_first_name(self): """Tests setter and getter of first name of a person""" first_name = "Firstname" self._person.set_first_name(first_name) self.assertEqual(self._person.get_first_name(), first_name) def test_last_name(self): """Tests setter and getter of last name of a person""" last_name = "Lastname" self._person.set_last_name(last_name) self.assertEqual(self._person.get_last_name(), last_name)
def edit(self, key): self.vars["person"] = Person.get(key) self.render("people/edit.html")
def index(self): self.vars["people"] = Person.get(self.account.people) self.render('people/index.html')
def person_import(): """Импорт списка сотрудников из json""" answer = dict( error='yes', wrong_forms=[], wrong_cards=[], added_forms=0 ) data = json.loads(request.stream.read()) employers = data['employers'] for json_employer in employers: if not len(json_employer['name']): answer['wrong_forms'].append(json_employer) continue employer = request_helper.name_together(json_employer) if employer['birthday'] and len(employer['birthday']): try: employer['birthday'] = datetime.strptime( employer['birthday'], '%d.%m.%Y') employer['birthday'] = employer[ 'birthday'].strftime('%Y-%m-%d %H:%M:%S') except ValueError: answer['wrong_forms'].append(json_employer) continue if 'tabel_id' not in employer: employer['tabel_id'] = None elif not len(employer['tabel_id']): employer['tabel_id'] = None employer['firm_id'] = g.firm_info['id'] employer['csrf_token'] = data['csrf_token'] person = Person() form = PersonAddForm.from_json(employer) if not form.validate(): answer['wrong_forms'].append(json_employer) continue form.populate_obj(person) code = employer['code'] if 'code' in employer else False if code and len(code) == 10: bind_card = set_person_card(code) if bind_card['wallet']: wallet = bind_card['wallet'] person.payment_id = wallet.payment_id person.hard_id = wallet.hard_id else: answer['wrong_cards'].append(json_employer) else: answer['wrong_cards'].append(json_employer) answer['added_forms'] = answer['added_forms'] + 1 db.session.add(person) if db.session.commit(): answer['error'] = 'no' return jsonify(answer)
def people_models(self): return Person.get(self.people)
def setUp(self): self._person = Person()