|
| 1 | +import json |
| 2 | + |
| 3 | +from cachetools import LRUCache |
| 4 | + |
| 5 | +from pyld import ContextResolver, DocumentLoader, jsonld |
| 6 | + |
| 7 | +CONTEXT_URL = "context://my-app/vocab" |
| 8 | + |
| 9 | +DOCUMENT_CACHE = { |
| 10 | + CONTEXT_URL: { |
| 11 | + "contentType": "application/ld+json", |
| 12 | + "contextUrl": None, |
| 13 | + "documentUrl": CONTEXT_URL, |
| 14 | + "document": { |
| 15 | + "@context": { |
| 16 | + "name": "https://schema.org/name", |
| 17 | + "homepage": {"@id": "https://schema.org/url", "@type": "@id"}, |
| 18 | + } |
| 19 | + }, |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +class CachedContextLoader(DocumentLoader): |
| 25 | + def __init__(self, documents): |
| 26 | + self.documents = documents |
| 27 | + self.load_count = 0 |
| 28 | + |
| 29 | + def __call__(self, url, options): |
| 30 | + self.load_count += 1 |
| 31 | + return self.documents[url] |
| 32 | + |
| 33 | + |
| 34 | +loader = CachedContextLoader(DOCUMENT_CACHE) |
| 35 | +resolved_context_cache = LRUCache(maxsize=1000) |
| 36 | +resolver = ContextResolver( |
| 37 | + resolved_context_cache, |
| 38 | + loader, |
| 39 | + max_context_urls=20, |
| 40 | +) |
| 41 | + |
| 42 | +doc = { |
| 43 | + "@context": CONTEXT_URL, |
| 44 | + "name": "Example Person", |
| 45 | + "homepage": "https://example.com/", |
| 46 | +} |
| 47 | +options = {"documentLoader": loader, "contextResolver": resolver} |
| 48 | + |
| 49 | +expanded = jsonld.expand(doc, options=options) |
| 50 | +jsonld.expand(doc, options=options) |
| 51 | + |
| 52 | +print(json.dumps({"contextLoads": loader.load_count, "expanded": expanded}, indent=2)) |
0 commit comments