Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support transient identities and traits #93

Merged
merged 14 commits into from
Jul 19, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Linting and Tests
name: Run Tests

on:
pull_request:
Expand All @@ -9,7 +9,6 @@ on:
jobs:
test:
runs-on: ubuntu-latest
name: Linting and Tests

strategy:
max-parallel: 4
Expand All @@ -33,14 +32,5 @@ jobs:
pip install poetry
poetry install --with dev

- name: Check Formatting
run: |
poetry run black --check .
poetry run flake8 .
poetry run isort --check .

- name: Check Typing
run: poetry run mypy --strict .

- name: Run Tests
run: poetry run pytest
3 changes: 1 addition & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.5.1
rev: v1.10.1
hooks:
- id: mypy
args: [--strict]
Expand All @@ -14,7 +14,6 @@ repos:
rev: 24.3.0
hooks:
- id: black
language_version: python3
- repo: https://github.com/pycqa/flake8
rev: 6.1.0
hooks:
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ For full documentation visit

## Contributing

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code
of conduct, and the process for submitting pull requests
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull
requests

## Getting Help

Expand Down
44 changes: 25 additions & 19 deletions flagsmith/flagsmith.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,14 @@
from flagsmith.offline_handlers import BaseOfflineHandler
from flagsmith.polling_manager import EnvironmentDataPollingManager
from flagsmith.streaming_manager import EventStreamManager, StreamEvent
from flagsmith.utils.identities import Identity, generate_identities_data
from flagsmith.types import JsonType
from flagsmith.utils.identities import generate_identity_data

logger = logging.getLogger(__name__)

DEFAULT_API_URL = "https://edge.api.flagsmith.com/api/v1/"
DEFAULT_REALTIME_API_URL = "https://realtime.flagsmith.com/"

JsonType = typing.Union[
None,
int,
str,
bool,
typing.List["JsonType"],
typing.List[typing.Mapping[str, "JsonType"]],
typing.Dict[str, "JsonType"],
]


class Flagsmith:
"""A Flagsmith client.
Expand Down Expand Up @@ -238,6 +229,9 @@ def get_identity_flags(
self,
identifier: str,
traits: typing.Optional[typing.Mapping[str, TraitValue]] = None,
*,
transient: bool = False,
transient_traits: typing.Optional[typing.List[str]] = None,
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved
) -> Flags:
"""
Get all the flags for the current environment for a given identity. Will also
Expand All @@ -247,13 +241,18 @@ def get_identity_flags(
:param identifier: a unique identifier for the identity in the current
environment, e.g. email address, username, uuid
:param traits: a dictionary of traits to add / update on the identity in
Flagsmith, e.g. {"num_orders": 10}
Flagsmith, e.g. `{"num_orders": 10}`
:param transient: if `True`, the identity won't get persisted
:param transient_traits: a list of trait keys that won't get persisted,
e.g. `["num_orders"]`
:return: Flags object holding all the flags for the given identity.
"""
traits = traits or {}
if (self.offline_mode or self.enable_local_evaluation) and self._environment:
return self._get_identity_flags_from_document(identifier, traits)
return self._get_identity_flags_from_api(identifier, traits)
return self._get_identity_flags_from_api(
identifier, traits, transient=transient, transient_traits=transient_traits
)

def get_identity_segments(
self,
Expand Down Expand Up @@ -339,13 +338,22 @@ def _get_environment_flags_from_api(self) -> Flags:
raise

def _get_identity_flags_from_api(
self, identifier: str, traits: typing.Mapping[str, typing.Any]
self,
identifier: str,
traits: typing.Mapping[str, typing.Any],
*,
transient: bool = False,
transient_traits: typing.Optional[typing.List[str]] = None,
) -> Flags:
request_body = generate_identity_data(
identifier, traits, transient=transient, transient_traits=transient_traits
)
try:
data = generate_identities_data(identifier, traits)
json_response: typing.Dict[str, typing.List[typing.Dict[str, JsonType]]] = (
self._get_json_response(
url=self.identities_url, method="POST", body=data
url=self.identities_url,
method="POST",
body=request_body,
)
)
return Flags.from_api_flags(
Expand All @@ -364,9 +372,7 @@ def _get_json_response(
self,
url: str,
method: str,
body: typing.Optional[
typing.Union[Identity, typing.Dict[str, JsonType]]
] = None,
body: typing.Optional[JsonType] = None,
) -> typing.Any:
Comment on lines +377 to 378
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't the return type be JsonType?

Copy link
Member Author

@khvn26 khvn26 Jul 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return type here corresponds to response.json() type, which is typing.Any.
Casting to a specific type is responsibility of the caller, see e.g.

json_response: typing.Dict[str, typing.List[typing.Dict[str, JsonType]]] = (
self._get_json_response(

try:
request_method = getattr(self.session, method.lower())
Expand Down
2 changes: 1 addition & 1 deletion flagsmith/streaming_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(
stream_url: str,
on_event: Callable[[StreamEvent], None],
request_timeout_seconds: Optional[int] = None,
**kwargs: typing.Any
**kwargs: typing.Any,
) -> None:
super().__init__(*args, **kwargs)
self._stop_event = threading.Event()
Expand Down
14 changes: 14 additions & 0 deletions flagsmith/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import typing

_JsonScalarType = typing.Union[
int,
str,
float,
bool,
None,
]
JsonType = typing.Union[
_JsonScalarType,
typing.Dict[str, "JsonType"],
typing.List["JsonType"],
]
39 changes: 24 additions & 15 deletions flagsmith/utils/identities.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,29 @@

from flag_engine.identities.traits.types import TraitValue

Identity = typing.TypedDict(
"Identity",
{"identifier": str, "traits": typing.List[typing.Mapping[str, TraitValue]]},
)
from flagsmith.types import JsonType


def generate_identities_data(
identifier: str, traits: typing.Optional[typing.Mapping[str, TraitValue]] = None
) -> Identity:
return {
"identifier": identifier,
"traits": (
[{"trait_key": k, "trait_value": v} for k, v in traits.items()]
if traits
else []
),
}
def generate_identity_data(
identifier: str,
traits: typing.Optional[typing.Mapping[str, TraitValue]],
*,
transient: bool,
transient_traits: typing.Optional[typing.List[str]],
) -> JsonType:
identity_data: typing.Dict[str, JsonType] = {"identifier": identifier, "traits": []}
if traits:
traits_data: typing.List[JsonType] = []
transient_trait_keys = set(transient_traits) if transient_traits else set()
for trait_key, trait_value in traits.items():
trait_data: typing.Dict[str, JsonType] = {
"trait_key": trait_key,
"trait_value": trait_value,
}
if trait_key in transient_trait_keys:
trait_data["transient"] = True
traits_data.append(trait_data)
identity_data["traits"] = traits_data
if transient:
identity_data["transient"] = True
return identity_data
71 changes: 35 additions & 36 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 6 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ packages = [{ include = "flagsmith" }]

[tool.poetry.dependencies]
python = ">=3.8.1,<4"
requests = "^2.27.1"
requests-futures = "^1.0.0"
requests = "^2.32.3"
requests-futures = "^1.0.1"
flagsmith-flag-engine = "^5.1.0"
sseclient-py = "^1.8.0"

Expand All @@ -27,14 +27,16 @@ pre-commit = "^2.17.0"
responses = "^0.24.1"
flake8 = "^6.1.0"
isort = "^5.12.0"
mypy = "^1.7.1"
types-requests = "^2.31.0.10"
mypy = "^1.10.1"
types-requests = "^2.32"
pytest-cov = "^4.1.0"

[tool.mypy]
plugins = ["pydantic.mypy"]
exclude = ["example/*"]

[tool.black]
target-version = ["py38"]
matthewelwell marked this conversation as resolved.
Show resolved Hide resolved

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
Loading