Skip to content

Commit f0681dd

Browse files
authored
Changed resource URI format in hydra-python-core and fixed tests. (#81)
* changed uri format * updated doc_writer_sample * fixed doc writer tests * fixed tests * fix pep8
1 parent f6b6e6d commit f0681dd

File tree

8 files changed

+264
-204
lines changed

8 files changed

+264
-204
lines changed

docs/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,4 @@
5454
# Add any paths that contain custom static files (such as style sheets) here,
5555
# relative to this directory. They are copied after the builtin static files,
5656
# so a file named "default.css" will overwrite the builtin "default.css".
57-
html_static_path = ['_static']
57+
html_static_path = ['_static']

hydra_python_core/doc_maker.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
from pyld import jsonld
77
import requests
88
from hydra_python_core.doc_writer import (HydraDoc, HydraClass, HydraClassProp,
9-
HydraClassOp, HydraStatus, HydraLink, HydraCollection, DocUrl)
9+
HydraClassOp, HydraStatus, HydraLink,
10+
HydraCollection, DocUrl)
1011
from typing import Any, Dict, Match, Optional, Tuple, Union, List
1112
from hydra_python_core.namespace import hydra, rdfs
1213
from urllib.parse import urlparse
@@ -30,7 +31,6 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None,
3031
if not all(key in doc for key in ('@context', '@id', '@type')):
3132
raise SyntaxError("Please make sure doc contains @context, @id and @type")
3233

33-
3434
_context = doc['@context']
3535
base_url = ''
3636
entrypoint = ''
@@ -115,7 +115,8 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None,
115115

116116
# make endpoint classes
117117
for endpoint_classes in _endpoint_class:
118-
if endpoint_classes['@id'] == hydra['Resource'] or endpoint_classes['@id'] == hydra['Collection'] or \
118+
if endpoint_classes['@id'] == hydra['Resource'] or \
119+
endpoint_classes['@id'] == hydra['Collection'] or \
119120
endpoint_classes['@id'].find("EntryPoint") != -1:
120121
continue
121122
class_ = create_class(endpoint_classes, endpoint=True)
@@ -145,6 +146,7 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None,
145146
apidoc.gen_EntryPoint()
146147
return apidoc
147148

149+
148150
def create_collection(endpoint_collection: Dict[str, Any]) -> HydraCollection:
149151
"""
150152
Creates the instance of HydraCollection from expanded APIDOC
@@ -164,11 +166,14 @@ def create_collection(endpoint_collection: Dict[str, Any]) -> HydraCollection:
164166

165167
manages = {}
166168
if hydra['object'] in endpoint_collection[hydra['manages']][0]:
167-
manages['object'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['object']][0]['@id'])
169+
object_id = endpoint_collection[hydra['manages']][0][hydra['object']][0]['@id']
170+
manages['object'] = check_namespace(object_id)
168171
if hydra['subject'] in endpoint_collection[hydra['manages']][0]:
169-
manages['subject'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['subject']][0]['@id'])
172+
subject_id = endpoint_collection[hydra['manages']][0][hydra['subject']][0]['@id']
173+
manages['subject'] = check_namespace(subject_id)
170174
if hydra['property'] in endpoint_collection[hydra['manages']][0]:
171-
manages['property'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['property']][0]['@id'])
175+
property_id = endpoint_collection[hydra['manages']][0][hydra['property']][0]['@id']
176+
manages['property'] = check_namespace(property_id)
172177
is_get = False
173178
is_post = False
174179
is_put = False
@@ -364,13 +369,11 @@ def create_link(supported_property: Dict[str, Any]) -> HydraLink:
364369

365370
def check_namespace(id_: str = None) -> str:
366371
"""
367-
A helper method to check if the classes and properties are in the same namespace and if not bring them
368-
into the right namespace
372+
A helper method to check if the classes and properties are in the same
373+
namespace and if not bring them into the right namespace
369374
:param id_ The id to check
370375
:return: correct url
371376
"""
372-
if id_.find(DocUrl.doc_url) == -1 and id_ != "null" and id_.find('#') != -1:
373-
id_ = "{}{}".format(DocUrl.doc_url, id_.split('#')[-1])
377+
if id_.find(DocUrl.doc_url) == -1 and id_ != "null" and id_.find('?resource=') != -1:
378+
id_ = "{}{}".format(DocUrl.doc_url, id_.split('?resource=')[-1])
374379
return id_
375-
376-

hydra_python_core/doc_writer.py

Lines changed: 63 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ def generate(self) -> Dict[str, Any]:
109109
"description": self.desc,
110110
"entrypoint": urljoin(self.base_url, self.entrypoint_endpoint),
111111
"supportedClass": [
112-
x.generate() for x in parsed_classes + self.other_classes + collections + [self.entrypoint]],
112+
x.generate()
113+
for x in parsed_classes + self.other_classes + collections + [self.entrypoint]
114+
],
113115
"possibleStatus": [status.generate() for status in self.possible_status]
114116
}
115117
return doc
@@ -214,15 +216,16 @@ def generate(self) -> Dict[str, Any]:
214216
class HydraClassOp():
215217
"""Template for a new supportedOperation."""
216218

217-
def __init__(self,
218-
title: str,
219-
method: str,
220-
expects: Optional[str],
221-
returns: Optional[str],
222-
expects_header: List[str] = [],
223-
returns_header: List[str] = [],
224-
possible_status: List[Union['HydraStatus', 'HydraError']] = [],
225-
) -> None:
219+
def __init__(
220+
self,
221+
title: str,
222+
method: str,
223+
expects: Optional[str],
224+
returns: Optional[str],
225+
expects_header: List[str] = [],
226+
returns_header: List[str] = [],
227+
possible_status: List[Union['HydraStatus', 'HydraError']]=[],
228+
) -> None:
226229
"""Initialize the Hydra_Prop."""
227230
self.title = title
228231
self.method = method
@@ -267,52 +270,59 @@ def __init__(
267270
collection_name: str = None,
268271
collection_path: str = None,
269272
collection_description: str = None,
270-
manages: Union[Dict[str, Any], List] = None,
273+
manages: Union[Dict[str, Any], List]=None,
271274
get: bool = True, post: bool = True, put: bool = True, delete: bool = True) -> None:
272275
"""Generate Collection for related resources."""
273276
self.collection_id = "{}{}".format(DocUrl.doc_url, quote(collection_name, safe=''))
274277
self.name = collection_name
275278
self.collection_description = collection_description
276279
self.path = collection_path if collection_path else self.name
277280
self.supportedOperation = list() # type: List
278-
self.supportedProperty = [HydraClassProp("http://www.w3.org/ns/hydra/core#member",
279-
"members",
280-
True, True, False,
281-
"The members of {}".format(collection_name))]
281+
self.supportedProperty = [HydraClassProp(
282+
"http://www.w3.org/ns/hydra/core#member",
283+
"members",
284+
True,
285+
True,
286+
False,
287+
"The members of {}".format(collection_name))]
282288
self.manages = manages
283289

284290
if get:
285-
get_op = HydraCollectionOp("_:{}_retrieve".format(self.name),
286-
"http://schema.org/FindAction",
287-
"GET", "Retrieves all the members of {}".format(self.name),
288-
None, self.manages['object'], [], [], [])
291+
get_op = HydraCollectionOp(
292+
"_:{}_retrieve".format(self.name),
293+
"http://schema.org/FindAction",
294+
"GET", "Retrieves all the members of {}".format(self.name),
295+
None, self.manages['object'], [], [], [])
289296
self.supportedOperation.append(get_op)
290297

291298
if put:
292-
put_op = HydraCollectionOp("_:{}_create".format(self.name), "http://schema.org/AddAction",
293-
"PUT", "Create new member in {}".format(self.name),
294-
self.manages['object'], self.manages['object'], [], [],
295-
[HydraStatus(code=201, desc="A new member in {} created".format(self.name))]
296-
)
299+
put_op = HydraCollectionOp(
300+
"_:{}_create".format(self.name), "http://schema.org/AddAction",
301+
"PUT", "Create new member in {}".format(self.name),
302+
self.manages['object'], self.manages['object'], [], [],
303+
[HydraStatus(code=201, desc="A new member in {} created".format(self.name))]
304+
)
297305
self.supportedOperation.append(put_op)
298306
if post:
299-
post_op = HydraCollectionOp("_:{}_update".format(self.name),
300-
"http://schema.org/UpdateAction",
301-
"POST", "Update member of {} ".format(self.name),
302-
self.manages['object'], self.manages['object'], [], [],
303-
[HydraStatus(code=200, desc="If the entity was updated"
304-
"from {}.".format(self.name))]
305-
)
307+
post_op = HydraCollectionOp(
308+
"_:{}_update".format(self.name),
309+
"http://schema.org/UpdateAction",
310+
"POST", "Update member of {} ".format(self.name),
311+
self.manages['object'], self.manages['object'], [], [],
312+
[HydraStatus(code=200, desc="If the entity was updated"
313+
"from {}.".format(self.name))]
314+
)
306315
self.supportedOperation.append(post_op)
307316

308317
if delete:
309-
delete_op = HydraCollectionOp("_:{}_delete".format(self.name),
310-
"http://schema.org/DeleteAction",
311-
"DELETE", "Delete member of {} ".format(self.name),
312-
self.manages['object'], self.manages['object'], [], [],
313-
[HydraStatus(code=200, desc="If entity was deleted"
314-
"successfully from {}.".format(self.name))]
315-
)
318+
delete_op = HydraCollectionOp(
319+
"_:{}_delete".format(self.name),
320+
"http://schema.org/DeleteAction",
321+
"DELETE", "Delete member of {} ".format(self.name),
322+
self.manages['object'], self.manages['object'], [], [],
323+
[HydraStatus(code=200, desc="If entity was deleted"
324+
"successfully from {}.".format(self.name))]
325+
)
316326
self.supportedOperation.append(delete_op)
317327

318328
def generate(self) -> Dict[str, Any]:
@@ -343,7 +353,7 @@ def __init__(self,
343353
returns: Optional[str],
344354
expects_header: List[str] = [],
345355
returns_header: List[str] = [],
346-
possible_status: List[Union['HydraStatus', 'HydraError']] = [],
356+
possible_status: List[Union['HydraStatus', 'HydraError']]=[],
347357
) -> None:
348358
"""Create method."""
349359
self.id_ = id_
@@ -379,18 +389,19 @@ def __init__(self, base_url: str, entrypoint: str) -> None:
379389
"""Initialize the Entrypoint."""
380390
self.url = base_url
381391
self.api = entrypoint
392+
class_id = "{}?resource=EntryPoint".format(urljoin(self.url, self.api))
382393
self.entrypoint = HydraClass("EntryPoint", "The main entry point or homepage of the API.",
383-
_id="{}#EntryPoint".format(urljoin(self.url, self.api)))
394+
_id=class_id)
384395
self.entrypoint.add_supported_op(EntryPointOp(
385396
"_:entry_point".format(base_url), "GET", "The APIs main entry point.", None, None,
386-
type_="{}/{}#EntryPoint".format(base_url, entrypoint)))
397+
type_="{}/{}?resource=EntryPoint".format(base_url, entrypoint)))
387398
self.context = Context(
388399
"{}{}".format(
389400
base_url,
390401
entrypoint),
391402
entrypoint=self)
392403

393-
self.collections: List[EntryPointCollection] = []
404+
self.collections = list()
394405

395406
def add_Class(self, class_: HydraClass) -> None:
396407
"""Add supportedProperty to the EntryPoint.
@@ -428,8 +439,8 @@ def generate(self) -> Dict[str, Any]:
428439
def get(self) -> Dict[str, str]:
429440
"""Create the EntryPoint object to be returnd for the get function."""
430441
object_ = {
431-
"@context": "{}{}/contexts/EntryPoint.jsonld".format(self.url,self.api),
432-
"@id": "{}{}".format(self.url,self.api),
442+
"@context": "{}{}/contexts/EntryPoint.jsonld".format(self.url, self.api),
443+
"@id": "{}{}".format(self.url, self.api),
433444
"@type": "EntryPoint",
434445

435446
}
@@ -438,7 +449,7 @@ def get(self) -> Dict[str, str]:
438449
if item.generate() in self.collections:
439450
collection_returned = item.generate()
440451
collection_id = uri.replace(
441-
"{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url,self.api))
452+
"{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url, self.api))
442453
collection_to_append = {
443454
"@id": collection_id,
444455
'title': collection_returned['hydra:title'],
@@ -454,7 +465,7 @@ def get(self) -> Dict[str, str]:
454465

455466
else:
456467
object_[item.name] = uri.replace(
457-
"{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url,self.api))
468+
"{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url, self.api))
458469

459470
return object_
460471

@@ -554,7 +565,7 @@ def __init__(self,
554565
returns: Optional[str],
555566
expects_header: List[str] = [],
556567
returns_header: List[str] = [],
557-
possible_status: List[Union['HydraStatus', 'HydraError']] = [],
568+
possible_status: List[Union['HydraStatus', 'HydraError']]=[],
558569
type_: Optional[str] = None,
559570
label: str = "",
560571
) -> None:
@@ -639,10 +650,10 @@ def __init__(self,
639650

640651
def generate(self) -> Dict[str, Any]:
641652
"""Get IriTemplate as a python dict"""
642-
base_url = DocUrl.doc_url.rsplit('/',2)[0]
653+
base_url = DocUrl.doc_url.rsplit('/', 2)[0]
643654
iri_template = {
644655
"@type": "hydra:IriTemplate",
645-
"hydra:template": "{}{}".format(base_url,self.template),
656+
"hydra:template": "{}{}".format(base_url, self.template),
646657
"hydra:variableRepresentation": self.variable_rep,
647658
"hydra:mapping": [x.generate() for x in self.mapping]
648659
}
@@ -739,7 +750,8 @@ def __init__(self,
739750
# context elements to the base Hydra context
740751
if class_ is not None:
741752
self.context = {"hydra": "http://www.w3.org/ns/hydra/core#",
742-
"members": "http://www.w3.org/ns/hydra/core#member", "object": "http://schema.org/object",
753+
"members": "http://www.w3.org/ns/hydra/core#member",
754+
"object": "http://schema.org/object",
743755
class_.title: class_.id_} # type: Dict[str, Any]
744756
for prop in class_.supportedProperty:
745757
if isinstance(prop.prop, HydraLink):
@@ -840,4 +852,4 @@ class DocUrl:
840852
doc_url = ''
841853

842854
def __init__(self, base_url: str, api_name: str, doc_name: str) -> None:
843-
DocUrl.doc_url = "{}/{}#".format(urljoin(base_url, api_name), doc_name)
855+
DocUrl.doc_url = "{}/{}?resource=".format(urljoin(base_url, api_name), doc_name)

hydra_python_core/namespace.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,4 @@
8686
"domain": rdfsNamespace + "domain",
8787
"label": rdfsNamespace + "label",
8888
"range": rdfsNamespace + "range"
89-
}
89+
}

0 commit comments

Comments
 (0)