mustrd 0.2.0__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mustrd/mustrdGraphDb.py CHANGED
@@ -1,125 +1,125 @@
1
- """
2
- MIT License
3
-
4
- Copyright (c) 2023 Semantic Partners Ltd
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
- """
24
-
25
- import urllib.parse
26
- import requests
27
- from rdflib import Graph, Literal
28
- from requests import ConnectionError, HTTPError, RequestException, Response
29
-
30
-
31
- # https://github.com/Semantic-partners/mustrd/issues/72
32
- def manage_graphdb_response(response: Response) -> str:
33
- content_string = response.content.decode("utf-8")
34
- if response.status_code == 200:
35
- return content_string
36
- elif response.status_code == 204:
37
- pass
38
- elif response.status_code == 401:
39
- raise HTTPError(f"GraphDB authentication error, status code: {response.status_code}, content: {content_string}")
40
- elif response.status_code == 406:
41
- raise HTTPError(f"GraphDB error, status code: {response.status_code}, content: {content_string}")
42
- else:
43
- raise RequestException(f"GraphDb error, status code: {response.status_code}, content: {content_string}")
44
-
45
-
46
- def upload_given(triple_store: dict, given: Graph):
47
- if given:
48
- try:
49
- graph = "default"
50
- if triple_store['input_graph']:
51
- graph = urllib.parse.urlencode({'graph': triple_store['input_graph']})
52
- url = f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}" \
53
- f"/rdf-graphs/service?{graph}"
54
- # graph store PUT drop silently the graph or default and upload the payload
55
- # https://www.w3.org/TR/sparql11-http-rdf-update/#http-put
56
- manage_graphdb_response(requests.put(url=url,
57
- auth=(triple_store['username'], triple_store['password']),
58
- data=given.serialize(format="ttl"),
59
- headers={'Content-Type': 'text/turtle'}))
60
- except ConnectionError:
61
- raise
62
-
63
-
64
- def parse_bindings(bindings: dict = None) -> dict:
65
- return None if not bindings else {f"${k}": str(v.n3()) for k, v in bindings.items()}
66
-
67
-
68
- def execute_select(triple_store: dict, when: str, bindings: dict = None) -> str:
69
- return post_query(triple_store, when, "application/sparql-results+json", parse_bindings(bindings))
70
-
71
-
72
- def execute_construct(triple_store: dict, when: str, bindings: dict = None) -> Graph:
73
- return Graph().parse(data=post_query(triple_store, when, "text/turtle", parse_bindings(bindings)))
74
-
75
-
76
- def execute_update(triple_store: dict, when: str, bindings: dict = None) -> Graph:
77
- post_update_query(triple_store, when, parse_bindings(bindings))
78
- return Graph().parse(data=post_query(triple_store, "CONSTRUCT {?s ?p ?o} where { ?s ?p ?o }", 'text/turtle'))
79
-
80
-
81
- def post_update_query(triple_store: dict, query: str, params: dict = None) -> str:
82
- params = add_graph_to_params(params, triple_store["input_graph"])
83
- try:
84
- return manage_graphdb_response(requests.post(
85
- url=f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}/statements",
86
- data=query,
87
- params=params,
88
- auth=(triple_store['username'], triple_store['password']),
89
- headers={'Content-Type': 'application/sparql-update'}))
90
- except (ConnectionError, OSError):
91
- raise
92
-
93
-
94
- def post_query(triple_store: dict, query: str, accept: str, params: dict = None) -> str:
95
- headers = {
96
- 'Content-Type': 'application/sparql-query',
97
- 'Accept': accept
98
- }
99
- params = add_graph_to_params(params, triple_store["input_graph"])
100
- try:
101
- return manage_graphdb_response(
102
- requests.post(url=f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}",
103
- data=query,
104
- params=params,
105
- auth=(triple_store['username'], triple_store['password']),
106
- headers=headers))
107
- except (ConnectionError, OSError):
108
- raise
109
-
110
-
111
- def add_graph_to_params(params: dict, graph: Literal) -> dict:
112
- graph = graph or "http://rdf4j.org/schema/rdf4j#nil"
113
- if params:
114
- params['default-graph-uri'] = graph
115
- params['using-graph-uri'] = graph
116
- params['remove-graph-uri'] = graph
117
- params['insert-graph-uri'] = graph
118
- else:
119
- params = {
120
- 'default-graph-uri': graph,
121
- 'using-graph-uri': graph,
122
- 'remove-graph-uri': graph,
123
- 'insert-graph-uri': graph
124
- }
125
- return params
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2023 Semantic Partners Ltd
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ """
24
+
25
+ import urllib.parse
26
+ import requests
27
+ from rdflib import Graph, Literal
28
+ from requests import ConnectionError, HTTPError, RequestException, Response
29
+
30
+
31
+ # https://github.com/Semantic-partners/mustrd/issues/72
32
+ def manage_graphdb_response(response: Response) -> str:
33
+ content_string = response.content.decode("utf-8")
34
+ if response.status_code == 200:
35
+ return content_string
36
+ elif response.status_code == 204:
37
+ pass
38
+ elif response.status_code == 401:
39
+ raise HTTPError(f"GraphDB authentication error, status code: {response.status_code}, content: {content_string}")
40
+ elif response.status_code == 406:
41
+ raise HTTPError(f"GraphDB error, status code: {response.status_code}, content: {content_string}")
42
+ else:
43
+ raise RequestException(f"GraphDb error, status code: {response.status_code}, content: {content_string}")
44
+
45
+
46
+ def upload_given(triple_store: dict, given: Graph):
47
+ if given:
48
+ try:
49
+ graph = "default"
50
+ if triple_store['input_graph']:
51
+ graph = urllib.parse.urlencode({'graph': triple_store['input_graph']})
52
+ url = f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}" \
53
+ f"/rdf-graphs/service?{graph}"
54
+ # graph store PUT drop silently the graph or default and upload the payload
55
+ # https://www.w3.org/TR/sparql11-http-rdf-update/#http-put
56
+ manage_graphdb_response(requests.put(url=url,
57
+ auth=(triple_store['username'], triple_store['password']),
58
+ data=given.serialize(format="ttl"),
59
+ headers={'Content-Type': 'text/turtle'}))
60
+ except ConnectionError:
61
+ raise
62
+
63
+
64
+ def parse_bindings(bindings: dict = None) -> dict:
65
+ return None if not bindings else {f"${k}": str(v.n3()) for k, v in bindings.items()}
66
+
67
+
68
+ def execute_select(triple_store: dict, when: str, bindings: dict = None) -> str:
69
+ return post_query(triple_store, when, "application/sparql-results+json", parse_bindings(bindings))
70
+
71
+
72
+ def execute_construct(triple_store: dict, when: str, bindings: dict = None) -> Graph:
73
+ return Graph().parse(data=post_query(triple_store, when, "text/turtle", parse_bindings(bindings)))
74
+
75
+
76
+ def execute_update(triple_store: dict, when: str, bindings: dict = None) -> Graph:
77
+ post_update_query(triple_store, when, parse_bindings(bindings))
78
+ return Graph().parse(data=post_query(triple_store, "CONSTRUCT {?s ?p ?o} where { ?s ?p ?o }", 'text/turtle'))
79
+
80
+
81
+ def post_update_query(triple_store: dict, query: str, params: dict = None) -> str:
82
+ params = add_graph_to_params(params, triple_store["input_graph"])
83
+ try:
84
+ return manage_graphdb_response(requests.post(
85
+ url=f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}/statements",
86
+ data=query,
87
+ params=params,
88
+ auth=(triple_store['username'], triple_store['password']),
89
+ headers={'Content-Type': 'application/sparql-update'}))
90
+ except (ConnectionError, OSError):
91
+ raise
92
+
93
+
94
+ def post_query(triple_store: dict, query: str, accept: str, params: dict = None) -> str:
95
+ headers = {
96
+ 'Content-Type': 'application/sparql-query',
97
+ 'Accept': accept
98
+ }
99
+ params = add_graph_to_params(params, triple_store["input_graph"])
100
+ try:
101
+ return manage_graphdb_response(
102
+ requests.post(url=f"{triple_store['url']}:{triple_store['port']}/repositories/{triple_store['repository']}",
103
+ data=query,
104
+ params=params,
105
+ auth=(triple_store['username'], triple_store['password']),
106
+ headers=headers))
107
+ except (ConnectionError, OSError):
108
+ raise
109
+
110
+
111
+ def add_graph_to_params(params: dict, graph: Literal) -> dict:
112
+ graph = graph or "http://rdf4j.org/schema/rdf4j#nil"
113
+ if params:
114
+ params['default-graph-uri'] = graph
115
+ params['using-graph-uri'] = graph
116
+ params['remove-graph-uri'] = graph
117
+ params['insert-graph-uri'] = graph
118
+ else:
119
+ params = {
120
+ 'default-graph-uri': graph,
121
+ 'using-graph-uri': graph,
122
+ 'remove-graph-uri': graph,
123
+ 'insert-graph-uri': graph
124
+ }
125
+ return params
mustrd/mustrdRdfLib.py CHANGED
@@ -1,56 +1,56 @@
1
- """
2
- MIT License
3
-
4
- Copyright (c) 2023 Semantic Partners Ltd
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
23
- """
24
-
25
- from pyparsing import ParseException
26
- from rdflib import Graph
27
- from requests import RequestException
28
-
29
-
30
- def execute_select(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> str:
31
- try:
32
- return given.query(when, initBindings=bindings).serialize(format="json").decode("utf-8")
33
- except ParseException:
34
- raise
35
- except Exception as e:
36
- raise RequestException(e)
37
-
38
-
39
- def execute_construct(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> Graph:
40
- try:
41
- return given.query(when, initBindings=bindings).graph
42
- except ParseException:
43
- raise
44
- except Exception as e:
45
- raise RequestException(e)
46
-
47
-
48
- def execute_update(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> Graph:
49
- try:
50
- result = given
51
- result.update(when, initBindings=bindings)
52
- return result
53
- except ParseException:
54
- raise
55
- except Exception as e:
56
- raise RequestException(e)
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2023 Semantic Partners Ltd
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ """
24
+
25
+ from pyparsing import ParseException
26
+ from rdflib import Graph
27
+ from requests import RequestException
28
+
29
+
30
+ def execute_select(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> str:
31
+ try:
32
+ return given.query(when, initBindings=bindings).serialize(format="json").decode("utf-8")
33
+ except ParseException:
34
+ raise
35
+ except Exception as e:
36
+ raise RequestException(e)
37
+
38
+
39
+ def execute_construct(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> Graph:
40
+ try:
41
+ return given.query(when, initBindings=bindings).graph
42
+ except ParseException:
43
+ raise
44
+ except Exception as e:
45
+ raise RequestException(e)
46
+
47
+
48
+ def execute_update(triple_store: dict, given: Graph, when: str, bindings: dict = None) -> Graph:
49
+ try:
50
+ result = given
51
+ result.update(when, initBindings=bindings)
52
+ return result
53
+ except ParseException:
54
+ raise
55
+ except Exception as e:
56
+ raise RequestException(e)