|
7 | 7 | from flag_engine.environments.builders import build_environment_model |
8 | 8 | from flag_engine.environments.models import EnvironmentModel |
9 | 9 | from flag_engine.identities.models import IdentityModel, TraitModel |
| 10 | +from flag_engine.segments.evaluator import get_identity_segments |
10 | 11 | from requests.adapters import HTTPAdapter |
11 | 12 | from urllib3 import Retry |
12 | 13 |
|
13 | 14 | from flagsmith.analytics import AnalyticsProcessor |
14 | 15 | from flagsmith.exceptions import FlagsmithAPIError, FlagsmithClientError |
15 | | -from flagsmith.models import DefaultFlag, Flags |
| 16 | +from flagsmith.models import DefaultFlag, Flags, Segment |
16 | 17 | from flagsmith.polling_manager import EnvironmentDataPollingManager |
17 | 18 | from flagsmith.utils.identities import generate_identities_data |
18 | 19 |
|
@@ -43,7 +44,7 @@ def __init__( |
43 | 44 | custom_headers: typing.Dict[str, typing.Any] = None, |
44 | 45 | request_timeout_seconds: int = None, |
45 | 46 | enable_local_evaluation: bool = False, |
46 | | - environment_refresh_interval_seconds: int = 60, |
| 47 | + environment_refresh_interval_seconds: typing.Union[int, float] = 60, |
47 | 48 | retries: Retry = None, |
48 | 49 | enable_analytics: bool = False, |
49 | 50 | default_flag_handler: typing.Callable[[str], DefaultFlag] = None, |
@@ -129,6 +130,29 @@ def get_identity_flags( |
129 | 130 | return self._get_identity_flags_from_document(identifier, traits) |
130 | 131 | return self._get_identity_flags_from_api(identifier, traits) |
131 | 132 |
|
| 133 | + def get_identity_segments( |
| 134 | + self, identifier: str, traits: typing.Dict[str, typing.Any] = None |
| 135 | + ) -> typing.List[Segment]: |
| 136 | + """ |
| 137 | + Get a list of segments that the given identity is in. |
| 138 | +
|
| 139 | + :param identifier: a unique identifier for the identity in the current |
| 140 | + environment, e.g. email address, username, uuid |
| 141 | + :param traits: a dictionary of traits to add / update on the identity in |
| 142 | + Flagsmith, e.g. {"num_orders": 10} |
| 143 | + :return: list of Segment objects that the identity is part of. |
| 144 | + """ |
| 145 | + |
| 146 | + if not self._environment: |
| 147 | + raise FlagsmithClientError( |
| 148 | + "Local evaluation required to obtain identity segments." |
| 149 | + ) |
| 150 | + |
| 151 | + traits = traits or {} |
| 152 | + identity_model = self._build_identity_model(identifier, **traits) |
| 153 | + segment_models = get_identity_segments(self._environment, identity_model) |
| 154 | + return [Segment(id=sm.id, name=sm.name) for sm in segment_models] |
| 155 | + |
132 | 156 | def update_environment(self): |
133 | 157 | self._environment = self._get_environment_from_api() |
134 | 158 |
|
|
0 commit comments