Skip to content

Commit

Permalink
Backwards compatibility - templates (#128)
Browse files Browse the repository at this point in the history
* Backwards compatibility for specifying bufr template by file name, addition of test.

* two blank lines
  • Loading branch information
david-i-berry committed Feb 9, 2024
1 parent 47c9e89 commit b0d7654
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 13 deletions.
40 changes: 27 additions & 13 deletions csv2bufr/templates/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,16 @@
LOGGER.error(msg)
raise RuntimeError(msg)


if Path("/opt/csv2bufr/templates").exists():
TEMPLATE_DIRS.append(Path("/opt/csv2bufr/templates"))

# Set user defined location first
if 'CSV2BUFR_TEMPLATES' in os.environ:
TEMPLATE_DIRS.append(Path(os.environ['CSV2BUFR_TEMPLATES']))
else:
LOGGER.warning(f"""CSV2BUFR_TEMPLATES is not set, default search path(s)
will be used ({TEMPLATE_DIRS}).""")

if Path("/opt/csv2bufr/templates").exists():
TEMPLATE_DIRS.append(Path("/opt/csv2bufr/templates"))

# Dictionary to store template filename and label (if assigned)
TEMPLATES = {}

Expand All @@ -76,19 +75,31 @@ def load_template(template_name: str) -> Union[dict, None]:
"""
template = None
msg = False
fname = None
error_flag = False
if template_name not in TEMPLATES:
msg = f"Requested template '{template_name}' not found." +\
f" Search path = {TEMPLATE_DIRS}. Please update " +\
"search path (e.g. 'export CSV2BUFR_TEMPLATE=...')"
msg = f"Requested template {template_name} not found, " +\
"searching by file name"
for _template in TEMPLATES.values():
if template_name in _template.get('path'):
fname = _template.get('path')
break
if fname is None:
msg = f"Requested template '{template_name}' not found. " +\
f"Search path = {TEMPLATE_DIRS}. Please update " +\
"search path (e.g. 'export CSV2BUFR_TEMPLATE=...')"
error_flag = True
else:
fname = TEMPLATES[template_name].get('path')
if fname is None:
msg = f"Error loading template {template_name}, no path found"
else:
with open(fname) as fh:
template = json.load(fh)

if msg:
if fname is None:
msg = f"Error loading template {template_name}, no path found"
error_flag = True
else:
with open(fname) as fh:
template = json.load(fh)

if error_flag:
raise RuntimeError(msg)
else:
# update template originating centre and subcentre
Expand All @@ -114,6 +125,9 @@ def load_template(template_name: str) -> Union[dict, None]:
{"eccodes_key": "bufrHeaderSubCentre",
"value": f"const:{ORIGINATING_SUBCENTRE}"})

if msg:
LOGGER.warning(msg)

return template


Expand Down
5 changes: 5 additions & 0 deletions tests/test_csv2bufr.py
Original file line number Diff line number Diff line change
Expand Up @@ -279,3 +279,8 @@ def test_templates():
oscset = True
assert ocset
assert oscset


def test_load_template_by_name():
tmpl = c2bt.load_template('aws-template')
assert tmpl is not None

0 comments on commit b0d7654

Please sign in to comment.