-
Notifications
You must be signed in to change notification settings - Fork 1
AB#241796: Add cache for Kobo data #65
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
Merged
sergey-misuk-valor
merged 5 commits into
develop
from
feature/241796-add-cache-on-projects-for-kobo
Apr 3, 2025
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ae348d3
Add cache for Kobo data
sergey-misuk-personal 524dcaa
Fix tests
sergey-misuk-personal e47bd26
Add few more tests
sergey-misuk-personal 1333546
Add docstring to DataGetter
sergey-misuk-personal b6b8872
Merge branch 'develop' into feature/241796-add-cache-on-projects-for-…
domdinicola File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,70 @@ | ||
| from collections.abc import Callable | ||
| from typing import Any, TypedDict | ||
|
|
||
| from requests import Response | ||
| from django.core.cache import cache | ||
| from requests import Response, Session, HTTPError | ||
|
|
||
| DataGetter = Callable[[str], Response] | ||
| UrlPredicate = Callable[[str], bool] | ||
|
|
||
|
|
||
| class ResponseDict(TypedDict): | ||
| """Dictionary for response data.""" | ||
|
|
||
| json: dict[str, Any] | ||
| status_code: int | ||
|
|
||
|
|
||
| class CachedResponse: | ||
| """Wrapper resembling requests.Response.""" | ||
|
|
||
| def __init__(self, response_dict: ResponseDict) -> None: | ||
| self._response_dict = response_dict | ||
|
|
||
| def json(self) -> dict[str, Any]: | ||
| return self._response_dict["json"] | ||
|
|
||
| @property | ||
| def status_code(self) -> int: | ||
| return self._response_dict["status_code"] | ||
|
|
||
| def raise_for_status(self) -> None: | ||
| pass | ||
|
|
||
|
|
||
| def data_getter_cache_key(url: str) -> str: | ||
| return f"dg:{url}" | ||
|
|
||
|
|
||
| class DataGetter: | ||
| def __init__( | ||
| self, | ||
| session: Session, | ||
| cache_ttl: int, | ||
| headers: dict[str, str] | None = None, | ||
| do_not_use_cache_if: UrlPredicate | None = None, | ||
| ) -> None: | ||
| self._session = session | ||
| self._headers = headers | ||
| self._cache_ttl = cache_ttl | ||
| self._do_not_use_cache_if = do_not_use_cache_if | ||
|
|
||
| def __call__(self, url: str) -> Response | CachedResponse: | ||
| if self._do_not_use_cache_if and self._do_not_use_cache_if(url): | ||
| return self._session.get(url, headers=self._headers) | ||
|
|
||
| cache_key = data_getter_cache_key(url) | ||
|
|
||
| if cached_value := cache.get(cache_key): | ||
| return CachedResponse(cached_value) | ||
|
|
||
| response = self._session.get(url, headers=self._headers) | ||
| try: | ||
| response.raise_for_status() | ||
| except HTTPError: | ||
| # don't cache failed response | ||
| return response | ||
|
|
||
| value: ResponseDict = {"json": response.json(), "status_code": response.status_code} | ||
| cache.set(cache_key, value, self._cache_ttl) | ||
|
|
||
| return response | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,32 +1,25 @@ | ||
| from unittest.mock import Mock | ||
|
|
||
| from pytest_mock import MockerFixture | ||
|
|
||
| from country_workspace.contrib.kobo.api.client.main import ACCEPT_JSON_HEADERS, Client | ||
| from country_workspace.contrib.kobo.api.client.main import Client | ||
|
|
||
|
|
||
| def test_client(mocker: MockerFixture) -> None: | ||
| session_class = mocker.patch("country_workspace.contrib.kobo.api.client.main.Session") | ||
| session = session_class.return_value | ||
| auth_class = mocker.patch("country_workspace.contrib.kobo.api.client.main.Auth") | ||
| auth = auth_class.return_value | ||
| partial = mocker.patch("country_workspace.contrib.kobo.api.client.main.partial") | ||
| data_getter = partial.return_value | ||
| data_getter_mock = Mock() | ||
| get_asset_list_url = mocker.patch("country_workspace.contrib.kobo.api.client.main.get_asset_list_url") | ||
| url = get_asset_list_url.return_value | ||
| get_asset_list = mocker.patch("country_workspace.contrib.kobo.api.client.main.get_asset_list") | ||
| get_asset_list.return_value = [] | ||
|
|
||
| tuple( | ||
| Client( | ||
| data_getter=data_getter_mock, | ||
| base_url=(base_url := "https://test.org"), | ||
| token=(token := "test-token"), | ||
| country_code=(country_code := "CNT"), | ||
| project_view_id=(project_view_id := "project-view-id"), | ||
| ).assets | ||
| ) | ||
|
|
||
| get_asset_list_url.assert_called_once_with(base_url, project_view_id, country_code) | ||
| session_class.assert_called_once() | ||
| auth_class.assert_called_once_with(token) | ||
| assert session.auth == auth | ||
| partial.assert_called_once_with(session.get, headers=ACCEPT_JSON_HEADERS) | ||
| get_asset_list.assert_called_with(data_getter, url) | ||
| get_asset_list.assert_called_with(data_getter_mock, url) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| from country_workspace.contrib.kobo.api.common import CachedResponse | ||
|
|
||
|
|
||
| def test_cached_response() -> None: | ||
| cached_response = CachedResponse( | ||
| { | ||
| "json": (expected_json := {"foo": "bar"}), | ||
| "status_code": (expected_status_code := 42), | ||
| } | ||
| ) | ||
| assert cached_response.json() == expected_json | ||
| assert cached_response.status_code == expected_status_code | ||
| # we should not get an exception here | ||
| cached_response.raise_for_status() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| from collections.abc import Generator | ||
| from unittest.mock import Mock, MagicMock | ||
|
|
||
| import pytest | ||
| from pytest_mock import MockFixture | ||
| from requests import HTTPError | ||
|
|
||
| from country_workspace.contrib.kobo.api.common import DataGetter | ||
|
|
||
|
|
||
| URL = "https://test.org" | ||
| CACHE_TTL = 42 | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def cache_mock(mocker: MockFixture) -> Mock: | ||
| return mocker.patch("country_workspace.contrib.kobo.api.common.cache") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def session_mock() -> Generator[Mock, None, None]: | ||
| return MagicMock(name="Session()") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def cached_response_class_mock(mocker: MockFixture) -> Mock: | ||
| return mocker.patch("country_workspace.contrib.kobo.api.common.CachedResponse") | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def data_getter_cache_key_mock(mocker: MockFixture) -> Mock: | ||
| return mocker.patch("country_workspace.contrib.kobo.api.common.data_getter_cache_key") | ||
|
|
||
|
|
||
| def test_cache_can_be_skipped(cache_mock: Mock, session_mock: Mock) -> None: | ||
| function = MagicMock() | ||
| function.return_value = True | ||
|
|
||
| data_getter = DataGetter( | ||
| session=session_mock, | ||
| cache_ttl=CACHE_TTL, | ||
| do_not_use_cache_if=function, | ||
| ) | ||
| response = data_getter(URL) | ||
|
|
||
| assert response == session_mock.get.return_value | ||
| session_mock.get.assert_called_with(URL, headers=None) | ||
| function.assert_called_once_with(URL) | ||
| cache_mock.assert_not_called() | ||
|
|
||
|
|
||
| def test_cached_value_is_returned( | ||
| cache_mock: Mock, session_mock: Mock, cached_response_class_mock: Mock, data_getter_cache_key_mock: Mock | ||
| ) -> None: | ||
| data_getter = DataGetter( | ||
| session=session_mock, | ||
| cache_ttl=CACHE_TTL, | ||
| ) | ||
| response = data_getter(URL) | ||
|
|
||
| assert response == cached_response_class_mock.return_value | ||
| cached_response_class_mock.assert_called_once_with(cache_mock.get.return_value) | ||
| session_mock.get.assert_not_called() | ||
| cache_mock.get.assert_called_once_with(data_getter_cache_key_mock.return_value) | ||
| data_getter_cache_key_mock.assert_called_once_with(URL) | ||
|
|
||
|
|
||
| def test_failing_response_is_not_cached(cache_mock: Mock, session_mock: Mock) -> None: | ||
| cache_mock.get.return_value = None | ||
| session_mock.get.return_value.raise_for_status.side_effect = HTTPError() | ||
|
|
||
| data_getter = DataGetter( | ||
| session=session_mock, | ||
| cache_ttl=CACHE_TTL, | ||
| ) | ||
| response = data_getter(URL) | ||
|
|
||
| assert response == session_mock.get.return_value | ||
| cache_mock.set.assert_not_called() | ||
|
|
||
|
|
||
| def test_response_is_cached( | ||
| cache_mock: Mock, session_mock: Mock, cached_response_class_mock: Mock, data_getter_cache_key_mock: Mock | ||
| ) -> None: | ||
| cache_mock.get.return_value = None | ||
|
|
||
| data_getter = DataGetter( | ||
| session=session_mock, | ||
| cache_ttl=CACHE_TTL, | ||
| ) | ||
| response = data_getter(URL) | ||
|
|
||
| assert response == session_mock.get.return_value | ||
| cache_mock.set.assert_called_once_with( | ||
| data_getter_cache_key_mock.return_value, | ||
| { | ||
| "json": session_mock.get.return_value.json.return_value, | ||
| "status_code": session_mock.get.return_value.status_code, | ||
| }, | ||
| CACHE_TTL, | ||
| ) |
15 changes: 15 additions & 0 deletions
15
tests/contrib/kobo/api/common/test_is_submission_data_url.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| import pytest | ||
|
|
||
| from country_workspace.contrib.kobo.sync import is_submission_data_url | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("url", "expected"), | ||
| [ | ||
| ("", False), | ||
| ("https://example.com", False), | ||
| ("https://example.com/api/v2/assets/abc42/data/", True), | ||
| ], | ||
| ) | ||
| def test_is_submission_data_url(url: str, expected: bool) -> None: | ||
| assert is_submission_data_url(url) is expected |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we have a more intuitive name?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@domdinicola Does HttpDataGetter sound better?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ok, would be good if we add docstrings to classes