wordlift-sdk 2.7.6__py3-none-any.whl → 2.8.0__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ from .google_sheets_lookup import GoogleSheetsLookup
2
+
3
+ __all__ = ["GoogleSheetsLookup"]
@@ -0,0 +1,121 @@
1
+ import logging
2
+ import os
3
+ from typing import Optional, Any, Dict
4
+
5
+ import gspread
6
+ from wordlift_sdk.configuration import ConfigurationProvider
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class GoogleSheetsLookup:
12
+ """
13
+ A generic class to lookup values from a Google Sheet.
14
+ Preloads data upon initialization for O(1) lookup performance.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ spreadsheet_url: str,
20
+ sheet_name: str,
21
+ key_column: str,
22
+ value_column: str,
23
+ configuration_provider: ConfigurationProvider,
24
+ service_account_file: Optional[str] = None,
25
+ ):
26
+ """
27
+ Initialize the GoogleSheetsLookup.
28
+
29
+ :param spreadsheet_url: The URL of the Google Sheet.
30
+ :param sheet_name: The name of the specific worksheet (tab).
31
+ :param key_column: The header name of the column to use as keys.
32
+ :param value_column: The header name of the column to use as values.
33
+ :param configuration_provider: The ConfigurationProvider instance.
34
+ :param service_account_file: Optional path to the service account JSON file.
35
+ If not provided, it will be looked up in the configuration.
36
+ """
37
+ self.spreadsheet_url = spreadsheet_url
38
+ self.sheet_name = sheet_name
39
+ self.key_column = key_column
40
+ self.value_column = value_column
41
+ self.configuration_provider = configuration_provider
42
+ self.service_account_file = service_account_file
43
+
44
+ self._data: Dict[str, Any] = {}
45
+ self._load_data()
46
+
47
+ def _resolve_service_account_file(self) -> Optional[str]:
48
+ """
49
+ Resolves the service account file path.
50
+ Priority:
51
+ 1. Argument passed to __init__
52
+ 2. 'SERVICE_ACCOUNT_FILE' from ConfigurationProvider
53
+ """
54
+ if self.service_account_file:
55
+ return self.service_account_file
56
+
57
+ # Attempt to retrieve from ConfigurationProvider
58
+ return self.configuration_provider.get_value("SERVICE_ACCOUNT_FILE")
59
+
60
+ # Fallback: check environment variable directly if ConfigurationProvider
61
+ # behavior is different or it didn't return anything.
62
+ return os.getenv("SERVICE_ACCOUNT_FILE")
63
+
64
+ def _load_data(self):
65
+ """
66
+ Connects to Google Sheets and preloads the data into a dictionary.
67
+ """
68
+ credentials_file = self._resolve_service_account_file()
69
+
70
+ try:
71
+ if credentials_file:
72
+ logger.info(
73
+ f"Connecting to Google Sheets using credentials: {credentials_file}"
74
+ )
75
+ gc = gspread.service_account(filename=credentials_file)
76
+ else:
77
+ logger.info(
78
+ "Connecting to Google Sheets using default environment credentials"
79
+ )
80
+ gc = gspread.service_account()
81
+
82
+ # Open spreadsheet by URL
83
+ sh = gc.open_by_url(self.spreadsheet_url)
84
+
85
+ # Select worksheet
86
+ worksheet = sh.worksheet(self.sheet_name)
87
+
88
+ # Get all records
89
+ records = worksheet.get_all_records()
90
+ logger.info(
91
+ f"Fetched {len(records)} records from sheet '{self.sheet_name}'"
92
+ )
93
+
94
+ # Build lookup dictionary
95
+ for i, record in enumerate(records):
96
+ key = record.get(self.key_column)
97
+ value = record.get(self.value_column)
98
+
99
+ if key is None:
100
+ logger.warning(
101
+ f"Row {i + 2}: Key column '{self.key_column}' is missing or empty. Skipping."
102
+ )
103
+ continue
104
+
105
+ # We stringify the key to ensure consistent lookup, optional but recommended for mixed types
106
+ self._data[str(key)] = value
107
+
108
+ logger.info(f"Successfully loaded {len(self._data)} items into cache.")
109
+
110
+ except Exception as e:
111
+ logger.error(f"Failed to load data from Google Sheets: {e}")
112
+ raise
113
+
114
+ def get_value(self, key: Any) -> Optional[Any]:
115
+ """
116
+ Look up a value by its key.
117
+
118
+ :param key: The key to look up.
119
+ :return: The corresponding value, or None if not found.
120
+ """
121
+ return self._data.get(str(key))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: wordlift-sdk
3
- Version: 2.7.6
3
+ Version: 2.8.0
4
4
  Summary:
5
5
  Author: David Riccitelli
6
6
  Author-email: david@wordlift.io
@@ -123,3 +123,8 @@ poetry install --with dev
123
123
  poetry run pytest
124
124
  ```
125
125
 
126
+ ## Documentation
127
+
128
+ - [Google Sheets Lookup](docs/google_sheets_lookup.md): Utility for O(1) lookups from Google Sheets.
129
+
130
+
@@ -14,6 +14,8 @@ wordlift_sdk/entity/patch.py,sha256=CP2H2nrrli4A_zu1D00Egye1I784ZQ6MxL_jS9ZsW9k,
14
14
  wordlift_sdk/google_search_console/__init__.py,sha256=-PmsnNYsGs4Utb9l7AXz0qAzcWhJeD-eZyFNfOHM5ow,384
15
15
  wordlift_sdk/google_search_console/create_google_search_console_data_import.py,sha256=xP_koUaaXYnnNVyw2ld4jbqc_d7yFkYXLe2dC2vLpm0,2223
16
16
  wordlift_sdk/google_search_console/raise_error_if_account_analytics_not_configured.py,sha256=pXcRlaVAODSbSgxI3KTtsHp37qiIaWCu9ISDKtDw6qM,830
17
+ wordlift_sdk/google_sheets/__init__.py,sha256=CEeLCBM2IJ_Yux0bY2T4MfIHVRc93OMF3aRPfpIYXRU,87
18
+ wordlift_sdk/google_sheets/google_sheets_lookup.py,sha256=oQwPizlT7Imbeq_Vlc5ZWfv2lkrO4VnA2sNeqdZHqew,4278
17
19
  wordlift_sdk/graph/graph_bag.py,sha256=Gp0ufstKY5xCx6dZNohcTmaEhoEYef891eaLuESUJpM,105
18
20
  wordlift_sdk/graph/ttl_liquid/__init__.py,sha256=2AmJpsFFkJxv6FyO7J3XFUfX1nSPDoY31tRom-K5C_w,97
19
21
  wordlift_sdk/graph/ttl_liquid/ttl_liquid_graph_factory.py,sha256=CSzO36YZ-XQrV7xRi99LhmYfQgMxjBkKdfEGeD0Zt9M,1242
@@ -95,6 +97,6 @@ wordlift_sdk/workflow/url_handler/default_url_handler.py,sha256=irMoJftx9Gyq-8HQ
95
97
  wordlift_sdk/workflow/url_handler/search_console_url_handler.py,sha256=uOwD4t009-cA9JI7ZtbYhCGRwjhLzDpBNTWHERPnNqI,2698
96
98
  wordlift_sdk/workflow/url_handler/url_handler.py,sha256=meyOpWVhLk2NcbtUOO_V0z6_T9q-D3pD7kWQCRioYh0,129
97
99
  wordlift_sdk/workflow/url_handler/web_page_import_url_handler.py,sha256=xQiy-fgFj_dWKFFBNWeodAGhIMJQereSPdgnjK-Crmo,3529
98
- wordlift_sdk-2.7.6.dist-info/METADATA,sha256=GtUczWgOG4_IP8PN5NisKsEh4YPnxYS_iNcU9ekXCio,4977
99
- wordlift_sdk-2.7.6.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
100
- wordlift_sdk-2.7.6.dist-info/RECORD,,
100
+ wordlift_sdk-2.8.0.dist-info/METADATA,sha256=KTf_FJcjFXsAV_vRB5yaK27fBdYHnKufUCPJe5tJ66o,5098
101
+ wordlift_sdk-2.8.0.dist-info/WHEEL,sha256=zp0Cn7JsFoX2ATtOhtaFYIiE2rmFAD4OcMhtUki8W3U,88
102
+ wordlift_sdk-2.8.0.dist-info/RECORD,,