polyapi 0.0.5__tar.gz → 5.9.20__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. {polyapi-0.0.5 → polyapi-5.9.20}/LICENSE.txt +1 -1
  2. polyapi-5.9.20/PKG-INFO +73 -0
  3. polyapi-5.9.20/README.md +39 -0
  4. polyapi-5.9.20/polyapi.egg-info/PKG-INFO +73 -0
  5. polyapi-5.9.20/polyapi.egg-info/SOURCES.txt +53 -0
  6. polyapi-5.9.20/polyapi.egg-info/requires.txt +12 -0
  7. polyapi-5.9.20/polyapi.egg-info/top_level.txt +1 -0
  8. polyapi-5.9.20/polymatica/__init__.py +5 -0
  9. polyapi-5.9.20/polymatica/authorization.py +197 -0
  10. polyapi-5.9.20/polymatica/business_logic_doc.py +104 -0
  11. polyapi-5.9.20/polymatica/business_scenarios.py +9513 -0
  12. polyapi-5.9.20/polymatica/commands/__init__.py +11 -0
  13. polyapi-5.9.20/polymatica/commands/base_command.py +78 -0
  14. polyapi-5.9.20/polymatica/commands/olap_module.py +58 -0
  15. polyapi-5.9.20/polymatica/commands/other_modules.py +34 -0
  16. polyapi-5.9.20/polymatica/common/__init__.py +12 -0
  17. polyapi-5.9.20/polymatica/common/consts.py +222 -0
  18. polyapi-5.9.20/polymatica/common/helper_funcs.py +361 -0
  19. polyapi-5.9.20/polymatica/common/params_models.py +87 -0
  20. polyapi-5.9.20/polymatica/error_handler.py +1549 -0
  21. polyapi-5.9.20/polymatica/exceptions.py +173 -0
  22. polyapi-5.9.20/polymatica/executor.py +428 -0
  23. polyapi-5.9.20/polymatica/graph/__init__.py +7 -0
  24. polyapi-5.9.20/polymatica/graph/base_graph.py +408 -0
  25. polyapi-5.9.20/polymatica/graph/graph_interface.py +498 -0
  26. polyapi-5.9.20/polymatica/graph/types/__init__.py +44 -0
  27. polyapi-5.9.20/polymatica/graph/types/areas.py +65 -0
  28. polyapi-5.9.20/polymatica/graph/types/balls.py +88 -0
  29. polyapi-5.9.20/polymatica/graph/types/chord.py +71 -0
  30. polyapi-5.9.20/polymatica/graph/types/circles.py +91 -0
  31. polyapi-5.9.20/polymatica/graph/types/circles_series.py +87 -0
  32. polyapi-5.9.20/polymatica/graph/types/corridors.py +84 -0
  33. polyapi-5.9.20/polymatica/graph/types/cumulative_areas.py +77 -0
  34. polyapi-5.9.20/polymatica/graph/types/cumulative_cylinders.py +83 -0
  35. polyapi-5.9.20/polymatica/graph/types/cylinders.py +90 -0
  36. polyapi-5.9.20/polymatica/graph/types/graph.py +173 -0
  37. polyapi-5.9.20/polymatica/graph/types/lines.py +82 -0
  38. polyapi-5.9.20/polymatica/graph/types/pies.py +97 -0
  39. polyapi-5.9.20/polymatica/graph/types/point.py +83 -0
  40. polyapi-5.9.20/polymatica/graph/types/point_series.py +95 -0
  41. polyapi-5.9.20/polymatica/graph/types/pools.py +87 -0
  42. polyapi-5.9.20/polymatica/graph/types/pools_3d.py +84 -0
  43. polyapi-5.9.20/polymatica/graph/types/radar.py +60 -0
  44. polyapi-5.9.20/polymatica/graph/types/sankey.py +51 -0
  45. polyapi-5.9.20/polymatica/graph/types/surface.py +87 -0
  46. polyapi-5.9.20/polymatica/helper.py +1300 -0
  47. polyapi-5.9.20/pyproject.toml +43 -0
  48. {polyapi-0.0.5 → polyapi-5.9.20}/setup.cfg +4 -4
  49. polyapi-5.9.20/setup.py +33 -0
  50. polyapi-5.9.20/tests/test_create_sphere.py +754 -0
  51. polyapi-5.9.20/tests/test_create_sphere_dims_measures.py +993 -0
  52. polyapi-5.9.20/tests/test_create_sphere_links_multisource.py +671 -0
  53. polyapi-5.9.20/tests/test_update_cube.py +622 -0
  54. polyapi-0.0.5/CHANGELOG.txt +0 -23
  55. polyapi-0.0.5/MANIFEST.in +0 -3
  56. polyapi-0.0.5/PKG-INFO +0 -58
  57. polyapi-0.0.5/README.txt +0 -18
  58. polyapi-0.0.5/polyapi/__init__.py +0 -0
  59. polyapi-0.0.5/polyapi/authorization.py +0 -106
  60. polyapi-0.0.5/polyapi/business_logic_doc.py +0 -61
  61. polyapi-0.0.5/polyapi/business_scenarios.py +0 -4037
  62. polyapi-0.0.5/polyapi/error_handler.py +0 -326
  63. polyapi-0.0.5/polyapi/executor.py +0 -321
  64. polyapi-0.0.5/polyapi/helper.py +0 -342
  65. polyapi-0.0.5/polyapi/manager_commands.py +0 -73
  66. polyapi-0.0.5/polyapi/olap_commands.py +0 -118
  67. polyapi-0.0.5/polyapi/precondition.py +0 -47
  68. polyapi-0.0.5/polyapi.egg-info/PKG-INFO +0 -58
  69. polyapi-0.0.5/polyapi.egg-info/SOURCES.txt +0 -20
  70. polyapi-0.0.5/polyapi.egg-info/requires.txt +0 -4
  71. polyapi-0.0.5/polyapi.egg-info/top_level.txt +0 -1
  72. polyapi-0.0.5/setup.py +0 -1
  73. {polyapi-0.0.5 → polyapi-5.9.20}/polyapi.egg-info/dependency_links.txt +0 -0
@@ -1,4 +1,4 @@
1
- Copyright 2020 Polymatica Rus LLC
1
+ Copyright 2020-2025 Polymatica Rus LLC
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
4
  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyapi
3
+ Version: 5.9.20
4
+ Summary: Wrapper for Polymatica API
5
+ Home-page: https://slsoft.ru/products/polymatica/
6
+ Author: Polymatica Rus LLC
7
+ Author-email: polymatica_support@slsoft.ru
8
+ License: MIT
9
+ Keywords: polymatica
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: End Users/Desktop
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: setuptools
17
+ Requires-Dist: numpy==1.19.5; python_version < "3.9"
18
+ Requires-Dist: numpy>1.21.1; python_version >= "3.9"
19
+ Requires-Dist: pandas<=1.2.5,>=1.1.5; python_version < "3.9"
20
+ Requires-Dist: pandas>2.0.0; python_version >= "3.9"
21
+ Requires-Dist: requests>=2.27.1
22
+ Requires-Dist: pydantic<=2.5.3,>=1.9.2
23
+ Requires-Dist: packaging
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: requires-dist
33
+ Dynamic: summary
34
+
35
+
36
+ # Основные сведения
37
+ Библиотека предназначена для работы с Polymatica API.
38
+
39
+ # Работа с библиотекой
40
+ Основным модулем бизнес-логики является файл business_scenarios.py,
41
+ импортировать который можно с помощью команды ``from polymatica import business_scenarios as sc``.
42
+
43
+ Модуль предоставляет два класса для работы с Полиматикой - ``BusinessLogic`` и ``GetDataChunk``.
44
+ Методы этих классов можно посмотреть при помощи стандартной функции ``dir()``.
45
+
46
+ Аргументы функций и прочую docstring-документацию модуля и функций можно посмотреть
47
+ при помощи стандартной функции ``help()``.
48
+
49
+ ### Инициализация нового клиентского подключения:
50
+ ``session = sc.BusinessLogic(login="your_login", password="your_password", url="polymatica_server_url", **args)``
51
+
52
+ ### Пример создания слоя и воспроизведения сценария на этом слое с использованием PolyAPI
53
+
54
+ Создадим слой:
55
+ ``session.execute_manager_command(command_name="user_layer", state="create_layer")``
56
+
57
+ Запросим список сценариев:
58
+ ``session.execute_manager_command(command_name="scripts", state="get_script_descriptions_list")``
59
+
60
+ Загрузим сценарий на слой, используя полученные на предыдущих шагах идентификаторы слоя и сценария:
61
+ ``session.execute_manager_command(command_name="scripts", state="load_on_layer", runtime_id="d46b7075", script_id="40fc65db", on_load_action=0)``
62
+
63
+ Воспроизведем сценарий:
64
+ ``session.execute_manager_command(command_name="scripts", state="play_to_position", runtime_id="d46b7075", script_id="40fc65db", play_to_position=23, clear_workspace=True)``
65
+
66
+ Получим статус воспроизведения сценария:
67
+ ``session.execute_manager_command(command_name="scripts", state="get_script_status", runtime_id="d46b7075")``
68
+
69
+ Получили ответ, из которого видим, что сценарий воспроизведен успешно:
70
+ ``{'state': 1, 'queries': [{'uuid': '872bdbde-20b9f734-2a5a5ad5-9b08e670', 'command': {'plm_type_code': 227, 'state': 6, 'script_status': {'id': '40fc65db', 'action_name': '', 'status': 3, 'current_step': 24, 'steps_count': 24, 'errors': []}}}]}``
71
+
72
+ Получим информацию о слое:
73
+ ``session.execute_manager_command(command_name="user_layer", state="get_layer", layer_id="d46b7075")``
@@ -0,0 +1,39 @@
1
+
2
+ # Основные сведения
3
+ Библиотека предназначена для работы с Polymatica API.
4
+
5
+ # Работа с библиотекой
6
+ Основным модулем бизнес-логики является файл business_scenarios.py,
7
+ импортировать который можно с помощью команды ``from polymatica import business_scenarios as sc``.
8
+
9
+ Модуль предоставляет два класса для работы с Полиматикой - ``BusinessLogic`` и ``GetDataChunk``.
10
+ Методы этих классов можно посмотреть при помощи стандартной функции ``dir()``.
11
+
12
+ Аргументы функций и прочую docstring-документацию модуля и функций можно посмотреть
13
+ при помощи стандартной функции ``help()``.
14
+
15
+ ### Инициализация нового клиентского подключения:
16
+ ``session = sc.BusinessLogic(login="your_login", password="your_password", url="polymatica_server_url", **args)``
17
+
18
+ ### Пример создания слоя и воспроизведения сценария на этом слое с использованием PolyAPI
19
+
20
+ Создадим слой:
21
+ ``session.execute_manager_command(command_name="user_layer", state="create_layer")``
22
+
23
+ Запросим список сценариев:
24
+ ``session.execute_manager_command(command_name="scripts", state="get_script_descriptions_list")``
25
+
26
+ Загрузим сценарий на слой, используя полученные на предыдущих шагах идентификаторы слоя и сценария:
27
+ ``session.execute_manager_command(command_name="scripts", state="load_on_layer", runtime_id="d46b7075", script_id="40fc65db", on_load_action=0)``
28
+
29
+ Воспроизведем сценарий:
30
+ ``session.execute_manager_command(command_name="scripts", state="play_to_position", runtime_id="d46b7075", script_id="40fc65db", play_to_position=23, clear_workspace=True)``
31
+
32
+ Получим статус воспроизведения сценария:
33
+ ``session.execute_manager_command(command_name="scripts", state="get_script_status", runtime_id="d46b7075")``
34
+
35
+ Получили ответ, из которого видим, что сценарий воспроизведен успешно:
36
+ ``{'state': 1, 'queries': [{'uuid': '872bdbde-20b9f734-2a5a5ad5-9b08e670', 'command': {'plm_type_code': 227, 'state': 6, 'script_status': {'id': '40fc65db', 'action_name': '', 'status': 3, 'current_step': 24, 'steps_count': 24, 'errors': []}}}]}``
37
+
38
+ Получим информацию о слое:
39
+ ``session.execute_manager_command(command_name="user_layer", state="get_layer", layer_id="d46b7075")``
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.4
2
+ Name: polyapi
3
+ Version: 5.9.20
4
+ Summary: Wrapper for Polymatica API
5
+ Home-page: https://slsoft.ru/products/polymatica/
6
+ Author: Polymatica Rus LLC
7
+ Author-email: polymatica_support@slsoft.ru
8
+ License: MIT
9
+ Keywords: polymatica
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Intended Audience :: End Users/Desktop
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: setuptools
17
+ Requires-Dist: numpy==1.19.5; python_version < "3.9"
18
+ Requires-Dist: numpy>1.21.1; python_version >= "3.9"
19
+ Requires-Dist: pandas<=1.2.5,>=1.1.5; python_version < "3.9"
20
+ Requires-Dist: pandas>2.0.0; python_version >= "3.9"
21
+ Requires-Dist: requests>=2.27.1
22
+ Requires-Dist: pydantic<=2.5.3,>=1.9.2
23
+ Requires-Dist: packaging
24
+ Dynamic: author
25
+ Dynamic: author-email
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: home-page
29
+ Dynamic: keywords
30
+ Dynamic: license
31
+ Dynamic: license-file
32
+ Dynamic: requires-dist
33
+ Dynamic: summary
34
+
35
+
36
+ # Основные сведения
37
+ Библиотека предназначена для работы с Polymatica API.
38
+
39
+ # Работа с библиотекой
40
+ Основным модулем бизнес-логики является файл business_scenarios.py,
41
+ импортировать который можно с помощью команды ``from polymatica import business_scenarios as sc``.
42
+
43
+ Модуль предоставляет два класса для работы с Полиматикой - ``BusinessLogic`` и ``GetDataChunk``.
44
+ Методы этих классов можно посмотреть при помощи стандартной функции ``dir()``.
45
+
46
+ Аргументы функций и прочую docstring-документацию модуля и функций можно посмотреть
47
+ при помощи стандартной функции ``help()``.
48
+
49
+ ### Инициализация нового клиентского подключения:
50
+ ``session = sc.BusinessLogic(login="your_login", password="your_password", url="polymatica_server_url", **args)``
51
+
52
+ ### Пример создания слоя и воспроизведения сценария на этом слое с использованием PolyAPI
53
+
54
+ Создадим слой:
55
+ ``session.execute_manager_command(command_name="user_layer", state="create_layer")``
56
+
57
+ Запросим список сценариев:
58
+ ``session.execute_manager_command(command_name="scripts", state="get_script_descriptions_list")``
59
+
60
+ Загрузим сценарий на слой, используя полученные на предыдущих шагах идентификаторы слоя и сценария:
61
+ ``session.execute_manager_command(command_name="scripts", state="load_on_layer", runtime_id="d46b7075", script_id="40fc65db", on_load_action=0)``
62
+
63
+ Воспроизведем сценарий:
64
+ ``session.execute_manager_command(command_name="scripts", state="play_to_position", runtime_id="d46b7075", script_id="40fc65db", play_to_position=23, clear_workspace=True)``
65
+
66
+ Получим статус воспроизведения сценария:
67
+ ``session.execute_manager_command(command_name="scripts", state="get_script_status", runtime_id="d46b7075")``
68
+
69
+ Получили ответ, из которого видим, что сценарий воспроизведен успешно:
70
+ ``{'state': 1, 'queries': [{'uuid': '872bdbde-20b9f734-2a5a5ad5-9b08e670', 'command': {'plm_type_code': 227, 'state': 6, 'script_status': {'id': '40fc65db', 'action_name': '', 'status': 3, 'current_step': 24, 'steps_count': 24, 'errors': []}}}]}``
71
+
72
+ Получим информацию о слое:
73
+ ``session.execute_manager_command(command_name="user_layer", state="get_layer", layer_id="d46b7075")``
@@ -0,0 +1,53 @@
1
+ LICENSE.txt
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ setup.py
6
+ polyapi.egg-info/PKG-INFO
7
+ polyapi.egg-info/SOURCES.txt
8
+ polyapi.egg-info/dependency_links.txt
9
+ polyapi.egg-info/requires.txt
10
+ polyapi.egg-info/top_level.txt
11
+ polymatica/__init__.py
12
+ polymatica/authorization.py
13
+ polymatica/business_logic_doc.py
14
+ polymatica/business_scenarios.py
15
+ polymatica/error_handler.py
16
+ polymatica/exceptions.py
17
+ polymatica/executor.py
18
+ polymatica/helper.py
19
+ polymatica/commands/__init__.py
20
+ polymatica/commands/base_command.py
21
+ polymatica/commands/olap_module.py
22
+ polymatica/commands/other_modules.py
23
+ polymatica/common/__init__.py
24
+ polymatica/common/consts.py
25
+ polymatica/common/helper_funcs.py
26
+ polymatica/common/params_models.py
27
+ polymatica/graph/__init__.py
28
+ polymatica/graph/base_graph.py
29
+ polymatica/graph/graph_interface.py
30
+ polymatica/graph/types/__init__.py
31
+ polymatica/graph/types/areas.py
32
+ polymatica/graph/types/balls.py
33
+ polymatica/graph/types/chord.py
34
+ polymatica/graph/types/circles.py
35
+ polymatica/graph/types/circles_series.py
36
+ polymatica/graph/types/corridors.py
37
+ polymatica/graph/types/cumulative_areas.py
38
+ polymatica/graph/types/cumulative_cylinders.py
39
+ polymatica/graph/types/cylinders.py
40
+ polymatica/graph/types/graph.py
41
+ polymatica/graph/types/lines.py
42
+ polymatica/graph/types/pies.py
43
+ polymatica/graph/types/point.py
44
+ polymatica/graph/types/point_series.py
45
+ polymatica/graph/types/pools.py
46
+ polymatica/graph/types/pools_3d.py
47
+ polymatica/graph/types/radar.py
48
+ polymatica/graph/types/sankey.py
49
+ polymatica/graph/types/surface.py
50
+ tests/test_create_sphere.py
51
+ tests/test_create_sphere_dims_measures.py
52
+ tests/test_create_sphere_links_multisource.py
53
+ tests/test_update_cube.py
@@ -0,0 +1,12 @@
1
+ setuptools
2
+ requests>=2.27.1
3
+ pydantic<=2.5.3,>=1.9.2
4
+ packaging
5
+
6
+ [:python_version < "3.9"]
7
+ numpy==1.19.5
8
+ pandas<=1.2.5,>=1.1.5
9
+
10
+ [:python_version >= "3.9"]
11
+ numpy>1.21.1
12
+ pandas>2.0.0
@@ -0,0 +1 @@
1
+ polymatica
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/python3
2
+ """ Пакет работы с Polymatica API """
3
+ from polymatica.business_scenarios import BusinessLogic, GetDataChunk
4
+
5
+ __all__ = ["BusinessLogic", "GetDataChunk"]
@@ -0,0 +1,197 @@
1
+ #!/usr/bin/python3
2
+ """ Модуль авторизации в Полиматике """
3
+
4
+ import json
5
+ from typing import Dict, List, Optional, Tuple
6
+
7
+ import requests
8
+
9
+ from .common import request_with_undefined_suffix_url
10
+ from .exceptions import AuthError
11
+
12
+
13
+ class Authorization:
14
+ """Предоставляет возможность авторизации в Полиматике"""
15
+
16
+ def login(
17
+ self,
18
+ user_name: Optional[str],
19
+ base_url: str,
20
+ server_codes: Dict,
21
+ timeout: float,
22
+ language: str,
23
+ suffixes_url: List,
24
+ is_guest: bool,
25
+ password: Optional[str],
26
+ session_id: str = "",
27
+ ) -> Tuple:
28
+ """
29
+ Авторизация (парольная/беспарольная/через идентификатор сессии).
30
+ В метод может быть передан логин-пароль, тогда на сервер будет отправлена команда 205-2; может быть
31
+ передан только логин, без пароля, тогда метод получит session_id от сервера и отправит ему 205-1;
32
+ может быть передан session_id, тогда тоже будет отправлена команда 205-1.
33
+ :param user_name: имя пользователя.
34
+ :param base_url: базовый URL стенда Полиматики.
35
+ :param server_codes: значение файла "server_codes.json", хранящего коды команд и их состояний.
36
+ :param timeout: тайм-аут выполнения запроса авторизации.
37
+ :param language: язык локализации; возможны значения: "en" / "ru" / "de" / "fr".
38
+ :param is_guest: флаг гостевого пользователя при беспарольной авторизации.
39
+ :param password: пароль пользователя; может быть не задан (None).
40
+ :param suffixes_url: список возможных суффиксов URL-адреса стенда Полиматики.
41
+ :param session_id: идентификатор сессии, необязательный параметр.
42
+ :return: (Tuple) идентификатор сессии, uuid, полная версия Полиматики.
43
+ """
44
+ self._check_language(language)
45
+
46
+ if not isinstance(suffixes_url, list):
47
+ raise AuthError('Incorrect "suffixes_url" param: expected list type!')
48
+ suffixes_url.insert(0, "")
49
+
50
+ auth_manager_command = server_codes.get("manager", {}).get("command", {}).get("authenticate", {})
51
+ auth_command = auth_manager_command.get("id")
52
+ auth_check = auth_manager_command.get("state", {}).get("check")
53
+ auth_login = auth_manager_command.get("state", {}).get("login")
54
+ locale_value = server_codes.get("locale", {}).get(language)
55
+
56
+ # для авторизации без пароля формируем id сессии для беспарольного пользователя
57
+ if session_id == "" and password is None:
58
+ is_guest_str = self._check_guest(is_guest)
59
+ login_url = f"{base_url}login?login={user_name}&is_guest={is_guest_str}"
60
+ r = requests.get(url=login_url)
61
+ if not r.ok:
62
+ msg = (
63
+ 'Stand "{}" not supporting non-password authorization. Please, specify the password! '
64
+ 'Details: Code: {}, Reason: "{}", Text: {}'.format(
65
+ base_url,
66
+ r.status_code,
67
+ r.reason,
68
+ "<empty>" if not r.text else r.text,
69
+ )
70
+ )
71
+ raise AuthError(msg)
72
+ else:
73
+ try:
74
+ response = r.json()
75
+ except json.decoder.JSONDecodeError:
76
+ msg = 'Invalid server response! Details: URL: {}, Code: {}, Reason: "{}", Text: {}'.format(
77
+ login_url,
78
+ r.status_code,
79
+ r.reason,
80
+ "<empty>" if not r.text else r.text,
81
+ )
82
+ raise AuthError(msg)
83
+ session_id = response.get("session")
84
+
85
+ # формирование поля command
86
+ command = {"plm_type_code": auth_command}
87
+ if password is None:
88
+ command.update({"state": auth_check})
89
+ else:
90
+ command.update(
91
+ {
92
+ "state": auth_login,
93
+ "login": user_name,
94
+ "passwd": password,
95
+ "locale": locale_value,
96
+ }
97
+ )
98
+
99
+ # формирование тела и заголовка запроса
100
+ params = {
101
+ "state": 0,
102
+ "session": session_id,
103
+ "queries": [{"uuid": "00000000-00000000-00000000-00000000", "command": command}],
104
+ }
105
+ headers = {"Content-Type": "text/plain; charset=utf-8", "Accept": "text/plain"}
106
+
107
+ # отправляем запрос аутентификации на заданный URL
108
+ r, suffix_url = request_with_undefined_suffix_url(
109
+ suffixes_url, base_url, self._get_prepare_query(params), timeout, headers
110
+ )
111
+
112
+ # проверки и вывод результата
113
+ status_code = r.status_code
114
+ if not r.ok:
115
+ error_msg = 'Invalid server response (URL: {}, Code: {}, Reason: "{}", Text: {})'.format(
116
+ r.url, status_code, r.reason, "<empty>" if not r.text else r.text
117
+ )
118
+ raise AuthError(error_msg)
119
+
120
+ try:
121
+ json_response = r.json()
122
+ except json.decoder.JSONDecodeError:
123
+ raise AuthError("Server response cannot be converted to the JSON format")
124
+ return self._authorization_checks(params, json_response, status_code, suffix_url)
125
+
126
+ def _get_command(self, data: Dict) -> Dict:
127
+ """
128
+ Возвращает команду запроса/ответа.
129
+ """
130
+ queries = next(iter(data.get("queries")))
131
+ return queries.get("command")
132
+
133
+ def _authorization_checks(self, request: Dict, response: Dict, response_code: int, url_suffix: str) -> Tuple:
134
+ """
135
+ Проверка успешности авторизации. Возвращает идентификатор сессии и manager uuid.
136
+ :param request: (Dict) запрос.
137
+ :param response: (Dict) ответ.
138
+ :param response_code: (int) код ответа.
139
+ :param url_suffix: (str) верное окончание URL-адреса стенда Полиматики.
140
+ :return: (Tuple) идентификатор сессии, uuid, полная версия Полиматики, url_suffix
141
+ """
142
+ # получаем команды и коды запроса/ответа
143
+ request_command = self._get_command(request)
144
+ request_code = request_command.get("plm_type_code")
145
+ resp_command = self._get_command(response)
146
+ resp_code = resp_command.get("plm_type_code")
147
+
148
+ # проверки полученных кодов
149
+ assert "error" not in resp_command, resp_command.get("error", "No error description!")
150
+ assert response_code == 200, "Response code != 200"
151
+ assert (
152
+ request_code == resp_code
153
+ ), f"Request plm_type_code ({request_code}) is not equal response plm_type_code ({resp_code})!"
154
+
155
+ # проверки идентификаторов session_id и uuid
156
+ session_id, uuid = resp_command.get("session_id"), resp_command.get("manager_uuid")
157
+ assert session_id != "", "incorrect session_id specified, such session does not exist!"
158
+ assert session_id is not None, "session_id is None!"
159
+ assert uuid != "", "manager_id is empty!"
160
+ assert uuid is not None, "manager_id is None!"
161
+
162
+ return session_id, uuid, resp_command.get("version"), url_suffix
163
+
164
+ def _check_language(self, language: str):
165
+ """
166
+ Проверка пользовательского значения языка локализации.
167
+ Если проверка пройдена - ничего не вернёт, в противном случае будет сгенерирована ошибка AuthError.
168
+ :param locale: (str) пользовательское значение языка.
169
+ """
170
+ if language not in ("ru", "en"):
171
+ error_msg = f'Invalid language! Expected: "ru"/"en", found: "{language}"'
172
+ raise AuthError(error_msg)
173
+
174
+ def _check_guest(self, guest_param: bool) -> str:
175
+ """
176
+ Проверка параметра "is_guest": должны быть только булевы значения. В противном случае сгенерируется ошибка.
177
+ Возвращает строковое значение параметра.
178
+ """
179
+ if not isinstance(guest_param, bool):
180
+ error_msg = f'Invalid "is_guest" param! Expected: True/False, found: "{guest_param}"'
181
+ raise AuthError(error_msg)
182
+ return "true" if guest_param else "false"
183
+
184
+ def _get_prepare_query(self, query: Dict) -> str:
185
+ """
186
+ Подготовка тела запроса для дальнейшей отправки POST-запросом: обработка кириллицы в логине/пароле.
187
+ :param query: (Dict) параметры запроса в формате JSON.
188
+ :return: (str) параметры запроса в формате строки.
189
+ """
190
+ params = str(query)
191
+ return (
192
+ params.replace("'", '"')
193
+ .replace("False", "false")
194
+ .replace("True", "true")
195
+ .replace("None", "null")
196
+ .encode("utf-8")
197
+ )
@@ -0,0 +1,104 @@
1
+ #!/usr/bin/python3
2
+ """
3
+ Базовый класс, описывающий бизнес-сценарии использования Полиматики.
4
+ Используемые переменные класса:
5
+
6
+ # Флаг работы в Jupiter Notebook
7
+ self.jupiter
8
+
9
+ # Флаг гостевого пользователя при беспарольной авторизации
10
+ self.is_guest
11
+
12
+ # Текст ошибки присваивается в случае аварийного завершения работы; может быть удобно при работе в Jupiter Notebook
13
+ self.current_exception
14
+
15
+ # Версия сервера Полиматики; например, '5.6'
16
+ self.polymatica_version
17
+
18
+ # Полная версия сервера Полиматики; например, '5.6.14-ab9def0-7799123f-x86_64-centos'
19
+ self.full_polymatica_version
20
+
21
+ # Язык интерфейса. Задается во время авторизации. Возможно задать следующие значения: "ru", "en".
22
+ # По-умолчанию "ru"
23
+ self.language
24
+
25
+ # Базовый URL стенда Полиматики (тот, что передаётся в конструктор при инициализации класса)
26
+ self.base_url
27
+
28
+ # Таймаут выполнения запросов
29
+ self.timeout
30
+
31
+ # Логин пользователя Полиматики
32
+ self.login
33
+
34
+ # Для измерения времени работы функций бизнес-логики
35
+ self.func_timing
36
+
37
+ # Таблица команд и состояний
38
+ self.server_codes
39
+
40
+ # Идентификатор активного OLAP-модуля (мультисферы)
41
+ self.multisphere_module_id
42
+
43
+ # Идентификатор куба, соответствующего активному OLAP-модулю
44
+ self.cube_id
45
+
46
+ # Название куба, соответствующего активному OLAP-модулю
47
+ self.cube_name
48
+
49
+ # Список идентификаторов всех слоёв
50
+ self.layers_list
51
+
52
+ # Идентификатор активного слоя
53
+ self.active_layer_id
54
+
55
+ # Данные мультисферы в формате {"dimensions": "", "facts": "", "data": ""}
56
+ self.multisphere_data
57
+
58
+ # Общее число строк текущего (активного) OLAP-модуля
59
+ self.total_row
60
+
61
+ # Идентификатор активного модуля графиков
62
+ self.graph_module_id
63
+
64
+ # URL стенда Полиматики, использующийся для вызова серверных команд
65
+ self.command_url
66
+
67
+ # URL стенда Полиматики для обращения к ресурсам
68
+ self.resources_url
69
+
70
+ # Идентификатор сессии
71
+ self.session_id
72
+
73
+ # Идентификатор (uuid) авторизации
74
+ self.authorization_uuid
75
+
76
+ # Класс, выполняющий HTTP-запросы
77
+ self.exec_request
78
+
79
+ # Объект выполнения команд модуля Manager
80
+ self.manager_command
81
+
82
+ # Объект выполнения команд модуля OLAP
83
+ self.olap_command
84
+
85
+ # Объект выполнения команд модуля Graph
86
+ self.graph_command
87
+
88
+ # Helper class
89
+ self.h
90
+
91
+ # Сохранённое имя функции для избежания конфликтов с декоратором
92
+ self.func_name
93
+
94
+ # Содержимое DataFrame
95
+ self.df
96
+
97
+ # Колонки DataFrame
98
+ self.df_cols
99
+
100
+ # Вспомогательный класс, перенаправляющий вызовы методов на нужные реализации (в зависимости от версии)
101
+ self.version_redirect
102
+ """
103
+
104
+ __name__ = "BusinessLogic"