Skip to content

Commit 6f0094e

Browse files
author
irinaschubert
authored
fix(ontology): add default values for missing comments (DEV-337) (#141)
* fix property comments * fix default comment for resources * rename user variable to user_mail * make return type of getAllGroups optional * refactor project * change return type * refactor ontology creation * add try except clauses to list creation * replace typing types with built-in types * delete knora library readme * use indent of 4 instead of 3 when dumping json * improve code after review
1 parent 656ccff commit 6f0094e

24 files changed

Lines changed: 706 additions & 1271 deletions

‎knora/README.md‎

Lines changed: 0 additions & 683 deletions
This file was deleted.

‎knora/dsp_tools.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ def program(user_args: list[str]) -> None:
163163
create_ontology(input_file=args.datamodelfile,
164164
lists_file=args.listfile,
165165
server=args.server,
166-
user=args.user,
166+
user_mail=args.user,
167167
password=args.password,
168168
verbose=args.verbose,
169169
dump=args.dump if args.dump else False)

‎knora/dsplib/models/bitstream.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Dict, Optional, Any
1+
from typing import Optional, Any
22

33
from pystrict import strict
44

@@ -28,7 +28,7 @@ def value(self) -> str:
2828
def permissions(self) -> Optional[Permissions]:
2929
return self._permissions
3030

31-
def toJsonLdObj(self, action: Actions) -> Dict[str, Any]:
31+
def toJsonLdObj(self, action: Actions) -> dict[str, Any]:
3232
tmp = {}
3333
if action == Actions.Create:
3434
tmp["knora-api:fileValueHasFilename"] = self._value

‎knora/dsplib/models/connection.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import json
2-
from typing import Dict, Optional, Union
2+
from typing import Optional, Union
33

44
import requests
55
from pystrict import strict
@@ -19,11 +19,11 @@ class Connection:
1919
"""
2020

2121
_server: str
22-
_prefixes: Union[Dict[str, str], None]
22+
_prefixes: Union[dict[str, str], None]
2323
_token: Union[str, None]
2424
_log: bool
2525

26-
def __init__(self, server: str, prefixes: Dict[str, str] = None):
26+
def __init__(self, server: str, prefixes: dict[str, str] = None):
2727
"""
2828
Constructor requiring the server address, the user and password of KNORA
2929
:param server: Address of the server, e.g https://api.dasch.swiss
@@ -153,12 +153,12 @@ def post(self, path: str, jsondata: Optional[str] = None):
153153
tmp = path.split('/')
154154
filename = "POST" + "_".join(tmp) + ".json"
155155
with open(filename, 'w') as f:
156-
json.dump(logobj, f, indent=3)
156+
json.dump(logobj, f, indent=4)
157157
self.on_api_error(req)
158158
result = req.json()
159159
return result
160160

161-
def get(self, path: str, headers: Optional[Dict[str, str]] = None):
161+
def get(self, path: str, headers: Optional[dict[str, str]] = None):
162162
"""
163163
Get data from a server using a HTTP GET request
164164
:param path: Path of RESTful route

‎knora/dsplib/models/group.py‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
from __future__ import annotations
2+
13
import json
2-
from typing import List, Optional, Any, Union
4+
from typing import Optional, Any, Union
35
from urllib.parse import quote_plus
46

57
from pystrict import strict
68

7-
from knora.dsplib.models.langstring import LangString, Languages
9+
from knora.dsplib.models.langstring import LangString
810
from .connection import Connection
911
from .helpers import Actions, BaseError
1012
from .model import Model
@@ -211,7 +213,7 @@ def toJsonObj(self, action: Actions):
211213
tmp['selfjoin'] = self._selfjoin
212214
return tmp
213215

214-
def create(self):
216+
def create(self) -> Group:
215217
jsonobj = self.toJsonObj(Actions.Create)
216218
jsondata = json.dumps(jsonobj)
217219
result = self._con.post(Group.ROUTE, jsondata)
@@ -238,14 +240,16 @@ def delete(self):
238240
return Group.fromJsonObj(self._con, result['group'])
239241

240242
@staticmethod
241-
def getAllGroups(con: Connection) -> List['Group']:
242-
result = con.get(Group.ROUTE)
243-
if 'groups' not in result:
244-
raise BaseError("Request got no groups!")
245-
return list(map(lambda a: Group.fromJsonObj(con, a), result['groups']))
243+
def getAllGroups(con: Connection) -> Optional[list[Group]]:
244+
try:
245+
result = con.get(Group.ROUTE)
246+
return [Group.fromJsonObj(con, group_item) for group_item in result["groups"]]
247+
except BaseError:
248+
# return None if no groups are found or an error happened
249+
return None
246250

247251
@staticmethod
248-
def getAllGroupsForProject(con: Connection, proj_shortcode: str) -> List['Group']:
252+
def getAllGroupsForProject(con: Connection, proj_shortcode: str) -> list[Group]:
249253
result = con.get(Group.ROUTE)
250254
if 'groups' not in result:
251255
raise BaseError("Request got no groups!")
@@ -265,7 +269,7 @@ def createDefinitionFileObj(self):
265269
}
266270
return group
267271

268-
def print(self):
272+
def print(self) -> None:
269273
print('Group Info:')
270274
print(' Id: {}'.format(self._id))
271275
print(' Name: {}'.format(self._name))

‎knora/dsplib/models/helpers.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from dataclasses import dataclass
44
from enum import Enum, unique
55
from traceback import format_exc
6-
from typing import NewType, List, Dict, Optional, Any, Tuple, Union, Pattern
6+
from typing import NewType, Optional, Any, Tuple, Union, Pattern
77

88
from pystrict import strict
99

@@ -23,7 +23,7 @@ class OntoInfo:
2323
hashtag: bool
2424

2525

26-
ContextType = NewType("ContextType", Dict[str, OntoInfo])
26+
ContextType = NewType("ContextType", dict[str, OntoInfo])
2727

2828

2929
def LINE() -> int:
@@ -86,7 +86,7 @@ class Cardinality(Enum):
8686
@strict
8787
class ContextIterator:
8888
_context: 'Context'
89-
_prefixes: List[str]
89+
_prefixes: list[str]
9090
_index: int
9191

9292
def __init__(self, context: 'Context'):
@@ -111,10 +111,10 @@ class Context:
111111
This class holds a JSON-LD context with the ontology IRI's and the associated prefixes
112112
"""
113113
_context: ContextType
114-
_rcontext: Dict[str, str]
114+
_rcontext: dict[str, str]
115115
_exp: Pattern[str]
116116

117-
common_ontologies = ContextType({
117+
common_ontologies = ContextType({
118118
"foaf": OntoInfo("http://xmlns.com/foaf/0.1/", False),
119119
"dc": OntoInfo("http://purl.org/dc/elements/1.1/", False),
120120
"dcterms": OntoInfo("http://purl.org/dc/terms/", False),
@@ -148,7 +148,7 @@ def __is_iri(self, val: str) -> bool:
148148
m = self._exp.match(val)
149149
return m.span()[1] == len(val) if m else False
150150

151-
def __init__(self, context: Optional[Dict[str, str]] = None):
151+
def __init__(self, context: Optional[dict[str, str]] = None):
152152
"""
153153
THe Constructor of the Context. It takes one optional parameter which as a dict of
154154
prefix - ontology-iri pairs. If the hashtag "#" is used to append element name, the
@@ -158,17 +158,17 @@ def __init__(self, context: Optional[Dict[str, str]] = None):
158158
# regexp to test for a complete IRI (including fragment identifier)
159159
self._exp = re.compile("^(http)s?://([\\w\\.\\-~]+)?(:\\d{,6})?(/[\\w\\-~]+)*(#[\\w\\-~]*)?")
160160
self._context = ContextType({})
161-
161+
162162
# add ontologies from context, if any
163163
if context:
164164
for prefix, onto in context.items():
165165
self._context[prefix] = OntoInfo(onto.removesuffix('#'), onto.endswith('#'))
166-
166+
167167
# add standard ontologies (rdf, rdfs, owl, xsl)
168168
for k, v in self.base_ontologies.items():
169169
if not self._context.get(k):
170170
self._context[k] = v
171-
171+
172172
# add DSP-API internal ontologies (knora-api, salsah-gui)
173173
for k, v in self.knora_ontologies.items():
174174
if not self._context.get(k):
@@ -224,7 +224,7 @@ def context(self, value: ContextType) -> None:
224224
raise BaseError("Error in parameter to context setter")
225225

226226
@property
227-
def rcontext(self) -> Dict[str, str]:
227+
def rcontext(self) -> dict[str, str]:
228228
return self._rcontext
229229

230230
def add_context(self, prefix: str, iri: Optional[str] = None) -> None:
@@ -400,15 +400,15 @@ def reduce_iri(self, iristr: str, ontoname: Optional[str] = None) -> str:
400400
else:
401401
return iristr
402402

403-
def toJsonObj(self) -> Dict[str, str]:
403+
def toJsonObj(self) -> dict[str, str]:
404404
"""
405405
Return a python object that can be jsonfied...
406406
:return: Object to be jsonfied
407407
"""
408408
return {prefix: oinfo.iri + '#' if oinfo.hashtag else oinfo.iri
409409
for prefix, oinfo in self._context.items()}
410410

411-
def get_externals_used(self) -> Dict[str, str]:
411+
def get_externals_used(self) -> dict[str, str]:
412412
exclude = ["rdf", "rdfs", "owl", "xsd", "knora-api", "salsah-gui"]
413413
return {prefix: onto.iri for prefix, onto in self._context.items() if prefix not in exclude}
414414

@@ -487,7 +487,7 @@ class WithId:
487487
"""
488488
_tmp: str = None
489489

490-
def __init__(self, obj: Optional[Dict[str, str]]):
490+
def __init__(self, obj: Optional[dict[str, str]]):
491491
if obj is None:
492492
return
493493
self._tmp = obj.get('@id')

‎knora/dsplib/models/langstring.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from enum import Enum, unique
2-
from typing import List, Dict, Tuple, Optional, Any, Union
2+
from typing import Tuple, Optional, Any, Union
33

44
from ..models.helpers import BaseError
55

@@ -12,7 +12,7 @@ class Languages(Enum):
1212
IT = 'it'
1313

1414

15-
LangStringParam = Optional[Union[Dict[Union[Languages, str], str], str]]
15+
LangStringParam = Optional[Union[dict[Union[Languages, str], str], str]]
1616

1717

1818
class LangStringIterator:
@@ -53,7 +53,7 @@ class LangString:
5353
"some:thing": "a string without language specificer"
5454
```
5555
"""
56-
_langstrs: Dict[Languages, str]
56+
_langstrs: dict[Languages, str]
5757
_simplestring: str
5858

5959
def __init__(self, initvalue: LangStringParam = None):
@@ -204,7 +204,7 @@ def toJsonLdObj(self):
204204
# return list(map(lambda a: {'@language': a[0].value, '@value': a[1]}, self._langstrs.items()))
205205

206206
@classmethod
207-
def fromJsonLdObj(cls, obj: Optional[Union[List[Dict[str, str]], str]]) -> 'LangString':
207+
def fromJsonLdObj(cls, obj: Optional[Union[list[dict[str, str]], str]]) -> 'LangString':
208208
if obj is None:
209209
return None
210210
if isinstance(obj, str):
@@ -213,7 +213,7 @@ def fromJsonLdObj(cls, obj: Optional[Union[List[Dict[str, str]], str]]) -> 'Lang
213213
objs = obj
214214
else:
215215
objs = [obj]
216-
lstrs: Dict[Languages, str] = {}
216+
lstrs: dict[Languages, str] = {}
217217
for o in objs:
218218
lang = o.get('@language')
219219
if lang == 'en':
@@ -239,7 +239,7 @@ def fromJsonObj(cls, obj: Optional[Any]) -> 'LangString':
239239
objs = obj
240240
else:
241241
objs = [obj]
242-
lstrs: Dict[Languages, str] = {}
242+
lstrs: dict[Languages, str] = {}
243243
for o in objs:
244244
lang = o.get('language')
245245
if lang == 'en':
@@ -268,7 +268,7 @@ def print(self, offset: Optional[int] = None):
268268
def langstrs(self):
269269
return self._langstrs
270270

271-
def createDefinitionFileObj(self) -> Union[str, Dict[str, str]]:
271+
def createDefinitionFileObj(self) -> Union[str, dict[str, str]]:
272272
if self._simplestring:
273273
return self._simplestring
274274
langstring = {}

‎knora/dsplib/models/listnode.py‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,8 @@
3838
def list_creator(con: Connection,
3939
project: Project,
4040
parent_node: 'ListNode',
41-
nodes: List[dict]) -> List['ListNode']:
42-
43-
nodelist: List[ListNode] = []
41+
nodes: list[dict]) -> list['ListNode']:
42+
nodelist: list[ListNode] = []
4443

4544
for node in nodes:
4645
new_node = ListNode(
@@ -96,7 +95,7 @@ class ListNode(Model):
9695
isRootNode : bool
9796
Is True if the ListNode is the root node of a list. Cannot be set [read].
9897
99-
children : List[ListNode]
98+
children : list[ListNode]
10099
Contains a list of child nodes. This attribute is only available for nodes that have been read by the
101100
method "getAllNodes()" [read].
102101
@@ -141,7 +140,7 @@ class ListNode(Model):
141140
_name: Optional[str]
142141
_parent: Optional[str]
143142
_isRootNode: bool
144-
_children: Optional[List['ListNode']]
143+
_children: Optional[list['ListNode']]
145144
_rootNodeIri: Optional[str]
146145

147146
def __init__(self,
@@ -153,7 +152,7 @@ def __init__(self,
153152
name: Optional[str] = None,
154153
parent: Optional[Union['ListNode', str]] = None,
155154
isRootNode: bool = False,
156-
children: Optional[List['ListNode']] = None,
155+
children: Optional[list['ListNode']] = None,
157156
rootNodeIri: Optional[str] = None):
158157
"""
159158
This is the constructor for the ListNode object. For
@@ -312,18 +311,18 @@ def isRootNode(self, value: bool) -> None:
312311
raise BaseError('Property isRootNode cannot be set!')
313312

314313
@property
315-
def children(self) -> Optional[List['ListNode']]:
314+
def children(self) -> Optional[list['ListNode']]:
316315
return self._children
317316

318317
@children.setter
319-
def children(self, value: List['ListNode']) -> None:
318+
def children(self, value: list['ListNode']) -> None:
320319
self._children = value
321320

322321
@staticmethod
323322
def __getChildren(con: Connection,
324323
parent_iri: str,
325324
project_iri: str,
326-
children: List[Any]) -> Optional[List['ListNode']]:
325+
children: list[Any]) -> Optional[list['ListNode']]:
327326
"""
328327
Internal method! Should not be used directly!
329328
@@ -334,7 +333,7 @@ def __getChildren(con: Connection,
334333
:return: List of ListNode instances
335334
"""
336335
if children:
337-
child_nodes: List[Any] = []
336+
child_nodes: list[Any] = []
338337
for child in children:
339338

340339
if 'parentNodeIri' not in child:
@@ -530,7 +529,7 @@ def getAllNodes(self) -> 'ListNode':
530529
return root
531530

532531
@staticmethod
533-
def getAllLists(con: Connection, project_iri: Optional[str] = None) -> List['ListNode']:
532+
def getAllLists(con: Connection, project_iri: Optional[str] = None) -> list['ListNode']:
534533
"""
535534
Get all lists. If a project IRI is given, it returns the lists of the specified project
536535
@@ -546,7 +545,7 @@ def getAllLists(con: Connection, project_iri: Optional[str] = None) -> List['Lis
546545
raise BaseError("Request got no lists!")
547546
return list(map(lambda a: ListNode.fromJsonObj(con, a), result['lists']))
548547

549-
def _createDefinitionFileObj(self, children: List["ListNode"]):
548+
def _createDefinitionFileObj(self, children: list["ListNode"]):
550549
"""
551550
Create an object that corresponds to the syntax of the input to "create_onto".
552551
Node: This method must be used only internally (for recursion)!!

‎knora/dsplib/models/model.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
from typing import Set
2-
31
from .connection import Connection
42
from .helpers import BaseError
53

64

75
class Model:
86
_con: Connection
9-
_changed: Set[str]
7+
_changed: set[str]
108

119
def __init__(self, con: Connection):
1210
if not isinstance(con, Connection):

0 commit comments

Comments
 (0)