Skip to content

Instantly share code, notes, and snippets.

@georgepadayatti
Last active March 25, 2022 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgepadayatti/33cae6a54faa924017c6fadc354aad7f to your computer and use it in GitHub Desktop.
Save georgepadayatti/33cae6a54faa924017c6fadc354aad7f to your computer and use it in GitHub Desktop.
JSON-LD context cache in pyld (Python)

JSON-LD context cache in PyLD

Problem

When performing canonization of a JSON-LD document, it is necessary to perform compact, expand and normalise operations. This would involve resolving multiple remote contexts. Since the contexts are located in a remote host, the availability of the resource cannot be garunteed. Fetching a remote resource adds significant latency if the remote server doesn't respond fast.

Solution

Implement a cache for remote contexts. This can be done by caching the responses from the document loader used by PyLD. A simple cache snippet using python dictionary for PyLD is given below.

from pyld import jsonld

cache = {}

def caching_document_loader(url, options):

    loader = jsonld.requests_document_loader()
    
    if url in cache:
        return cache[url]
        
    resp = loader(url)
    
    cache[url] = resp
    
    return resp

jsonld.set_document_loader(caching_document_loader)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment