cjapy 0.2.4.post3__tar.gz → 0.3.0__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 (33) hide show
  1. {cjapy-0.2.4.post3/cjapy.egg-info → cjapy-0.3.0}/PKG-INFO +1 -1
  2. cjapy-0.3.0/cjapy/__version__.py +1 -0
  3. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/cjapy.py +36 -13
  4. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/config.py +1 -4
  5. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/configs.py +68 -53
  6. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/connector.py +95 -113
  7. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/requestCreator.py +32 -25
  8. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/workspace.py +14 -5
  9. {cjapy-0.2.4.post3 → cjapy-0.3.0/cjapy.egg-info}/PKG-INFO +1 -1
  10. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy.egg-info/SOURCES.txt +0 -1
  11. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/cja.md +46 -0
  12. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/getting_started.md +40 -0
  13. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/main.md +38 -9
  14. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/releases.md +8 -0
  15. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/requestCreator.md +32 -6
  16. {cjapy-0.2.4.post3 → cjapy-0.3.0}/setup.py +0 -2
  17. cjapy-0.2.4.post3/cjapy/__version__.py +0 -1
  18. cjapy-0.2.4.post3/cjapy/token_provider.py +0 -93
  19. {cjapy-0.2.4.post3 → cjapy-0.3.0}/.gitignore +0 -0
  20. {cjapy-0.2.4.post3 → cjapy-0.3.0}/LICENSE +0 -0
  21. {cjapy-0.2.4.post3 → cjapy-0.3.0}/README.md +0 -0
  22. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/__init__.py +0 -0
  23. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy/projects.py +0 -0
  24. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy.egg-info/dependency_links.txt +0 -0
  25. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy.egg-info/requires.txt +0 -0
  26. {cjapy-0.2.4.post3 → cjapy-0.3.0}/cjapy.egg-info/top_level.txt +0 -0
  27. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/authenticating_without_config_json.md +0 -0
  28. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/logging.md +0 -0
  29. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/projects.md +0 -0
  30. {cjapy-0.2.4.post3 → cjapy-0.3.0}/docs/workspace.md +0 -0
  31. {cjapy-0.2.4.post3 → cjapy-0.3.0}/pyproject.toml +0 -0
  32. {cjapy-0.2.4.post3 → cjapy-0.3.0}/requirements.txt +0 -0
  33. {cjapy-0.2.4.post3 → cjapy-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cjapy
3
- Version: 0.2.4.post3
3
+ Version: 0.3.0
4
4
  Summary: Adobe Customer Journey Analytics (CJA) wrapper
5
5
  Home-page: https://github.com/pitchmuc/cjapy
6
6
  Author: Julien Piccini
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -13,6 +13,7 @@ import string
13
13
  # Non standard libraries
14
14
  import pandas as pd
15
15
  from cjapy import config, connector
16
+ from .configs import ConfigObj
16
17
  from .workspace import Workspace
17
18
  from .requestCreator import RequestCreator
18
19
  from .projects import Project
@@ -32,17 +33,30 @@ class CJA:
32
33
 
33
34
  def __init__(
34
35
  self,
35
- config_object: dict = config.config_object,
36
- header: dict = config.header,
36
+ config_object: Union[ConfigObj, dict, None] = None,
37
37
  loggingObject: dict = None,
38
38
  ) -> None:
39
39
  """
40
40
  Instantiate the class with the information provided.
41
41
  Arguments:
42
- loggingObject : OPTIONAL :If you want to set logging capability for your actions.
43
- header : REQUIRED : config header loaded (DO NOT MODIFY)
44
- config_object : REQUIRED : config object loaded (DO NOT MODIFY)
45
- """
42
+ config_object : OPTIONAL : One of:
43
+ - A :class:`~cjapy.ConfigObj` instance (created via ``configure(..., return_object=True)``
44
+ or ``importConfigFile(..., return_object=True)``), for isolated credentials that allow
45
+ multiple CJA instances to run in parallel with different client IDs.
46
+ - A plain ``dict`` matching the internal config_object structure (legacy usage).
47
+ - ``None`` (default): uses the global config set by :func:`~cjapy.configure` or
48
+ :func:`~cjapy.importConfigFile`.
49
+ loggingObject : OPTIONAL : If you want to set logging capability for your actions.
50
+ """
51
+ if isinstance(config_object, ConfigObj):
52
+ _config_object = config_object.config_object
53
+ _header = config_object.header
54
+ elif isinstance(config_object, dict):
55
+ _config_object = config_object
56
+ _header = config.header
57
+ else:
58
+ _config_object = config.config_object
59
+ _header = config.header
46
60
  if loggingObject is not None and sorted(
47
61
  ["level", "stream", "format", "filename", "file"]
48
62
  ) == sorted(list(loggingObject.keys())):
@@ -59,8 +73,8 @@ class CJA:
59
73
  streamHandler.setFormatter(formatter)
60
74
  self.logger.addHandler(streamHandler)
61
75
  self.connector = connector.AdobeRequest(
62
- config_object=config_object,
63
- header=header,
76
+ config_object=_config_object,
77
+ header=_header,
64
78
  loggingEnabled=self.loggingEnabled,
65
79
  logger=self.logger,
66
80
  )
@@ -2141,9 +2155,16 @@ class CJA:
2141
2155
  data_rows = deepcopy(dataRows)
2142
2156
  expanded_rows = {}
2143
2157
  if reportType == "normal":
2144
- for row in data_rows:
2145
- expanded_rows[row["itemId"]] = [row["value"]]
2146
- expanded_rows[row["itemId"]] += row["data"]
2158
+ for idx, row in enumerate(data_rows):
2159
+ if 'itemId' in row.keys():
2160
+ expanded_rows[row["itemId"]] = [row["value"]]
2161
+ expanded_rows[row["itemId"]] += row["data"]
2162
+ elif "itemIds" in row.keys():
2163
+ expanded_rows[row["itemIds"][0]] = [row["values"][0]]
2164
+ expanded_rows[row["itemIds"][0]] += row["data"]
2165
+ elif reportType == "multidimensional":
2166
+ for idx, row in enumerate(data_rows):
2167
+ expanded_rows[idx] = list(row["values"]) + row["data"]
2147
2168
  elif reportType == "static":
2148
2169
  expanded_rows = data_rows
2149
2170
  return expanded_rows
@@ -2186,7 +2207,7 @@ class CJA:
2186
2207
  segmentApplied[obj["id"]] = obj["dateRange"]
2187
2208
  ### table columnIds and StaticRow IDs
2188
2209
  tableColumnIds = {
2189
- obj["columnId"]: obj.get("filters",[])[0]
2210
+ obj.get("columnId"): obj.get("filters",[])[0]
2190
2211
  for obj
2191
2212
  in dataRequest["metricContainer"]["metrics"]
2192
2213
  }
@@ -2285,7 +2306,7 @@ class CJA:
2285
2306
  ### Settings
2286
2307
  dataRequest["settings"]["page"] = 0
2287
2308
  dataRequest["settings"]["limit"] = limit
2288
- if returnsNone:
2309
+ if returnsNone is None or len(dataRequest.get("dimensions",[])) >1 :
2289
2310
  dataRequest["settings"]["nonesBehavior"] = "return-nones"
2290
2311
  else:
2291
2312
  dataRequest["settings"]["nonesBehavior"] = "exclude-nones"
@@ -2405,6 +2426,8 @@ class CJA:
2405
2426
  metricColumns.append(metricName)
2406
2427
  ### ending with ['metric1','metric2 + segId',...]
2407
2428
  ### preparing data points
2429
+ if len(dataRequest.get("dimensions",[]))>1 and reportType == "normal":
2430
+ reportType = "multidimensional"
2408
2431
  if self.loggingEnabled:
2409
2432
  self.logger.debug(f"preparing data")
2410
2433
  preparedData = self._prepareData(dataRows, reportType=reportType)
@@ -1,15 +1,12 @@
1
1
  config_object = {
2
2
  "org_id": "",
3
3
  "client_id": "",
4
- "tech_id": "",
5
- "pathToKey": "",
6
4
  "secret": "",
7
5
  "date_limit": 0,
8
6
  "token": "",
9
7
  "scopes":"",
10
8
  "imsEndpoint":"https://ims-na1.adobelogin.com",
11
- "oauthTokenEndpointV2": "",
12
- "jwtTokenEndpoint": "https://ims-na1.adobelogin.com/ims/exchange/jwt"
9
+ "oauthTokenEndpoint": "",
13
10
  }
14
11
  header = {"Accept": "application/json",
15
12
  "Content-Type": "application/json",
@@ -5,7 +5,7 @@ from typing import Optional
5
5
  import time
6
6
 
7
7
  # Non standard libraries
8
- from .config import config_object, header
8
+ from cjapy.config import config_object, header
9
9
 
10
10
 
11
11
  def find_path(path: str) -> Optional[Path]:
@@ -37,19 +37,15 @@ def createConfigFile(
37
37
  to store the access data in under the specified `destination`.
38
38
  Parameters:
39
39
  filename : OPTIONAL : : name of the config file.
40
- auth_type : OPTIONAL : type of authentication, either "jwt" or "oauthV2". Default is oauthV2
40
+ auth_type : OPTIONAL : type of authentication. Default is oauthV2
41
41
  verbose : OPTIONAL : set to true, gives you a print stateent where is the location.
42
42
  """
43
43
  json_data = {
44
44
  "org_id": "<orgID>",
45
45
  "client_id": "<APIkey>",
46
46
  "secret": "<YourSecret>",
47
+ "scopes": "<scope1,scope2>",
47
48
  }
48
- if auth_type == 'jwt':
49
- json_data["tech_id"] = "<something>@techacct.adobe.com"
50
- json_data["pathToKey"] = "<path/to/your/privatekey.key>"
51
- elif auth_type == 'OauthV2':
52
- json_data["scopes"] = "<scopes>"
53
49
  with open(filename, "w") as cf:
54
50
  cf.write(json.dumps(json_data, indent=4))
55
51
  if verbose:
@@ -60,16 +56,16 @@ def createConfigFile(
60
56
 
61
57
  def importConfigFile(
62
58
  path: str = None,
63
- auth_type: str = None,
64
59
  client_secret_index: int = 0,
65
- )-> None:
60
+ return_object: bool = False,
61
+ ) -> Optional["ConfigObj"]:
66
62
  """Reads the file denoted by the supplied `path` and retrieves the configuration information
67
63
  from it.
68
64
 
69
65
  Arguments:
70
66
  path: REQUIRED : path to the configuration file. Can be either a fully-qualified or relative.
71
- auth_type : OPTIONAL : type of authentication, either "jwt" or "oauthV2". Detected based on keys present in config file.
72
67
  client_secret_index : OPTIONAL : choose which of your client secrets that you want to use, specify the index, default 0.
68
+ return_object : OPTIONAL : If True, returns a ConfigObj instance instead of updating the global config. Default False.
73
69
 
74
70
  Example of path value.
75
71
  "config.json"
@@ -109,90 +105,109 @@ def importConfigFile(
109
105
  )
110
106
 
111
107
  if "scopes" in provided_keys:
112
- ## old naming for client_secret
113
108
  scopes = provided_config["scopes"]
114
109
  elif "SCOPES" in provided_keys:
115
110
  scopes = provided_config["SCOPES"]
111
+ else:
112
+ raise RuntimeError(
113
+ "Either a `scopes` or a `SCOPES` key should be provided."
114
+ )
116
115
 
117
116
  client_secret = client_secret[client_secret_index] if type(client_secret) == list else client_secret
118
- if auth_type is None:
119
- if 'scopes' in provided_keys:
120
- auth_type = 'oauthV2'
121
- elif 'tech_id' in provided_keys and "pathToKey" in provided_keys:
122
- auth_type = 'jwt'
123
117
  args = {
124
118
  "org_id": provided_config["org_id"] if provided_config.get("org_id") is not None else provided_config["ORG_ID"],
125
119
  "client_id": client_id,
126
120
  "secret": client_secret,
121
+ "scopes": ",".join(scopes) if type(scopes) == list else scopes.replace(' ',''),
127
122
  }
128
- if auth_type == "jwt":
129
- args["tech_id"] = provided_config["tech_id"]
130
- args["path_to_key"] = provided_config["pathToKey"]
131
- elif auth_type == "oauthV2":
132
- scopes = ",".join(scopes) if type(scopes) == list else scopes
133
- args["scopes"] = scopes.replace(' ','')
123
+ if return_object:
124
+ return ConfigObj(
125
+ org_id=args["org_id"],
126
+ client_id=args["client_id"],
127
+ secret=args["secret"],
128
+ scopes=args["scopes"],
129
+ )
134
130
  configure(**args)
135
131
 
136
132
 
137
133
  def configure(
138
134
  org_id: str = None,
139
- tech_id: str = None,
140
135
  secret: str = None,
141
136
  client_id: str = None,
142
- path_to_key: str = None,
143
- private_key: str = None,
144
- scopes: str = None
145
- ):
137
+ scopes: str = None,
138
+ return_object: bool = False,
139
+ ) -> Optional["ConfigObj"]:
146
140
  """Performs programmatic configuration of the API using provided values.
147
141
  Arguments:
148
142
  org_id : REQUIRED : Organization ID
149
- tech_id : REQUIRED : Technical Account ID
150
143
  secret : REQUIRED : secret generated for your connection
151
- client_id : REQUIRED : The client_id (old api_key) provided by the JWT connection.
152
- path_to_key : REQUIRED : If you have a file containing your private key value.
153
- private_key : REQUIRED : If you do not use a file but pass a variable directly.
154
- scopes : OPTIONAL : The scope define in your project for your API connection. Oauth V2, for clients and customers.
144
+ client_id : REQUIRED : The client_id (old api_key) provided by the connection.
145
+ scopes : REQUIRED : The scopes defined in your project for your API connection.
146
+ return_object : OPTIONAL : If True, returns a ConfigObj instance instead of updating the global config. Default False.
155
147
  """
156
148
  if not org_id:
157
149
  raise ValueError("`org_id` must be specified in the configuration.")
158
150
  if not client_id:
159
151
  raise ValueError("`client_id` must be specified in the configuration.")
160
- if tech_id is None and (path_to_key is None and private_key is None) and scopes is None:
161
- raise ValueError("either `scopes` needs to be specified or one of `private_key` or `path_to_key` with tech_id")
152
+ if not scopes:
153
+ raise ValueError("`scopes` must be specified in the configuration.")
162
154
  if not secret:
163
155
  raise ValueError("`secret` must be specified in the configuration.")
164
156
  config_object["org_id"] = org_id
165
157
  config_object["client_id"] = client_id
166
158
  header["x-api-key"] = client_id
167
159
  header["x-gw-ims-org-id"] = org_id
168
- config_object["tech_id"] = tech_id
169
160
  config_object["secret"] = secret
170
- config_object["pathToKey"] = path_to_key
171
- config_object["private_key"] = private_key
172
161
  config_object["scopes"] = scopes
173
- config_object["jwtTokenEndpoint"] = f"{config_object['imsEndpoint']}/ims/exchange/jwt"
174
- config_object["oauthTokenEndpointV2"] = f"{config_object['imsEndpoint']}/ims/token/v3"
162
+ config_object["oauthTokenEndpoint"] = f"{config_object['imsEndpoint']}/ims/token/v3"
175
163
 
176
164
  # ensure the reset of the state by overwriting possible values from previous import.
177
165
  config_object["date_limit"] = 0
178
166
  config_object["token"] = ""
167
+ if return_object:
168
+ return ConfigObj(
169
+ org_id=org_id,
170
+ client_id=client_id,
171
+ secret=secret,
172
+ scopes=scopes,
173
+ )
179
174
 
180
-
181
- def get_private_key_from_config(config: dict) -> str:
175
+ class ConfigObj:
182
176
  """
183
- Returns the private key directly or read a file to return the private key.
177
+ Holds an isolated set of credentials and configuration for a single CJA API connection.
178
+ cfg = importConfigFile("config_client_a.json", return_object=True)
179
+ cfg = configure(org_id="...", client_id="...", secret="...", scopes="...", return_object=True)
180
+ cja = CJA(config_object=cfg)
181
+ Attributes:
182
+ config_object : dict holding all credential and token state.
183
+ header : dict holding the HTTP headers for API requests.
184
184
  """
185
- private_key = config.get("private_key")
186
- if private_key is not None:
187
- return private_key
188
- private_key_path = find_path(config["pathToKey"])
189
- if private_key_path is None:
190
- raise FileNotFoundError(
191
- f'Unable to find the private key under path `{config["pathToKey"]}`.'
192
- )
193
- with open(Path(private_key_path), "r") as f:
194
- private_key = f.read()
195
- return private_key
185
+
186
+ def __init__(
187
+ self,
188
+ org_id: str = "",
189
+ client_id: str = "",
190
+ secret: str = "",
191
+ scopes: str = None,
192
+ ) -> None:
193
+ ims_endpoint = "https://ims-na1.adobelogin.com"
194
+ self.config_object: dict = {
195
+ "org_id": org_id,
196
+ "client_id": client_id,
197
+ "secret": secret,
198
+ "date_limit": 0,
199
+ "token": "",
200
+ "scopes": scopes,
201
+ "imsEndpoint": ims_endpoint,
202
+ "oauthTokenEndpoint": f"{ims_endpoint}/ims/token/v3",
203
+ }
204
+ self.header: dict = {
205
+ "Accept": "application/json",
206
+ "Content-Type": "application/json",
207
+ "Authorization": "Bearer ",
208
+ "x-api-key": client_id,
209
+ "x-gw-ims-org-id": org_id,
210
+ }
196
211
 
197
212
 
198
213
  def generateLoggingObject(level:str="WARNING",filename:str="cjapy.log") -> dict:
@@ -1,11 +1,14 @@
1
1
  import json
2
2
  import time
3
3
  from copy import deepcopy
4
+ from typing import Dict
4
5
 
5
6
  # Non standard libraries
6
7
  import requests
8
+ from requests.adapters import HTTPAdapter
9
+ from urllib3.util.retry import Retry
7
10
 
8
- from cjapy import config, token_provider
11
+ from cjapy import config
9
12
 
10
13
 
11
14
  class AdobeRequest:
@@ -48,17 +51,11 @@ class AdobeRequest:
48
51
  self.retry = retry
49
52
  self.connectionType = 'oauthV2'
50
53
  if self.config["token"] == "" or time.time() > self.config["date_limit"]:
51
- if self.config["private_key"] is not None or self.config["pathToKey"] is not None:
52
- self.connectionType = 'jwt'
53
- token_and_expiry = token_provider.get_jwt_token_and_expiry_for_config(
54
- config=self.config, verbose=verbose
55
- )
56
- elif self.config["scopes"] is not None:
57
- self.connectionType = 'oauthV2'
58
- token_and_expiry = token_provider.get_oauth_token_and_expiry_for_config(
59
- config=self.config,
60
- verbose=verbose
61
- )
54
+ self.connectionType = 'oauthV2'
55
+ token_and_expiry = self.get_oauth_token_and_expiry_for_config(
56
+ config=self.config,
57
+ verbose=verbose
58
+ )
62
59
  token = token_and_expiry["token"]
63
60
  expiry = token_and_expiry["expiry"]
64
61
  if self.loggingEnabled:
@@ -67,6 +64,58 @@ class AdobeRequest:
67
64
  self.config["token"] = token
68
65
  self.config["date_limit"] = time.time() + expiry - 500
69
66
  self.header.update({"Authorization": f"Bearer {token}"})
67
+ self.session = self._build_session(self.retry)
68
+
69
+ def get_oauth_token_and_expiry_for_config(self, config: dict,
70
+ verbose: bool = False,
71
+ save: bool = False
72
+ ) -> Dict[str, str]:
73
+ """
74
+ Retrieve the access token by using the OAuth information provided by the user
75
+ during the import importConfigFile function.
76
+ Arguments :
77
+ config : REQUIRED : Configuration object.
78
+ verbose : OPTIONAL : Default False. If set to True, print information.
79
+ save : OPTIONAL : Default False. If set to True, save the toke in the .
80
+ """
81
+ oauth_payload = {
82
+ "grant_type": "client_credentials",
83
+ "client_id": config["client_id"],
84
+ "client_secret": config["secret"],
85
+ "scope": config["scopes"]
86
+ }
87
+ response = requests.post(
88
+ config["oauthTokenEndpoint"], data=oauth_payload
89
+ )
90
+ responseJson = response.json()
91
+ token = responseJson.get('access_token')
92
+ expiry = responseJson.get("expires_in")
93
+ if token is None or expiry is None:
94
+ raise Exception(f"OAuth response missing required fields. Response: {responseJson}")
95
+ return {'token': token, 'expiry': expiry}
96
+
97
+ def _build_session(self, max_retries: int) -> requests.Session:
98
+ """
99
+ Build a requests.Session with an HTTPAdapter configured for retrying
100
+ on 429 and common 5xx server errors with exponential back-off.
101
+
102
+ The adapter honours the ``Retry-After`` response header so the wait
103
+ time advertised by the server is respected automatically.
104
+ """
105
+ session = requests.Session()
106
+ retry_strategy = Retry(
107
+ total=max(max_retries, 3),
108
+ status_forcelist=[429, 500, 502, 503, 504],
109
+ allowed_methods={"DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"},
110
+ backoff_factor=1,
111
+ respect_retry_after_header=True,
112
+ raise_on_status=False,
113
+ )
114
+ adapter = HTTPAdapter(max_retries=retry_strategy)
115
+ session.mount("https://", adapter)
116
+ session.mount("http://", adapter)
117
+ session.headers.update(self.header)
118
+ return session
70
119
 
71
120
  def _checkingDate(self) -> None:
72
121
  """
@@ -76,22 +125,16 @@ class AdobeRequest:
76
125
  if now > self.config["date_limit"]:
77
126
  if self.loggingEnabled:
78
127
  self.logger.warning("token expired. Trying to retrieve a new token")
79
- if self.connectionType == 'jwt':
80
- token_with_expiry = token_provider.get_jwt_token_and_expiry_for_config(
81
- config=self.config)
82
- elif self.connectionType == 'oauthV2':
83
- token_with_expiry = token_provider.get_oauth_token_and_expiry_for_config(
84
- config=self.config)
128
+ token_with_expiry = self.get_oauth_token_and_expiry_for_config(
129
+ config=self.config)
85
130
  token = token_with_expiry["token"]
86
131
  expiry = token_with_expiry["expiry"]
87
132
  if self.loggingEnabled:
88
- self.logger.info("new token retrieved : {token}")
133
+ self.logger.info(f"new token retrieved : {token}")
89
134
  self.config["token"] = token
90
135
  self.config["date_limit"] = time.time() + expiry - 500
91
136
  self.header.update({"Authorization": f"Bearer {token}"})
92
- self.config["date_limit"] = (
93
- time.time() + (token_with_expiry["expiry"]) - 500
94
- )
137
+ self.session.headers.update({"Authorization": f"Bearer {token}"})
95
138
 
96
139
  def getData(
97
140
  self,
@@ -105,34 +148,19 @@ class AdobeRequest:
105
148
  """
106
149
  Abstraction for getting data
107
150
  """
108
- internRetry = kwargs.get("retry", self.retry)
109
151
  expansion = kwargs.get("expansion")
110
152
  if expansion:
153
+ if params is None:
154
+ params = {}
111
155
  params["expansion"] = expansion
112
156
  self._checkingDate()
113
- if headers is None:
114
- headers = self.header
115
- if params is None and data is None:
116
- res = requests.get(endpoint, headers=headers)
117
- elif params is not None and data is None:
118
- res = requests.get(endpoint, headers=headers, params=params)
119
- elif params is None and data is not None:
120
- res = requests.get(endpoint, headers=headers, data=data)
121
- elif params is not None and data is not None:
122
- res = requests.get(endpoint, headers=headers, params=params, data=data)
157
+ res = self.session.get(endpoint, params=params, data=data, headers=headers)
123
158
  if self.loggingEnabled:
124
159
  self.logger.debug(f"request_URL : {res.request.url}")
125
- self.logger.debug(f"header used: {json.dumps(headers)}")
160
+ self.logger.debug(f"header used: {json.dumps(dict(self.session.headers))}")
126
161
  self.logger.debug(f"status_code: {res.status_code}")
127
162
  self.logger.debug(f"parameters used: {json.dumps(params)}")
128
163
  try:
129
- while str(res.status_code) == "429":
130
- if self.loggingEnabled:
131
- self.logger.info(
132
- f"Too many requests: retrying in {self.restTime} seconds"
133
- )
134
- time.sleep(self.restTime)
135
- res = requests.get(endpoint, headers=headers, params=params, data=data)
136
164
  res_json = res.json()
137
165
  except:
138
166
  ## handling 1.4
@@ -142,27 +170,10 @@ class AdobeRequest:
142
170
  except:
143
171
  if self.loggingEnabled:
144
172
  self.logger.error(
145
- f"GET method failed: {res.status}, {res.status}"
173
+ f"GET method failed: {res.status_code}, {res.text}"
146
174
  )
147
175
  return res.text
148
176
  res_json = {"error": "Request Error"}
149
- while internRetry > 0:
150
- if self.loggingEnabled:
151
- self.logger.warning(f"Trying again with internal retry")
152
- if kwargs.get("verbose", False):
153
- print("Retry parameter activated")
154
- print(f"{internRetry} retry left")
155
- if "error" in res_json.keys():
156
- time.sleep(30)
157
- res_json = self.getData(
158
- endpoint,
159
- params=params,
160
- data=data,
161
- headers=headers,
162
- retry=internRetry - 1,
163
- **kwargs,
164
- )
165
- return res_json
166
177
  return res_json
167
178
 
168
179
  def postData(
@@ -179,31 +190,22 @@ class AdobeRequest:
179
190
  """
180
191
  expansion = kwargs.get("expansion")
181
192
  if expansion:
193
+ if params is None:
194
+ params = {}
182
195
  params["expansion"] = expansion
183
196
  self._checkingDate()
184
- if headers is None:
185
- headers = self.header
186
197
  if params is None and data is None:
187
- res = requests.post(endpoint, headers=headers)
198
+ res = self.session.post(endpoint, headers=headers)
188
199
  elif params is not None and data is None:
189
- res = requests.post(endpoint, headers=headers, params=params)
200
+ res = self.session.post(endpoint, params=params, headers=headers)
190
201
  elif params is None and data is not None:
191
- res = requests.post(endpoint, headers=headers, data=json.dumps(data))
202
+ res = self.session.post(endpoint, data=json.dumps(data), headers=headers)
192
203
  elif params is not None and data is not None:
193
- res = requests.post(
194
- endpoint, headers=headers, params=params, data=json.dumps(data)
195
- )
204
+ res = self.session.post(endpoint, params=params, data=json.dumps(data), headers=headers)
196
205
  if self.loggingEnabled:
197
206
  self.logger.debug(f"request_URL : {res.request.url}")
198
207
  self.logger.debug(f"status_code: {res.status_code}")
199
208
  try:
200
- while (
201
- res.status_code == 429 or res.json().get("error_code", None) == "429050"
202
- ):
203
- if self.loggingEnabled:
204
- self.logger.warning(f"too many request: {res.status}, {res.text}")
205
- time.sleep(30)
206
- res = self.postData(endpoint, headers=headers, params=params, data=data)
207
209
  res_json = res.json()
208
210
  except:
209
211
  ## handling 1.4
@@ -213,10 +215,10 @@ class AdobeRequest:
213
215
  except:
214
216
  if self.loggingEnabled:
215
217
  self.logger.error(
216
- f"POST method failed: {res.status}, {res.text}"
218
+ f"POST method failed: {res.status_code}, {res.text}"
217
219
  )
218
220
  return res.text
219
- if res.status_code == '504':
221
+ if res.status_code == 504:
220
222
  res_json = {"error-504": "504 Gateway Time-out"}
221
223
  else:
222
224
  res_json = {"error": f"Request Error, status: {res.status_code}"}
@@ -235,31 +237,22 @@ class AdobeRequest:
235
237
  Abstraction for patching data
236
238
  """
237
239
  self._checkingDate()
238
- if headers is None:
239
- headers = self.header
240
- if params is not None and data is None:
241
- res = requests.patch(endpoint, headers=headers, params=params)
240
+ if params is None and data is None:
241
+ res = self.session.patch(endpoint, headers=headers)
242
+ elif params is not None and data is None:
243
+ res = self.session.patch(endpoint, params=params, headers=headers)
242
244
  elif params is None and data is not None:
243
- res = requests.patch(endpoint, headers=headers, data=json.dumps(data))
245
+ res = self.session.patch(endpoint, data=json.dumps(data), headers=headers)
244
246
  elif params is not None and data is not None:
245
- res = requests.patch(
246
- endpoint, headers=headers, params=params, data=json.dumps(data)
247
- )
247
+ res = self.session.patch(endpoint, params=params, data=json.dumps(data), headers=headers)
248
248
  if self.loggingEnabled:
249
249
  self.logger.debug(f"request_URL : {res.request.url}")
250
250
  self.logger.debug(f"status_code: {res.status_code}")
251
251
  try:
252
- while str(res.status_code) == "429":
253
- if kwargs.get("verbose", False):
254
- print(f"Too many requests: retrying in {self.restTime} seconds")
255
- time.sleep(self.restTime)
256
- res = requests.patch(
257
- endpoint, headers=headers, params=params, data=json.dumps(data)
258
- )
259
252
  res_json = res.json()
260
253
  except:
261
254
  if self.loggingEnabled:
262
- self.logger.error(f"PATCH method failed: {res.status}, {res.text}")
255
+ self.logger.error(f"PATCH method failed: {res.status_code}, {res.text}")
263
256
  res_json = {"error": "Request Error"}
264
257
  return res_json
265
258
 
@@ -277,22 +270,18 @@ class AdobeRequest:
277
270
  """
278
271
  expansion = kwargs.get("expansion")
279
272
  if expansion:
273
+ if params is None:
274
+ params = {}
280
275
  params["expansion"] = expansion
281
276
  self._checkingDate()
282
- if headers is None:
283
- headers = self.header
284
277
  if params is not None and data is None:
285
- res = requests.put(endpoint, headers=headers, params=params)
278
+ res = self.session.put(endpoint, params=params, headers=headers)
286
279
  elif params is None and data is not None:
287
- res = requests.put(endpoint, headers=headers, data=json.dumps(data))
280
+ res = self.session.put(endpoint, data=json.dumps(data), headers=headers)
288
281
  elif params is not None and data is not None:
289
- res = requests.put(
290
- endpoint, headers=headers, params=params, data=json.dumps(data)
291
- )
282
+ res = self.session.put(endpoint, params=params, data=json.dumps(data), headers=headers)
292
283
  elif params is None and data is None:
293
- res = requests.put(
294
- endpoint, headers=headers
295
- )
284
+ res = self.session.put(endpoint, headers=headers)
296
285
  if self.loggingEnabled:
297
286
  self.logger.debug(f"request_URL : {res.request.url}")
298
287
  self.logger.debug(f"status_code: {res.status_code}")
@@ -300,7 +289,7 @@ class AdobeRequest:
300
289
  status_code = res.json()
301
290
  except:
302
291
  if self.loggingEnabled:
303
- self.logger.error(f"PUT method failed: {res.status}, {res.text}")
292
+ self.logger.error(f"PUT method failed: {res.status_code}, {res.text}")
304
293
  status_code = {"error": "Request Error"}
305
294
  return status_code
306
295
 
@@ -311,21 +300,14 @@ class AdobeRequest:
311
300
  Abstraction for deleting data
312
301
  """
313
302
  self._checkingDate()
314
- if headers is None:
315
- headers = self.header
316
303
  if params is None:
317
- res = requests.delete(endpoint, headers=headers)
304
+ res = self.session.delete(endpoint, headers=headers)
318
305
  elif params is not None:
319
- res = requests.delete(endpoint, headers=headers, params=params)
306
+ res = self.session.delete(endpoint, params=params, headers=headers)
320
307
  try:
321
- while str(res.status_code) == "429":
322
- if kwargs.get("verbose", False):
323
- print(f"Too many requests: retrying in {self.restTime} seconds")
324
- time.sleep(self.restTime)
325
- res = requests.delete(endpoint, headers=headers, params=params)
326
308
  status_code = res.status_code
327
309
  except:
328
310
  if self.loggingEnabled:
329
- self.logger.error(f"DELETE method failed: {res.status}, {res.text}")
311
+ self.logger.error(f"DELETE method failed: {res.status_code}, {res.text}")
330
312
  status_code = {"error": "Request Error"}
331
313
  return status_code
@@ -3,7 +3,7 @@ import datetime
3
3
  import json
4
4
  from time import time
5
5
  from typing import Union
6
-
6
+ import deprecation
7
7
 
8
8
  class RequestCreator:
9
9
  """
@@ -16,7 +16,7 @@ class RequestCreator:
16
16
  "metrics": [],
17
17
  "metricFilters": [],
18
18
  },
19
- "dimension": "",
19
+ "dimensions": "",
20
20
  "settings": {
21
21
  "countRepeatInstances": True,
22
22
  "limit": 20000,
@@ -483,22 +483,6 @@ class RequestCreator:
483
483
  self.__request["search"]["clause"] = clause
484
484
  self.search = True
485
485
 
486
- # def addDimensions(self,dimensionIds:list=None)->None:
487
- # """
488
- # In case you want to pass a list of dimensions to the report API.
489
- # Arguments:
490
- # dimensionIds : REQUIRED : The list of dimensions IDs you want to use
491
- # """
492
- # if dimensionIds is None:
493
- # raise ValueError("dimensionIds parameters should be used")
494
- # if type(dimensionIds) != list:
495
- # raise TypeError("dimensionIds should be a list")
496
- # if len(dimensionIds)>5:
497
- # raise ValueError("dimensionIds should not countain more than 5 elements")
498
- # if 'dimension' in self.__request.keys():
499
- # del self.__request["dimension"]
500
- # self.__request["dimensions"] = dimensionIds
501
-
502
486
  def removeSearch(self)->None:
503
487
  """
504
488
  Remove the search capability in the request.
@@ -554,22 +538,46 @@ class RequestCreator:
554
538
  if "sort" in metric:
555
539
  del metric["sort"]
556
540
 
557
- def setDimension(self, dimension: str = None, sort_order: str = None) -> None:
541
+ @deprecation.deprecated(deprecated_in="0.3.0", details="Use setDimensions instead")
542
+ def setDimension(self, dimension: str = None) -> None:
558
543
  """
544
+ *** LEGACY METHOD, use setDimensions instead. ***
559
545
  Set the dimension to be used for reporting.
560
546
  Arguments:
561
- dimension : REQUIRED : the dimension to build your report on
562
- sort_order : OPTIONAL : The sort order, either "asc" or "desc".
547
+ dimension : REQUIRED : the dimension ID to build your report on
563
548
  """
564
549
  if self.STATIC_ROW_REPORT:
565
550
  raise Exception('This Request has been started as STATIC ROW REQUEST.\nCreate another RequestCreator instance for building it via dimension.')
566
551
  if dimension is None:
567
552
  raise ValueError("A dimension must be passed")
553
+ return self.setDimensions(dimensions=dimension)
554
+
555
+
556
+ def setDimensions(self, dimensions: Union[str,list] = None) -> None:
557
+ """
558
+ Set the dimension to be used for reporting.
559
+ Arguments:
560
+ dimensions : REQUIRED : the dimension ID(s) to build your report on (a list of strings or a single string)
561
+ """
562
+ if self.STATIC_ROW_REPORT:
563
+ raise Exception('This Request has been started as STATIC ROW REQUEST.\nCreate another RequestCreator instance for building it via dimension.')
564
+ if dimensions is None:
565
+ raise ValueError("A dimension must be passed")
566
+ if isinstance(dimensions, str):
567
+ dimensions = [dimensions]
568
568
  if 'dimensions' in self.__request.keys():
569
569
  del self.__request["dimensions"]
570
- self.__request["dimension"] = dimension
571
- if sort_order:
572
- self.setDimensionSort(sort_order)
570
+ if 'dimension' in self.__request.keys():
571
+ del self.__request["dimension"]
572
+ dimension_data = []
573
+ if type(dimensions) and len(dimensions) > 1:
574
+ self.__request["settings"]["nonesBehavior"] = "return-nones"
575
+ for index, dimension in enumerate(dimensions):
576
+ if not isinstance(dimension, str):
577
+ raise ValueError("All dimensions must be strings")
578
+ dimension_data.append({"columnId": f"col{index}","id": dimension})
579
+ self.__request["dimensions"] = dimension_data
580
+
573
581
 
574
582
  def setIdentityOverrides(self, identity_overrides: list) -> None:
575
583
  """
@@ -581,7 +589,6 @@ class RequestCreator:
581
589
  raise ValueError("identity_overrides must be a list of dictionaries")
582
590
  if not all(isinstance(item, dict) for item in identity_overrides):
583
591
  raise ValueError("All items in identity_overrides must be dictionaries")
584
-
585
592
  self.__request["identityOverrides"] = identity_overrides
586
593
 
587
594
  def setDataViewId(self, dataViewId: str = None) -> None:
@@ -76,17 +76,22 @@ class Workspace:
76
76
  if reportType == "normal" or reportType == "static":
77
77
  df_init = pd.DataFrame(responseData).T
78
78
  df_init = df_init.reset_index()
79
+ elif reportType == "multidimensional":
80
+ df_init = pd.DataFrame(responseData).T
81
+ df_init = df_init.reset_index(drop=True)
79
82
  elif reportType == "multi":
80
83
  df_init = responseData
81
84
  if reportType == "normal":
82
85
  columns_data = ["itemId"]
83
86
  elif reportType == "static":
84
87
  columns_data = ["FilterName"]
85
- ### adding dimensions & metrics in columns names when reportType is "normal"
86
- if "dimension" in dataRequest.keys() and reportType == "normal":
87
- columns_data.append(dataRequest["dimension"])
88
+ elif reportType == "multidimensional":
89
+ columns_data = []
90
+ ### adding dimensions & metrics in columns names when reportType is "normal" or "multidimensional"
91
+ if ("dimension" in dataRequest.keys() or "dimensions" in dataRequest.keys()) and (reportType == "normal" or reportType == "multidimensional"):
92
+ columns_data += [el['id'] for el in dataRequest.get("dimensions", [])]
88
93
  ### adding metrics in columns names
89
- columnIds = columns["columnIds"]
94
+ columnIds = columns.get("columnIds", [])
90
95
  for col in columnIds:
91
96
  metrics: dict = metrics ## case when dict is used
92
97
  metricListName: list = metrics[col].split(":::")
@@ -112,7 +117,7 @@ class Workspace:
112
117
  columns_data.append("FilterId")
113
118
  columns_data += metrics
114
119
  if df_init.empty == False and (
115
- reportType == "static" or reportType == "normal"
120
+ reportType == "static" or reportType == "normal" or reportType == "multidimensional"
116
121
  ):
117
122
  df_init.columns = columns_data
118
123
  self.columns = list(df_init.columns)
@@ -190,6 +195,10 @@ class Workspace:
190
195
  dimension : REQUIRED : dimension to report.
191
196
  n_results : OPTIONAL : number of results you want to have on your breakdown. Default 10, can use "inf"
192
197
  """
198
+ if self.reportType == "multidimensional":
199
+ raise NotImplementedError(
200
+ "Breakdown is not supported for multidimensional report type."
201
+ )
193
202
  if index is None or dimension is None:
194
203
  raise ValueError(
195
204
  "Require a value to use as breakdown and dimension to request"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cjapy
3
- Version: 0.2.4.post3
3
+ Version: 0.3.0
4
4
  Summary: Adobe Customer Journey Analytics (CJA) wrapper
5
5
  Home-page: https://github.com/pitchmuc/cjapy
6
6
  Author: Julien Piccini
@@ -12,7 +12,6 @@ cjapy/configs.py
12
12
  cjapy/connector.py
13
13
  cjapy/projects.py
14
14
  cjapy/requestCreator.py
15
- cjapy/token_provider.py
16
15
  cjapy/workspace.py
17
16
  cjapy.egg-info/PKG-INFO
18
17
  cjapy.egg-info/SOURCES.txt
@@ -8,6 +8,52 @@ This documentation will provide an overview on the different methods available i
8
8
  You can always apply the *_help()_* function to any of the method that are available in your instance.\
9
9
  Normaly a docstring is available to explain the usage of the parameters.
10
10
 
11
+ ## Instantiating the CJA class
12
+
13
+ The `CJA` class accepts an optional `config_object` parameter. Three usage patterns are supported:
14
+
15
+ **Standard (global config)**
16
+
17
+ Call `importConfigFile` or `configure` first, then instantiate `CJA` without arguments:
18
+
19
+ ```python
20
+ import cjapy
21
+
22
+ cjapy.importConfigFile('config.json')
23
+ cja = cjapy.CJA()
24
+ ```
25
+
26
+ **Legacy dict**
27
+
28
+ Pass a raw config dictionary directly (backwards-compatible with older code):
29
+
30
+ ```python
31
+ cja = cjapy.CJA(config_object=my_dict)
32
+ ```
33
+
34
+ **Isolated `ConfigObj` for parallel usage**
35
+
36
+ Use `return_object=True` on `importConfigFile` or `configure` to get a `ConfigObj` instance with its own isolated credentials and token state.\
37
+ Pass it to `CJA` to run multiple independent instances in parallel:
38
+
39
+ ```python
40
+ import cjapy
41
+ from concurrent.futures import ThreadPoolExecutor
42
+
43
+ cfg_a = cjapy.importConfigFile('config_a.json', return_object=True)
44
+ cfg_b = cjapy.importConfigFile('config_b.json', return_object=True)
45
+
46
+ cja_a = cjapy.CJA(config_object=cfg_a)
47
+ cja_b = cjapy.CJA(config_object=cfg_b)
48
+
49
+ with ThreadPoolExecutor() as pool:
50
+ fa = pool.submit(cja_a.getDataViews)
51
+ fb = pool.submit(cja_b.getDataViews)
52
+
53
+ print(fa.result())
54
+ print(fb.result())
55
+ ```
56
+
11
57
  In the following part, I will explain the GET, DELETE and CREATE methods that are available on your instance of this class.\
12
58
  At the end, we will focus briefly on the `getReport` method available.
13
59
 
@@ -94,4 +94,44 @@ myreport = cja.getReport('myRequest.json')
94
94
 
95
95
  You have more information on the method available on the CJA class in that documentation: [CJA class](./cja.md)
96
96
 
97
+ ## 7. Working with multiple CJA instances in parallel
98
+
99
+ If you need to query data from **multiple Adobe IO clients** at the same time (e.g. to parallelise work across different companies or sandboxes), you can use `return_object=True` on `importConfigFile` or `configure` to obtain an isolated `ConfigObj` instance.\
100
+ Each `ConfigObj` holds its own credentials and token state, so multiple `CJA` instances can run concurrently without interfering with each other.
101
+
102
+ ```python
103
+ import cjapy
104
+ from concurrent.futures import ThreadPoolExecutor
105
+
106
+ # Create an isolated config object for each client
107
+ cfg_a = cjapy.importConfigFile('config_client_a.json', return_object=True)
108
+ cfg_b = cjapy.importConfigFile('config_client_b.json', return_object=True)
109
+
110
+ # Or using configure() directly
111
+ cfg_c = cjapy.configure(
112
+ org_id='ORG_C',
113
+ client_id='CLIENT_C',
114
+ secret='SECRET_C',
115
+ scopes='openid,AdobeID,read_organizations',
116
+ return_object=True,
117
+ )
118
+
119
+ # Instantiate one CJA class per config
120
+ cja_a = cjapy.CJA(config_object=cfg_a)
121
+ cja_b = cjapy.CJA(config_object=cfg_b)
122
+ cja_c = cjapy.CJA(config_object=cfg_c)
123
+
124
+ # Run requests in parallel
125
+ with ThreadPoolExecutor() as pool:
126
+ future_a = pool.submit(cja_a.getDataViews)
127
+ future_b = pool.submit(cja_b.getDataViews)
128
+ future_c = pool.submit(cja_c.getDataViews)
129
+
130
+ results_a = future_a.result()
131
+ results_b = future_b.result()
132
+ results_c = future_c.result()
133
+ ```
134
+
135
+ > **Note**: The standard `importConfigFile` / `configure` workflow (without `return_object=True`) continues to work exactly as before and updates the shared global config.
136
+
97
137
  [Back to README](../README.md)
@@ -60,19 +60,48 @@ cja.importConfigFile(myfilePath)
60
60
  ### configure
61
61
 
62
62
  The configure method enables you to set the configuration for the `cjapy` module without importing a file.\
63
- It obviously takes different parameters that are providing all information required for the retrieval of the token:
64
-
65
- The different arguments are:
63
+ It takes the following parameters:
66
64
 
67
65
  * org_id : REQUIRED : Organization ID
68
- * tech_id : REQUIRED : Technical Account ID
66
+ * client_id : REQUIRED : The client ID from your Adobe IO project.
69
67
  * secret : REQUIRED : secret generated for your connection
70
- * client_id : REQUIRED : The client_id (old api_key) provided by the JWT connection.
71
- * scopes : REQUIRED : Require if using the oauth Server to Server
72
- * path_to_key : REQUIRED : If you have a file containing your private key value. If using jwt.
73
- * private_key : REQUIRED : If you do not use a file but pass a variable directly. If using jwt.
68
+ * scopes : REQUIRED : The OAuth Server-to-Server scopes defined in your Adobe IO project.
69
+
70
+ ### ConfigObj and multiple CJA instances
71
+
72
+ Both `importConfigFile` and `configure` accept a `return_object=True` parameter.\
73
+ When set, instead of updating the shared global config they return a `ConfigObj` instance that holds an **isolated** set of credentials and token state.
74
+
75
+ This allows you to create **multiple independent `CJA` instances** — each connected to a different Adobe IO client — and run them in parallel:
76
+
77
+ ```python
78
+ import cjapy
79
+ from concurrent.futures import ThreadPoolExecutor
80
+
81
+ # Isolated config objects — one per client
82
+ cfg_a = cjapy.importConfigFile('config_client_a.json', return_object=True)
83
+ cfg_b = cjapy.configure(
84
+ org_id='ORG_B',
85
+ client_id='CLIENT_B',
86
+ secret='SECRET_B',
87
+ scopes='openid,AdobeID,read_organizations',
88
+ return_object=True,
89
+ )
90
+
91
+ # One CJA instance per config
92
+ cja_a = cjapy.CJA(config_object=cfg_a)
93
+ cja_b = cjapy.CJA(config_object=cfg_b)
94
+
95
+ # Parallelise requests across both clients
96
+ with ThreadPoolExecutor() as pool:
97
+ fa = pool.submit(cja_a.getDataViews)
98
+ fb = pool.submit(cja_b.getDataViews)
99
+
100
+ print(fa.result())
101
+ print(fb.result())
102
+ ```
74
103
 
75
- **Note**: JWT integration will be discontinue in 2025. Hence we do not recommend starting a new integration using the `path_to_key` and `private_key` parameters.
104
+ > **Note**: The standard flow without `return_object=True` continues to work unchanged — `importConfigFile` and `configure` still update the global config used by a default `CJA()` call.
76
105
 
77
106
  ### CJA class
78
107
 
@@ -3,6 +3,14 @@
3
3
  This page will give you the change that are occuring when a new version has been published on pypi.
4
4
  The changes have been tracked starting version 0.1.0
5
5
 
6
+ ## 0.3.0
7
+ * changing the `setDimension` method in `RequestCreator` to `setDimensions` to support multiple dimensions at the same time
8
+ * Adding the capability to import multiple config files and save them as different class instances.
9
+ * configure method can now take an optional parameter: `return_object`
10
+ * importConfigFile can now take an optional parameter: `return_object`
11
+ * Removing JWT references and support for JWT configuration file.
12
+ * More robust handling of issues related to connection errors and over-usage of the API. Refactor of the connector module.
13
+
6
14
  ## 0.2.4
7
15
  * adding the `getUsers` method
8
16
  * adding the `getAssetCount` method
@@ -5,11 +5,22 @@ This class will provide you an instance that contains methods to modify your req
5
5
  In this documentation, we will review the different methods available.
6
6
 
7
7
  ## Menu
8
- - [RequestCreator instanciation](#requestCreator-instanciation)
9
- - [Creating an empty request](#creating-an-empty-request)
10
- - [Uploading a template request](#uploading-a-template-request)
11
- - [Methods availables on RequestCreator](#methods-availables-on-requestCreator-instance)
12
- - [RequestCreator Instance attributes](#requestCreator-instance-attributes)
8
+ - [cjapy : RequestCreator class](#cjapy--requestcreator-class)
9
+ - [Menu](#menu)
10
+ - [RequestCreator instanciation](#requestcreator-instanciation)
11
+ - [Creating an empty request](#creating-an-empty-request)
12
+ - [Uploading a template request](#uploading-a-template-request)
13
+ - [Methods availables on RequestCreator instance](#methods-availables-on-requestcreator-instance)
14
+ - [Adding a simple metric](#adding-a-simple-metric)
15
+ - [Adding a metric with an attribution model](#adding-a-metric-with-an-attribution-model)
16
+ - [Adding a metric with a custom attribution model](#adding-a-metric-with-a-custom-attribution-model)
17
+ - [Adding a metric with position-based attribution model](#adding-a-metric-with-position-based-attribution-model)
18
+ - [Adding a metric with sameTouch attribution model](#adding-a-metric-with-sametouch-attribution-model)
19
+ - [RequestCreator Instance attributes](#requestcreator-instance-attributes)
20
+ - [dates](#dates)
21
+ - [today](#today)
22
+ - [search](#search)
23
+ - [STATIC\_ROW\_REPORT](#static_row_report)
13
24
 
14
25
  ## RequestCreator instanciation
15
26
 
@@ -71,11 +82,26 @@ We will review the different methods available via the object.
71
82
  Arguments:
72
83
  * filename : OPTIONAL : Name of the file. (default cjapy_request_<_timestamp_>.json)
73
84
 
74
- * `setDimension()`
85
+ * `setDimension()` *(deprecated since 0.3.0 — use `setDimensions()` instead)*
75
86
  Set the dimension to be used for reporting.
76
87
  Arguments:
77
88
  * dimension : REQUIRED : the dimension to build your report on
78
89
 
90
+ * `setDimensions()`
91
+ Set one or more dimensions to be used for reporting. Accepts a single dimension string or a list of dimension strings.
92
+ When more than one dimension is provided, `nonesBehavior` is automatically set to `return-nones`.
93
+ Arguments:
94
+ * dimensions : REQUIRED : a dimension ID string, or a list of dimension ID strings
95
+
96
+ Examples:
97
+ ```python
98
+ # Single dimension
99
+ myRequest.setDimensions("variables/eventType")
100
+
101
+ # Multiple dimensions
102
+ myRequest.setDimensions(["variables/eventType", "variables/web.webReferrer.type"])
103
+ ```
104
+
79
105
  * `setDataViewId()`
80
106
  Set the dataView ID to be used for the reporting.
81
107
  Arguments:
@@ -57,8 +57,6 @@ setup(
57
57
  "pathlib2",
58
58
  "pathlib",
59
59
  "requests",
60
- "PyJWT[crypto]",
61
- "PyJWT",
62
60
  "pytest",
63
61
  ],
64
62
  classifiers=CLASSIFIERS,
@@ -1 +0,0 @@
1
- __version__ = "0.2.4-3"
@@ -1,93 +0,0 @@
1
- import os
2
- import time
3
- from typing import Dict, Union
4
-
5
- import jwt
6
- import requests
7
-
8
- from cjapy import configs
9
- import json
10
-
11
-
12
- def get_jwt_token_and_expiry_for_config(config: dict, verbose: bool = False, save: bool = False, *args, **kwargs) -> \
13
- Dict[str, str]:
14
- """
15
- Retrieve the token by using the information provided by the user during the import importConfigFile function.
16
- ArgumentS :
17
- verbose : OPTIONAL : Default False. If set to True, print information.
18
- save : OPTIONAL : Default False. If set to True, save the toke in the .
19
- """
20
- private_key = configs.get_private_key_from_config(config)
21
- header_jwt = {
22
- 'cache-control': 'no-cache',
23
- 'content-type': 'application/x-www-form-urlencoded'
24
- }
25
- now_plus_24h = int(time.time()) + 24 * 60 * 60
26
- jwt_payload = {
27
- 'exp': now_plus_24h,
28
- 'iss': config['org_id'],
29
- 'sub': config['tech_id'],
30
- "https://ims-na1.adobelogin.com/s/ent_dataservices_sdk":True,
31
- 'https://ims-na1.adobelogin.com/s/ent_cja_sdk': True,
32
- 'aud': f'https://ims-na1.adobelogin.com/c/{config["client_id"]}',
33
- }
34
- encoded_jwt = _get_jwt(payload=jwt_payload, private_key=private_key)
35
-
36
- payload = {
37
- 'client_id': config['client_id'],
38
- 'client_secret': config['secret'],
39
- 'jwt_token': encoded_jwt
40
- }
41
- response = requests.post(config['jwtTokenEndpoint'], headers=header_jwt, data=payload)
42
- json_response = response.json()
43
- try:
44
- token = json_response['access_token']
45
- except KeyError:
46
- print('Issue retrieving token')
47
- print(json_response)
48
- expiry = json_response['expires_in'] / 1000
49
- if save:
50
- with open('token.txt', 'w') as f:
51
- f.write(token)
52
- print(f'token has been saved here: {os.getcwd()}{os.sep}token.txt')
53
- if verbose:
54
- print('token valid till : ' + time.ctime(time.time() + expiry))
55
- return {'token': token, 'expiry': expiry}
56
-
57
-
58
- def _get_jwt(payload: dict, private_key: str) -> str:
59
- """
60
- Ensure that jwt enconding return the same type (str) as versions < 2.0.0 returned bytes and >2.0.0 return strings.
61
- """
62
- token: Union[str, bytes] = jwt.encode(payload, private_key, algorithm='RS256')
63
- if isinstance(token, bytes):
64
- return token.decode('utf-8')
65
- return token
66
-
67
- def get_oauth_token_and_expiry_for_config(config: dict,
68
- verbose: bool = False,
69
- save: bool = False
70
- ) -> Dict[str, str]:
71
- """
72
- Retrieve the access token by using the OAuth information provided by the user
73
- during the import importConfigFile function.
74
- Arguments :
75
- config : REQUIRED : Configuration object.
76
- verbose : OPTIONAL : Default False. If set to True, print information.
77
- save : OPTIONAL : Default False. If set to True, save the toke in the .
78
- """
79
- oauth_payload = {
80
- "grant_type": "client_credentials",
81
- "client_id": config["client_id"],
82
- "client_secret": config["secret"],
83
- "scope": config["scopes"]
84
- }
85
- response = requests.post(
86
- config["oauthTokenEndpointV2"], data=oauth_payload
87
- )
88
- responseJson = response.json()
89
- token = responseJson.get('access_token')
90
- expiry = responseJson.get("expires_in")
91
- if token is None or expiry is None:
92
- raise Exception(f"OAuth response missing required fields. Response: {responseJson}")
93
- return {'token': token, 'expiry': expiry}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes