Code
Hub
Workspaces
Following
Trending
Connect
MCP
copy
Create free account
hub
/
github.com/KonyshevArtem/yandex-academy-task
/ functions
Functions
200 in github.com/KonyshevArtem/yandex-academy-task
⨍
Functions
200
◇
Types & classes
19
↳
Endpoints
11
↓ 11 callers
Method
assert_exception
(self, import_data: dict, expected_exception_message: str)
tests/import_validator_tests.py:16
↓ 9 callers
Method
assert_exception
(self, citizen_id: int, patch_data: dict, expected_exception_message: str)
tests/citizen_patch_validator_tests.py:15
↓ 5 callers
Method
_create_index
Создает индекс в указанной коллекции указанной базы данных. При наличии индекса с таким же именем, но другими параметрами, удаляет и
application/custom_mongo_client.py:43
↓ 5 callers
Function
_make_error_response
Логирует ошибку и возвращает пару из объекта, содержащего сообщение, и кода ошибки :param logging.Logger logger: логгер, которым логируется
application/decorators/exception_handler.py:10
↓ 5 callers
Method
validate_import
Проводит валидацию данных поставки. Проверяется: 1. JSON схема 2. Уникальность идентификаторов жителей 3. Ун
application/data_validator.py:21
↓ 3 callers
Method
validate_citizen_patch
Проводит валидацию данных модификации жителя. Проверяется: 1. JSON схема 2. Уникальность идентификаторов родственник
application/data_validator.py:57
↓ 2 callers
Function
_load_schema
Загружает JSON схему из файла с указанным именем. :param str schema_name: Имя файла, содержащего JSON схема :return: Загруженная JSON сх
application/data_validator.py:79
↓ 2 callers
Function
make_app
(db: Database, data_validator: DataValidator, lock: MongoLock)
application/service.py:22
↓ 1 callers
Function
_add_import_id
Добавляет в данные о жителях поле с уникальным идентификатором набора import_id. :param dict import_data: валидированный набор с данными о ж
application/handlers/post_import_handler.py:21
↓ 1 callers
Function
_cache_data
Сохраняет данные, полученные из указанной поставки в базу данных. :param int import_id: уникальный идентификатор поставки :param str col
application/decorators/response_cacher.py:26
↓ 1 callers
Function
_calculate_age
Вычисляет возраст всех жителей в переданном списке. :param List[dict] citizens: список жителей
application/handlers/get_percentile_age_handler.py:13
↓ 1 callers
Function
_calculate_percentile
Вычисляет процентили p50, p75, p99 по возрастам жителей в городах :param dict grouped: возраста жителей, сгруппированные по городам
application/handlers/get_percentile_age_handler.py:39
↓ 1 callers
Function
_check_all_citizens_exist
Проверяет наличие всех жителей, указанных в relatives_ids в поставке с идентификатором import_id. :param Set[int] citizens_ids: Уникальные и
application/handlers/patch_citizen/update_relatives.py:94
↓ 1 callers
Function
_delete_birthdays_data
Удаляет сохраненные данные о подарках для указанной поставки при наличии поля relatives или birth_date в новых данных о жителе :param in
application/handlers/patch_citizen/patch_citizen_handler.py:67
↓ 1 callers
Function
_delete_percentile_age_data
Удаляет сохраненные данные о возрастах по городам для указанной поставки при наличии поля town или birth_date в новых данных о жителе :p
application/handlers/patch_citizen/patch_citizen_handler.py:84
↓ 1 callers
Function
_get_birthdays_data
Возвращает жителей и количество подарков по месяцам. :param List[dict] citizens: список жителей :return: Словарь количества подарков дл
application/handlers/get_birthdays_handler.py:11
↓ 1 callers
Function
_get_birthdays_representation
Преобразует данные о подарках в формат для отправки ответа. :param dict birthdays_data: данные о подарках :return: Данные о подарках в
application/handlers/get_birthdays_handler.py:27
↓ 1 callers
Function
_get_cached_data
Возвращает закешированные ранее данные из указанной поставки. Если закешированные данные отсутствуют, возвращается None. :param int impo
application/decorators/response_cacher.py:10
↓ 1 callers
Function
_get_citizen_data
Извлекает информацию о жителе из полученной из базы данных информации о поставке. Так же преобразует birth_date из datetime в строку :pa
application/handlers/patch_citizen/patch_citizen_handler.py:51
↓ 1 callers
Function
_get_percentiles_representation
Преобразует данные о возрасте в формат для отправки ответа. :param dict percentiles_data: данные о возрасте :return: Данные о возрасте
application/handlers/get_percentile_age_handler.py:49
↓ 1 callers
Function
_get_relatives
Возвращает сет родственников указанного жителя в указанной поставке. :param int citizen_id: Уникальный идентификатор жителя, чьих родственни
application/handlers/patch_citizen/update_relatives.py:54
↓ 1 callers
Function
_get_relatives_difference
Находит уникальные идентификаторы родственников, у которых нужно добавить/убрать из поля relatives уникальный идентификатор модифицируемого ж
application/handlers/patch_citizen/update_relatives.py:76
↓ 1 callers
Function
_group_by_town
Группирует возраст жителей по городам. :param dict citizens: список жителей :return: возрасты всех жителей, сгруппированные по городам
application/handlers/get_percentile_age_handler.py:24
↓ 1 callers
Function
_initiate_replica_set
Инициализирует replica set через новое подключение к узлу монго. :param str host: адрес узла монго, на котором инициируется replica set :para
application/custom_mongo_client.py:9
↓ 1 callers
Function
_make_db_requests
Создает запросы для вставки/удаления указанного citizen_id из поля relatives у всех жителей, чей индекс входит в to_push/to_pull в поставке с
application/handlers/patch_citizen/update_relatives.py:34
↓ 1 callers
Function
_make_update_relatives_request
Создает объект запроса к базе данных для изменения списка уникальных идентификаторов родственников у нескольких жителей. В запросе проис
application/handlers/patch_citizen/update_relatives.py:10
↓ 1 callers
Function
_parse_birth_date
Парсит поле birth_date у каждого жителя из строки в datetime. :param dict import_data: набор с данными о жителях
application/handlers/post_import_handler.py:11
↓ 1 callers
Function
_parse_birth_date
При наличии поля birth_date, парсит его из строки в datetime. :param dict patch_data: Новая информация о жителе
application/handlers/patch_citizen/patch_citizen_handler.py:14
↓ 1 callers
Function
_write_citizen_update
Записывает обновление информации о жителе в базу данных. :param int citizen_id: Уникальный идентификатор модифицируемого жителя :param i
application/handlers/patch_citizen/patch_citizen_handler.py:24
↓ 1 callers
Function
_write_relatives_update
При наличии запросов в db_request производит их запись в базу данных. :param List[UpdateMany] db_requests: Список запросов к базе данных на
application/handlers/patch_citizen/update_relatives.py:113
↓ 1 callers
Function
_write_to_db
Производит запись набора данных о жителях в базу данных. :param import_data: валидированный набор данных о жителях :param db: объект баз
application/handlers/post_import_handler.py:32
↓ 1 callers
Method
create_db_indexes
Создает необходимые индексы в базе данных. :param str db_name: имя базы данных, в которой необходимо создать индексы
application/custom_mongo_client.py:31
↓ 1 callers
Function
create_mock_validator
Создает фейковый экземпляр класса DataValidator :return: фейковый экземпляр класса DataValidator :rtype: DataValidator
tests/test_utils.py:34
↓ 1 callers
Function
decorator
(f)
application/decorators/response_cacher.py:50
↓ 1 callers
Function
get_birthdays
Возвращает жителей и количество подарков, которые они будут покупать своим ближайшим родственникам (1-го порядка), сгруппированных по месяц
application/handlers/get_birthdays_handler.py:42
↓ 1 callers
Function
get_fake_db
Создает экземпляр фейковой базы данных.
tests/test_utils.py:61
↓ 1 callers
Function
get_percentile_age
Возвращает статистику по городам для указанного набора данных в разрезе возраста (полных лет) жителей: p50, p75, p99, где число - это значен
application/handlers/get_percentile_age_handler.py:63
↓ 1 callers
Function
patch_citizen
Изменяет информацию о жителе в указанном наборе данных. На вход подается JSON в котором можно указать любые данные о жителе. :param int
application/handlers/patch_citizen/patch_citizen_handler.py:102
↓ 1 callers
Function
post_import
Принимает на вход набор с данными о жителях в формате json и сохраняет его с уникальным идентификатором import_id. :param dict import_da
application/handlers/post_import_handler.py:51
↓ 1 callers
Method
start_session
(self)
tests/test_utils.py:30
↓ 1 callers
Function
update_relatives
При наличии поля relatives в patch_data производит обновление поля relatives у всех родственников обновляемого жителя. :param int citize
application/handlers/patch_citizen/update_relatives.py:128
↓ 1 callers
Function
wrap
(*args, **kwargs)
application/decorators/response_cacher.py:52
Method
__init__
(self, host: str, port: int, replica_set: str)
application/custom_mongo_client.py:27
Method
__init__
(self)
application/data_validator.py:17
Method
__init__
(self, **kwargs)
tests/test_utils.py:21
Method
__init__
(self)
tests/handlers_tests/post_import_handler_tests.py:77
Function
birthdays
Возвращает жителей и количество подарков, которые они будут покупать своим ближайшим родственникам (1-го порядка), сгруппированных
application/service.py:90
Function
cache_response
Декоратор, проверяющий наличие закешированных данных в указанной коллекции перед выполнением обработчика. При отсутсвии закешированных данны
application/decorators/response_cacher.py:40
Function
citizen
Изменяет информацию о жителе в указанном наборе данных. На вход подается JSON в котором можно указать любые данные о жителе.
application/service.py:48
Function
citizens
Возвращает список всех жителей для указанного набора данных. :param int import_id: Уникальный идентификатор поставки :retu
application/service.py:71
Function
decorator
(f)
application/decorators/exception_handler.py:32
Method
f
()
tests/decorators_tests/exception_handler_tests.py:31
Method
f
(import_id: int)
tests/decorators_tests/response_cacher_tests.py:42
Function
get_citizens
Возвращает список жителей в указанной поставке, выбранный с указанной проекцией. :param int import_id: уникальный идентификатор поставки
application/handlers/shared.py:7
Function
handle_exceptions
Декоратор, обворачивающий указанную функцию в блок обработки ошибок. Логирует все появивишиеся ошибки с помощью логгера, переданного на вход
application/decorators/exception_handler.py:24
Function
imports
Принимает на вход набор с данными о жителях в формате json и сохраняет его с уникальным идентификатором import_id. :raises:
application/service.py:27
Function
percentile_age
Возвращает статистику по городам для указанного набора данных в разрезе возраста (полных лет) жителей: p50, p75, p99, где число - эт
application/service.py:106
Function
read_data
Считывает JSON из указанного файла. :param str filename: имя файла из которого нужно считать JSON :return: считанный объект :rtype:
tests/test_utils.py:47
Method
setUp
(cls)
tests/import_post_tests.py:13
Method
setUp
(cls)
tests/citizens_get_tests.py:9
Method
setUp
(cls)
tests/birthdays_get_tests.py:10
Method
setUp
(cls)
tests/percentile_age_get_tests.py:10
Method
setUp
(cls)
tests/citizen_patch_tests.py:14
Method
setUp
(cls)
tests/decorators_tests/exception_handler_tests.py:12
Method
setUp
(self)
tests/decorators_tests/response_cacher_tests.py:14
Method
setUpClass
(cls)
tests/citizen_patch_validator_tests.py:12
Method
setUpClass
(cls)
tests/import_validator_tests.py:13
Function
set_up_service
Производит подготовку сервиса к тестированию. :return: Запущенный сервис, фейковый монго клиент, фейковый валидатор :rtype: Tuple[Flask,
tests/test_utils.py:66
Method
test_add_import_id_should_add_count_of_imports
(self)
tests/handlers_tests/post_import_handler_tests.py:58
Method
test_add_import_id_should_add_zero_when_db_empty
(self)
tests/handlers_tests/post_import_handler_tests.py:51
Method
test_cache_data_should_write_all_dict_fields
(self)
tests/decorators_tests/response_cacher_tests.py:23
Method
test_cache_data_should_write_to_db
(self)
tests/decorators_tests/response_cacher_tests.py:17
Method
test_calculate_age_should_append_age_when_one_citizen
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:13
Method
test_calculate_age_should_calculate_when_birth_date_in_leap_year
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:19
Method
test_calculate_age_should_do_nothing_when_citizens_empty
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:9
Method
test_calculate_percentile_should_do_nothing_when_empty_grouped
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:39
Method
test_calculate_percentile_should_return_integers
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:43
Method
test_calculate_percentile_when_multiple_citizens
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:54
Method
test_calculate_percentile_when_multiple_towns
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:59
Method
test_calculate_percentile_when_one_citizen
(self)
tests/handlers_tests/get_percentile_age_handler_tests.py:49
Method
test_check_citizens_exists_should_do_nothing_when_citizens_empty
(self)
tests/handlers_tests/update_relatives_tests.py:73
Method
test_check_citizens_exists_should_not_raise_when_citizen_exists
(self)
tests/handlers_tests/update_relatives_tests.py:78
Method
test_check_citizens_exists_should_raise_when_at_least_one_citizen_dont_exists
(self)
tests/handlers_tests/update_relatives_tests.py:89
Method
test_check_citizens_exists_should_raise_when_citizen_dont_exists
(self)
tests/handlers_tests/update_relatives_tests.py:84
Method
test_correct_import_should_be_valid
(self)
tests/import_validator_tests.py:22
Method
test_correct_patch_should_be_valid
(self)
tests/citizen_patch_validator_tests.py:20
Method
test_decorator_return_error_response_when_exception_raised
(self)
tests/decorators_tests/exception_handler_tests.py:37
Method
test_decorator_should_cache_data_when_not_cache_not_present
(self)
tests/decorators_tests/response_cacher_tests.py:71
Method
test_decorator_should_not_cache_when_exception_in_func
(self)
tests/decorators_tests/response_cacher_tests.py:83
Method
test_decorator_should_not_call_func_when_cached_data_present
(self)
tests/decorators_tests/response_cacher_tests.py:50
Method
test_decorator_should_return_cached_data_when_present
(self)
tests/decorators_tests/response_cacher_tests.py:38
Method
test_decorator_should_return_function_response_not_cache_not_present
(self)
tests/decorators_tests/response_cacher_tests.py:59
Method
test_decorator_should_return_function_result_when_no_exception
(self)
tests/decorators_tests/exception_handler_tests.py:29
Method
test_delete_birthdays_should_delete_when_birth_date_in_patch
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:92
Method
test_delete_birthdays_should_delete_when_relatives_in_patch
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:84
Method
test_delete_birthdays_should_do_nothing_when_no_birthdays
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:100
Method
test_delete_birthdays_should_do_nothing_when_no_relatives_and_no_birth_date_in_patch
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:77
Method
test_delete_percentile_age_should_delete_when_birth_date_in_patch
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:122
Method
test_delete_percentile_age_should_delete_when_town_in_patch
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:114
Method
test_delete_percentile_age_should_do_nothing_when_no_percentile_age
(self)
tests/handlers_tests/patch_citizen_handler_tests.py:130
next →
1–100 of 200, ranked by callers