Skip to content

Commit

Permalink
chore: lint "models", part two (DEV-2287) (#406)
Browse files Browse the repository at this point in the history
  • Loading branch information
jnussbaum committed Jun 16, 2023
1 parent 1afd8cf commit 466597c
Show file tree
Hide file tree
Showing 25 changed files with 271 additions and 399 deletions.
8 changes: 1 addition & 7 deletions src/dsp_tools/models/group.py
Expand Up @@ -94,7 +94,7 @@ def __init__(
self._name = str(name) if name is not None else None
self._descriptions = LangString(descriptions)
if project is not None and isinstance(project, Project):
self._project = project.id
self._project = project.iri
else:
self._project = str(project) if project is not None else None
self._selfjoin = bool(selfjoin) if selfjoin is not None else None
Expand Down Expand Up @@ -152,12 +152,6 @@ def status(self, value: bool) -> None:
self._status = value
self._changed.add("status")

def has_changed(self) -> bool:
if self._changed:
return True
else:
return False

@classmethod
def fromJsonObj(cls, con: Connection, json_obj: Any):
group_id = json_obj.get("id")
Expand Down
8 changes: 1 addition & 7 deletions src/dsp_tools/models/listnode.py
Expand Up @@ -181,7 +181,7 @@ def __init__(

super().__init__(con)

self._project = project.id if isinstance(project, Project) else str(project) if project else None
self._project = project.iri if isinstance(project, Project) else str(project) if project else None
self._id = iri
self._label = LangString(label)
self._comments = LangString(comments) if comments else None
Expand Down Expand Up @@ -356,12 +356,6 @@ def rootNodeIri(self) -> Optional[str]:
def rootNodeIri(self, value: str):
raise BaseError("rootNodeIri cannot be set!")

def has_changed(self) -> bool:
if self._changed:
return True
else:
return False

@classmethod
def fromJsonObj(cls, con: Connection, json_obj: Any) -> Any:
"""
Expand Down
6 changes: 0 additions & 6 deletions src/dsp_tools/models/model.py
Expand Up @@ -11,9 +11,3 @@ def __init__(self, con: Connection):
raise BaseError('"con"-parameter must be an instance of Connection')
self._con = con
self._changed = set()

def has_changed(self) -> bool:
if self._changed:
return True
else:
return False
2 changes: 1 addition & 1 deletion src/dsp_tools/models/ontology.py
Expand Up @@ -73,7 +73,7 @@ def __init__(
super().__init__(con)
self._iri = iri
if isinstance(project, Project):
self._project = project.id
self._project = project.iri
else:
self._project = project
self._name = name
Expand Down
23 changes: 0 additions & 23 deletions src/dsp_tools/models/permission.py
Expand Up @@ -22,26 +22,6 @@ def __str__(self):
return tmp[self.value]


class PermissionsIterator:
_permissions: "Permissions"
_group: list[str]
_index: int

def __init__(self, permissions: "Permissions"):
self._permissions = permissions
self._index = 0

def __next__(self):
if len(self._permissions.permissions) == 0 and self._index == 0:
return None, None
elif self._index < len(self._permissions.permissions):
tmp = self._prefixes[self._index]
self._index += 1
return tmp, self._permissions.permissions[tmp]
else:
raise StopIteration


class Permissions:
_permissions: Union[dict[PermissionValue, list[str]], None]

Expand All @@ -63,9 +43,6 @@ def __delitem__(self, key: PermissionValue) -> None:
def __missing__(self, key: PermissionValue) -> None:
return None

def __iter__(self) -> PermissionsIterator:
return PermissionsIterator(self)

def __contains__(self, key: PermissionValue) -> bool:
return key in self._permissions

Expand Down
114 changes: 39 additions & 75 deletions src/dsp_tools/models/project.py
@@ -1,17 +1,3 @@
from __future__ import annotations

import json
from pprint import pprint
from typing import Any, Optional, Union
from urllib.parse import quote_plus

from dsp_tools.models.connection import Connection
from dsp_tools.models.exceptions import BaseError
from dsp_tools.models.helpers import Actions
from dsp_tools.models.langstring import LangString, Languages
from dsp_tools.models.model import Model
from dsp_tools.models.set_encoder import SetEncoder

"""
This module implements the handling (CRUD) of DSP projects.
Expand All @@ -20,7 +6,7 @@
* Call the ``create``-method on the instance
READ:
* Instantiate a new object with ``id``(IRI of project) given
* Instantiate a new object with ``iri`` given
* Call the ``read``-method on the instance
* Access the information that has been provided to the instance
Expand All @@ -30,12 +16,25 @@
* Call the ``update```method on the instance
DELETE
* Instantiate a new objects with ``id``(IRI of project) given, or use any instance that has the id set
* Instantiate a new objects with ``iri`` given, or use any instance that has the iri set
* Call the ``delete``-method on the instance
In addition there is a static methods ``getAllProjects`` which returns a list of all projects
"""

from __future__ import annotations

import json
from typing import Any, Optional, Union
from urllib.parse import quote_plus

from dsp_tools.models.connection import Connection
from dsp_tools.models.exceptions import BaseError
from dsp_tools.models.helpers import Actions
from dsp_tools.models.langstring import LangString, Languages
from dsp_tools.models.model import Model
from dsp_tools.models.set_encoder import SetEncoder


class Project(Model):
"""
Expand All @@ -47,7 +46,7 @@ class Project(Model):
con : Connection
A Connection instance to a DSP server
id : str
iri : str
IRI of the project [readonly, cannot be modified after creation of instance]
shortcode : str
Expand Down Expand Up @@ -100,7 +99,7 @@ class Project(Model):
ROUTE: str = "/admin/projects"
IRI: str = ROUTE + "/iri/"

_id: str
_iri: str
_shortcode: str
_shortname: str
_longname: str
Expand All @@ -116,7 +115,7 @@ class Project(Model):
def __init__(
self,
con: Connection,
id: Optional[str] = None,
iri: Optional[str] = None,
shortcode: Optional[str] = None,
shortname: Optional[str] = None,
longname: Optional[str] = None,
Expand All @@ -131,8 +130,8 @@ def __init__(
Constructor for Project
:param con: Connection instance
:param id: IRI of the project [required for CREATE, READ]
:param shortcode: Shortcode of the project. String inf the form 'XXXX' where each X is a hexadezimal sign 0-1,A,B,C,D,E,F. [required for CREATE]
:param iri: IRI of the project [required for CREATE, READ]
:param shortcode: Shortcode of the project. Four-digit hexadecimal number. [required for CREATE]
:param shortname: Shortname of the project [required for CREATE]
:param longname: Longname of the project [required for CREATE]
:param description: LangString instance containing the description [required for CREATE]
Expand All @@ -143,7 +142,7 @@ def __init__(
:param logo: Path to logo image file [optional] NOT YET USED
"""
super().__init__(con)
self._id = id
self._iri = iri
self._shortcode = shortcode
self._shortname = shortname
self._longname = longname
Expand All @@ -157,19 +156,19 @@ def __init__(
self._logo = logo

def __str__(self):
tmpstr = self._id + "\n " + self._shortcode + "\n " + self._shortname
tmpstr = self._iri + "\n " + self._shortcode + "\n " + self._shortname
return tmpstr

#
# Here follows a list of getters/setters
#
@property
def id(self) -> Optional[str]:
return self._id
def iri(self) -> Optional[str]:
return self._iri

@id.setter
def id(self, value: str) -> None:
raise BaseError("Project id cannot be modified!")
@iri.setter
def iri(self, value: str) -> None:
raise BaseError("Project iri cannot be modified!")

@property
def shortcode(self) -> Optional[str]:
Expand Down Expand Up @@ -224,7 +223,7 @@ def rmDescription(self, lang: Union[Languages, str]) -> None:
"""
Remove a description from a project (executed at next update)
:param lang: The language the description to be removed is in, either a string "EN", "DE", "FR", "IT" or a Language instance
:param lang: language of the description, either "EN", "DE", "FR", "IT", "RM", or a Language instance
:return: None
"""

Expand Down Expand Up @@ -269,7 +268,7 @@ def rmKeyword(self, value: str):
try:
self._keywords.remove(value)
except KeyError as ke:
raise BaseError('Keyword "' + value + '" is not in keyword set')
raise BaseError('Keyword "' + value + '" is not in keyword set') from ke
self._changed.add("keywords")

@property
Expand Down Expand Up @@ -321,9 +320,9 @@ def fromJsonObj(cls, con: Connection, json_obj: Any) -> Project:
:param json_obj: JSON data returned by DSP as python3 object
:return: Project instance
"""
id = json_obj.get("id")
if id is None:
raise BaseError("Project id is missing")
iri = json_obj.get("id")
if iri is None:
raise BaseError("Project iri is missing")
shortcode = json_obj.get("shortcode")
if shortcode is None:
raise BaseError("Shortcode is missing")
Expand All @@ -349,7 +348,7 @@ def fromJsonObj(cls, con: Connection, json_obj: Any) -> Project:
logo = json_obj.get("logo")
return cls(
con=con,
id=id,
iri=iri,
shortcode=shortcode,
shortname=shortname,
longname=longname,
Expand Down Expand Up @@ -439,8 +438,8 @@ def read(self) -> Project:
:return: JSON-object from DSP
"""
result = None
if self._id is not None:
result = self._con.get(Project.IRI + quote_plus(self._id))
if self._iri is not None:
result = self._con.get(Project.IRI + quote_plus(self._iri))
elif self._shortcode is not None:
result = self._con.get(Project.ROUTE + "/shortcode/" + quote_plus(self._shortcode))
elif self._shortname is not None:
Expand All @@ -449,7 +448,7 @@ def read(self) -> Project:
return Project.fromJsonObj(self._con, result["project"])
else:
raise BaseError(
f"ERROR: Could not read project '{self.shortname}' ({self.shortcode}) with IRI {self._id} "
f"ERROR: Could not read project '{self.shortname}' ({self.shortcode}) with IRI {self._iri} "
f"from DSP server."
)

Expand All @@ -462,7 +461,7 @@ def update(self) -> Project:

jsonobj = self.toJsonObj(Actions.Update)
jsondata = json.dumps(jsonobj, cls=SetEncoder)
result = self._con.put(Project.IRI + quote_plus(self.id), jsondata)
result = self._con.put(Project.IRI + quote_plus(self.iri), jsondata)
return Project.fromJsonObj(self._con, result["project"])

def delete(self) -> Project:
Expand All @@ -472,44 +471,9 @@ def delete(self) -> Project:
:return: DSP response
"""

result = self._con.delete(Project.IRI + quote_plus(self._id))
result = self._con.delete(Project.IRI + quote_plus(self._iri))
return Project.fromJsonObj(self._con, result["project"])

def set_default_permissions(self, group_id: str) -> None:
permobj = {
"forGroup": "http://www.knora.org/ontology/knora-admin#ProjectMember",
"forProject": self._id,
"hasPermissions": [
{
"additionalInformation": None,
"name": "ProjectResourceCreateAllPermission",
"permissionCode": None,
}
],
}
jsondata = json.dumps(permobj, indent=4)
print(jsondata)
result = self._con.post("/admin/permissions/ap", jsondata)
pprint(result)

return
permobj = {
"forGroup": group_id,
"forProject": self._id,
"forProperty": None,
"forResourceClass": None,
"hasPermissions": [
{
"additionalInformation": "http://www.knora.org/ontology/knora-admin#ProjectMember",
"name": "D",
"permissionCode": 7,
}
],
}
jsondata = json.dumps(permobj)
result = self._con.post("/admin/permissions/ap", jsondata)
pprint(result)

@staticmethod
def getAllProjects(con: Connection) -> list[Project]:
"""
Expand All @@ -531,7 +495,7 @@ def print(self) -> None:
"""

print("Project Info:")
print(" Id: {}".format(self._id))
print(" IRI: {}".format(self._iri))
print(" Shortcode: {}".format(self._shortcode))
print(" Shortname: {}".format(self._shortname))
print(" Longname: {}".format(self._longname))
Expand Down
4 changes: 2 additions & 2 deletions src/dsp_tools/models/projectContext.py
Expand Up @@ -20,8 +20,8 @@ class ProjectContext:
def __init__(self, con: Connection, shortcode: Optional[str] = None):
self._shortcode = shortcode
self._projects = Project.getAllProjects(con=con)
self._project_map: dict[str, str] = {x.shortname: x.id for x in self._projects}
self._inv_project_map: dict[str, str] = {x.id: x.shortname for x in self._projects}
self._project_map: dict[str, str] = {x.shortname: x.iri for x in self._projects}
self._inv_project_map: dict[str, str] = {x.iri: x.shortname for x in self._projects}
try:
self._groups = Group.getAllGroups(con=con)
except BaseError:
Expand Down

0 comments on commit 466597c

Please sign in to comment.