44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import json
|
|
from os import environ as env
|
|
from urllib.parse import quote_plus as url_encode
|
|
from pathlib import Path
|
|
|
|
def get_jrd(resource: str) -> dict[str, str | list[str] | dict[str,str]]:
|
|
"""
|
|
Obtain a JSON Resource Descriptor (JRD)
|
|
|
|
A JRD is a JSON object containing the following:
|
|
- subject (string value; SHOULD be present)
|
|
- aliases (array of string values; OPTIONAL)
|
|
- properties (object containing key-value pairs as strings; OPTIONAL)
|
|
- links (array of objects containing link relation information; OPTIONAL)
|
|
|
|
Parameters:
|
|
resource (str): The URI of the resouce
|
|
|
|
Returns:
|
|
jrd (dict): Parsed JRD
|
|
|
|
Raises:
|
|
FileNotFoundError: No JRD file exists in the resource directory
|
|
OSError: A file may exist, but it is not readable
|
|
json.JSONDecodeError: A file exists, but does not contain a valid JSON object
|
|
"""
|
|
# Get a filename for the resource document.
|
|
dir = env.get("RESOURCE_DIR") or "resource"
|
|
filename = resource
|
|
path = f"{dir}/{filename}.json"
|
|
|
|
# If we can't get a file, try percent-encoding
|
|
if not Path(path).is_file():
|
|
filename = url_encode(resource)
|
|
path = f"{dir}/{filename}.json"
|
|
|
|
# Open the file and load the JSON as a dictionary.
|
|
try:
|
|
with open(path, "r") as file:
|
|
jrd: dict[str, str | list[str] | dict[str,str]] = json.loads(file.read())
|
|
except:
|
|
raise
|
|
|
|
return jrd |