Skip to content

Commit

Permalink
Add odata_compact_json decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
gbryant-dev committed Nov 13, 2021
1 parent 419852c commit 793630d
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion TM1py/Services/CellService.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from TM1py.Services.ViewService import ViewService
from TM1py.Utils import Utils, CaseAndSpaceInsensitiveSet, format_url, add_url_parameters
from TM1py.Utils.Utils import build_pandas_dataframe_from_cellset, dimension_name_from_element_unique_name, \
CaseAndSpaceInsensitiveDict, wrap_in_curly_braces, CaseAndSpaceInsensitiveTuplesDict, abbreviate_mdx, \
CaseAndSpaceInsensitiveDict, extract_cell_properties_from_odata_context, map_cell_properties_to_data, wrap_in_curly_braces, CaseAndSpaceInsensitiveTuplesDict, abbreviate_mdx, \
build_csv_from_cellset_dict, require_version, require_pandas, build_cellset_from_pandas_dataframe, \
case_and_space_insensitive_equals, get_cube, resembles_mdx, require_admin

Expand Down Expand Up @@ -115,6 +115,54 @@ def wrapper(self, *args, **kwargs):
return wrapper


def odata_compact_json(return_props_with_data: Optional[bool] = True):
""" Higher order function to manage header and response when using compact JSON
Applies when decorated function has `use_compact_json` argument set to True
Currently only supports responses with only cell properties and where they are explicitly specified:
* Cellsets('...')?$expand=Axes(...),Cells($select=Ordinal,Value...) does NOT work !
* Cellsets('...')?$expand=Cells does NOT work !
* Cellsets('...')?$expand=Cells($select=Ordinal,Value...) works !
"""
def wrap(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
if kwargs.get("use_compact_json", False):
# Update Accept Header
header = self._rest.get_http_header('Accept')
parts = header.split(';')
# Point of insertion is important. Needs to come after application/json
parts.insert(1, 'tm1.compact=v0')
modified_header = ";".join(parts)
self._rest.add_http_header('Accept', modified_header)
try:
response = func(self, *args, **kwargs)
context = response['@odata.context']

props = extract_cell_properties_from_odata_context(context)

# First element [0] is the cellset ID, second is the cellset data
data = response['value'][1]

# return props with data if required
if return_props_with_data:
return map_cell_properties_to_data(props, data)

if len(props) == 1:
return [value[0] for value in data]

return data
finally:
# Restore original header
self._rest.add_http_header('Accept', header)
else:
return func(self, *args, **kwargs)
return wrapper
return wrap


class CellService(ObjectService):
""" Service to handle Read and Write operations to TM1 cubes
Expand Down

0 comments on commit 793630d

Please sign in to comment.