-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathClient.py
3087 lines (2684 loc) · 95.5 KB
/
Client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Client.py
Client is the Python public API for TerminusDB"""
import base64
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import requests
from ..__version__ import __version__
from ..errors import DatabaseError, InterfaceError
from ..woql_utils import (
_clean_dict,
_dt_dict,
_dt_list,
_finish_response,
_result2stream,
_args_as_payload,
)
from ..woqlquery.woql_query import WOQLQuery
# client object
# license Apache Version 2
# summary Python module for accessing the Terminus DB API
class WoqlResult:
"""Iterator for streaming WOQL results."""
def __init__(self, lines):
preface = json.loads(next(lines))
if not ('@type' in preface and preface['@type'] == 'PrefaceRecord'):
raise DatabaseError(response=preface)
self.preface = preface
self.postscript = {}
self.lines = lines
def _check_error(self, document):
if ('@type' in document):
if document['@type'] == 'Binding':
return document
if document['@type'] == 'PostscriptRecord':
self.postscript = document
raise StopIteration()
raise DatabaseError(response=document)
def variable_names(self):
return self.preface['names']
def __iter__(self):
return self
def __next__(self):
return self._check_error(json.loads(next(self.lines)))
class JWTAuth(requests.auth.AuthBase):
"""Class for JWT Authentication in requests"""
def __init__(self, token):
self._token = token
def __call__(self, r):
r.headers["Authorization"] = f"Bearer {self._token}"
return r
class APITokenAuth(requests.auth.AuthBase):
"""Class for API Token Authentication in requests"""
def __init__(self, token):
self._token = token
def __call__(self, r):
r.headers["Authorization"] = f"Token {self._token}"
return r
class Patch:
def __init__(self, json=None):
if json:
self.from_json(json)
else:
self.content = None
@property
def update(self):
def swap_value(swap_item):
result_dict = {}
for key, item in swap_item.items():
if isinstance(item, dict):
operation = item.get("@op")
if operation is not None and operation == "SwapValue":
result_dict[key] = item.get("@after")
elif operation is None:
result_dict[key] = swap_value(item)
return result_dict
return swap_value(self.content)
@update.setter
def update(self):
raise Exception("Cannot set update for patch")
@update.deleter
def update(self):
raise Exception("Cannot delete update for patch")
@property
def before(self):
def extract_before(extract_item):
before_dict = {}
for key, item in extract_item.items():
if isinstance(item, dict):
value = item.get("@before")
if value is not None:
before_dict[key] = value
else:
before_dict[key] = extract_before(item)
else:
before_dict[key] = item
return before_dict
return extract_before(self.content)
@before.setter
def before(self):
raise Exception("Cannot set before for patch")
@before.deleter
def before(self):
raise Exception("Cannot delete before for patch")
def from_json(self, json_str):
content = json.loads(json_str)
if isinstance(content, dict):
self.content = _dt_dict(content)
else:
self.content = _dt_list(content)
def to_json(self):
return json.dumps(_clean_dict(self.content))
def copy(self):
return copy.deepcopy(self)
class GraphType(str, Enum):
"""Type of graph"""
INSTANCE = 'instance'
SCHEMA = 'schema'
class Client:
"""Client for TerminusDB server.
Attributes
----------
server_url : str
URL of the server that this client connected.
api : str
API endpoint for this client.
team : str
Team that this client is using. "admin" for local dbs.
db : str
Database that this client is connected to.
user : str
TerminiusDB user that this client is using. "admin" for local dbs.
branch : str
Branch of the database that this client is connected to. Default to "main".
ref : str, None
Ref setting for the client. Default to None.
repo : str
Repo identifier of the database that this client is connected to. Default to "local".
"""
def from_json(self, json_str):
content = json.loads(json_str)
if isinstance(content, dict):
self.content = _dt_dict(content)
else:
self.content = _dt_list(content)
def to_json(self):
return json.dumps(_clean_dict(self.content))
def __init__(
self,
server_url: str,
user_agent: str = f"terminusdb-client-python/{__version__}",
**kwargs,
) -> None:
r"""The Client constructor.
Parameters
----------
server_url : str
URL of the server that this client will connect to.
user_agent : optional, str
User agent header when making requests. Defaults to terminusdb-client-python with the version appended.
**kwargs
Extra configuration options
"""
self.server_url = server_url.strip("/")
self.api = f"{self.server_url}/api"
self._connected = False
# properties with get/setters
self._team = None
self._db = None
self._user = None
self._branch = None
self._ref = None
self._repo = None
self._references = {}
# Default headers
self._default_headers = {"user-agent": user_agent}
@property
def team(self):
if isinstance(self._team, str):
return urlparse.unquote(self._team)
else:
return self._team
@team.setter
def team(self, value):
if isinstance(value, str):
self._team = urlparse.quote(value)
else:
self._team = value
@property
def db(self):
if isinstance(self._db, str):
return urlparse.unquote(self._db)
else:
return self._db
@db.setter
def db(self, value):
if isinstance(value, str):
self._db = urlparse.quote(value)
else:
self._db = value
@property
def user(self):
if isinstance(self._user, str):
return urlparse.unquote(self._user)
else:
return self._user
@user.setter
def user(self, value):
if isinstance(value, str):
self._user = urlparse.quote(value)
else:
self._user = value
@property
def branch(self):
if isinstance(self._branch, str):
return urlparse.unquote(self._branch)
else:
return self._branch
@branch.setter
def branch(self, value):
if isinstance(value, str):
self._branch = urlparse.quote(value)
else:
self._branch = value
@property
def repo(self):
if isinstance(self._repo, str):
return urlparse.unquote(self._repo)
else:
self._repo
@repo.setter
def repo(self, value):
if isinstance(value, str):
self._repo = urlparse.quote(value)
else:
self._repo = value
@property
def ref(self):
return self._ref
@ref.setter
def ref(self, value: Optional[str]):
if value is not None:
value = value.lower()
self._ref = value
def connect(
self,
team: str = "admin",
db: Optional[str] = None,
remote_auth: Optional[dict] = None,
use_token: bool = False,
jwt_token: Optional[str] = None,
api_token: Optional[str] = None,
key: str = "root",
user: str = "admin",
branch: str = "main",
ref: Optional[str] = None,
repo: str = "local",
**kwargs,
) -> None:
r"""Connect to a Terminus server at the given URI with an API key.
Stores the connection settings and necessary meta-data for the connected server. You need to connect before most database operations.
Parameters
----------
team : str
Name of the team, default to be "admin"
db : optional, str
Name of the database connected
remote_auth : optional, dict
Remote Auth setting
key : optional, str
API key for connecting, default to be "root"
user : optional, str
Name of the user, default to be "admin"
use_token : bool
Use token to connect. If both `jwt_token` and `api_token` is not provided (None), then it will use the ENV variable TERMINUSDB_ACCESS_TOKEN to connect as the API token
jwt_token : optional, str
The Bearer JWT token to connect. Default to be None.
api_token : optional, strs
The API token to connect. Default to be None.
branch : optional, str
Branch to be connected, default to be "main"
ref : optional, str
Ref setting
repo : optional, str
Local or remote repo, default to be "local"
**kwargs
Extra configuration options.
Examples
--------
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
"""
self.team = team
self.db = db
self._remote_auth_dict = remote_auth
self._key = key
self.user = user
if api_token:
self._use_token = True
else:
self._use_token = use_token
self._jwt_token = jwt_token
self._api_token = api_token
self.branch = branch
self.ref = ref
self.repo = repo
self._session = requests.Session()
self._connected = True
try:
self._db_info = self.info()
except Exception as error:
raise InterfaceError(
f"Cannot connect to server, please make sure TerminusDB is running at {self.server_url} and the authentication details are correct. Details: {str(error)}"
) from None
if self.db is not None:
try:
_finish_response(
self._session.head(
self._db_url(),
headers=self._default_headers,
params={"exists": "true"},
auth=self._auth(),
)
)
except DatabaseError:
raise InterfaceError(f"Connection fail, {self.db} does not exist.")
self._author = self.user
def close(self) -> None:
"""Undo connect and close the connection.
The connection will be unusable from this point forward; an Error (or subclass) exception will be raised if any operation is attempted with the connection, unless connect is call again."""
self._connected = False
def _check_connection(self, check_db=True) -> None:
"""Raise connection InterfaceError if not connected
Defaults to check if a db is connected"""
if not self._connected:
raise InterfaceError("Client is not connected to a TerminusDB server.")
if check_db and self.db is None:
raise InterfaceError(
"No database is connected. Please either connect to a database or create a new database."
)
def info(self) -> dict:
"""Get info of a TerminusDB database server
Returns
-------
dict
Dict with version information:
```
{
"@type": "api:InfoResponse",
"api:info": {
"authority": "anonymous",
"storage": {
"version": "1"
},
"terminusdb": {
"git_hash": "53acb38f9aedeec6c524f5679965488788e6ccf5",
"version": "10.1.5"
},
"terminusdb_store": {
"version": "0.19.8"
}
},
"api:status": "api:success"
}
```
"""
return json.loads(
_finish_response(
self._session.get(
self.api + "/info",
headers=self._default_headers,
auth=self._auth(),
)
)
)
def ok(self) -> bool:
"""Check whether the TerminusDB server is still OK.
Status is not OK when this function returns false
or throws an exception (mostly ConnectTimeout)
Raises
------
Exception
When a connection can't be made by the requests library
Returns
-------
bool
"""
if not self._connected:
return self._connected
req = self._session.get(
self.api + "/ok",
headers=self._default_headers,
timeout=6
)
return req.status_code == 200
def log(self,
team: Optional[str] = None,
db: Optional[str] = None,
start: int = 0,
count: int = -1):
"""Get commit history of a database
Parameters
----------
team : str, optional
The team from which the database is. Defaults to the class property.
db : str, optional
The database. Defaults to the class property.
start : int, optional
Commit index to start from. Defaults to 0.
count : int, optional
Amount of commits to get. Defaults to -1 which gets all.
Returns
-------
list
List of the following commit objects:
```
{
"@id":"InitialCommit/hpl18q42dbnab4vzq8me4bg1xn8p2a0",
"@type":"InitialCommit",
"author":"system",
"identifier":"hpl18q42dbnab4vzq8me4bg1xn8p2a0",
"message":"create initial schema",
"schema":"layer_data:Layer_4234adfe377fa9563a17ad764ac37f5dcb14de13668ea725ef0748248229a91b",
"timestamp":1660919664.9129035
}
```
"""
self._check_connection(check_db=(not team or not db))
team = team if team else self.team
db = db if db else self.db
result = self._session.get(
f"{self.api}/log/{team}/{db}",
params={'start': start, 'count': count},
headers=self._default_headers,
auth=self._auth(),
)
commits = json.loads(_finish_response(result))
for commit in commits:
commit['timestamp'] = datetime.fromtimestamp(commit['timestamp'])
commit['commit'] = commit['identifier'] # For backwards compat.
return commits
def get_commit_history(self, max_history: int = 500) -> list:
"""Get the whole commit history.
Commit history - Commit id, author of the commit, commit message and the commit time, in the current branch from the current commit, ordered backwards in time, will be returned in a dictionary in the follow format:
```
{ "commit_id":
{ "author": "commit_author",
"message": "commit_message",
"timestamp: <datetime object of the timestamp>"
}
}
```
Parameters
----------
max_history : int, optional
maximum number of commit that would return, counting backwards from your current commit. Default is set to 500. It needs to be nop-negative, if input is 0 it will still give the last commit.
Example
-------
>>> from terminusdb_client import Client
>>> client = Client("http://127.0.0.1:6363"
>>> client.connect(db="bank_balance_example")
>>> client.get_commit_history()
[{'commit': 's90wike9v5xibmrb661emxjs8k7ynwc', 'author': 'admin', 'message': 'Adding Jane', 'timestamp': datetime.da
tetime(2020, 9, 3, 15, 29, 34)}, {'commit': '1qhge8qlodajx93ovj67kvkrkxsw3pg', 'author': '[email protected]', 'm
essage': 'Adding Jim', 'timestamp': datetime.datetime(2020, 9, 3, 15, 29, 33)}, {'commit': 'rciy1rfu5foj67ch00ow6f6n
njjxe3i', 'author': '[email protected]', 'message': 'Update mike', 'timestamp': datetime.datetime(2020, 9, 3, 15,
29, 33)}, {'commit': 'n4d86u8juzx852r2ekrega5hl838ovh', 'author': '[email protected]', 'message': 'Add mike', '
timestamp': datetime.datetime(2020, 9, 3, 15, 29, 33)}, {'commit': '1vk2i8k8xce26p9jpi4zmq1h5vdqyuj', 'author': 'gav
[email protected]', 'message': 'Label for balance was wrong', 'timestamp': datetime.datetime(2020, 9, 3, 15, 29, 33)
}, {'commit': '9si4na9zv2qol9b189y92fia7ac3hbg', 'author': '[email protected]', 'message': 'Adding bank account
object to schema', 'timestamp': datetime.datetime(2020, 9, 3, 15, 29, 33)}, {'commit': '9egc4h0m36l5rbq1alr1fki6jbfu
kuv', 'author': 'TerminusDB', 'message': 'internal system operation', 'timstamp': datetime.datetime(2020, 9, 3, 15,
29, 33)}]
Returns
-------
list
"""
if max_history < 0:
raise ValueError("max_history needs to be non-negative.")
return self.log(count=max_history)
def _get_current_commit(self):
descriptor = self.db
if self.branch:
descriptor = f'{descriptor}/local/branch/{self.branch}'
commit = self.log(team=self.team, db=descriptor, count=1)[0]
return commit['identifier']
def _get_target_commit(self, step):
descriptor = self.db
if self.branch:
descriptor = f'{descriptor}/local/branch/{self.branch}'
commit = self.log(team=self.team, db=descriptor, count=1, start=step)[0]
return commit['identifier']
def get_all_branches(self, get_data_version=False):
"""Get all the branches available in the database."""
self._check_connection()
api_url = self._documents_url().split("/")
api_url = api_url[:-2]
api_url = "/".join(api_url) + "/_commits"
result = self._session.get(
api_url,
headers=self._default_headers,
params={"type": "Branch"},
auth=self._auth(),
)
if get_data_version:
result, version = _finish_response(result, get_data_version)
return list(_result2stream(result)), version
return list(_result2stream(_finish_response(result)))
def rollback(self, steps=1) -> None:
"""Curently not implementated. Please check back later.
Raises
----------
NotImplementedError
Since TerminusDB currently does not support open transactions. This method is not applicable to it's usage. To reset commit head, use Client.reset
"""
raise NotImplementedError(
"Open transactions are currently not supported. To reset commit head, check Client.reset"
)
def copy(self) -> "Client":
"""Create a deep copy of this client.
Returns
-------
Client
The copied client instance.
Examples
--------
>>> client = Client("http://127.0.0.1:6363/")
>>> clone = client.copy()
>>> assert client is not clone
"""
return copy.deepcopy(self)
def set_db(self, dbid: str, team: Optional[str] = None) -> str:
"""Set the connection to another database. This will reset the connection.
Parameters
----------
dbid : str
Database identifer to set in the config.
team : str
Team identifer to set in the config. If not passed in, it will use the current one.
Returns
-------
str
The current database identifier.
Examples
--------
>>> client = Client("http://127.0.0.1:6363")
>>> client.set_db("database1")
'database1'
"""
self._check_connection(check_db=False)
if team is None:
team = self.team
return self.connect(
team=team,
db=dbid,
remote_auth=self._remote_auth_dict,
key=self._key,
user=self.user,
branch=self.branch,
ref=self.ref,
repo=self.repo,
)
def _get_prefixes(self):
"""Get the prefixes for a given database"""
self._check_connection()
result = self._session.get(
self._db_base("prefixes"),
headers=self._default_headers,
auth=self._auth(),
)
return json.loads(_finish_response(result))
def create_database(
self,
dbid: str,
team: Optional[str] = None,
label: Optional[str] = None,
description: Optional[str] = None,
prefixes: Optional[dict] = None,
include_schema: bool = True,
) -> None:
"""Create a TerminusDB database by posting
a terminus:Database document to the Terminus Server.
Parameters
----------
dbid : str
Unique identifier of the database.
team : str, optional
ID of the Team in which to create the DB (defaults to 'admin')
label : str, optional
Database name.
description : str, optional
Database description.
prefixes : dict, optional
Optional dict containing ``"@base"`` and ``"@schema"`` keys.
@base (str)
IRI to use when ``doc:`` prefixes are expanded. Defaults to ``terminusdb:///data``.
@schema (str)
IRI to use when ``scm:`` prefixes are expanded. Defaults to ``terminusdb:///schema``.
include_schema : bool
If ``True``, a main schema graph will be created, otherwise only a main instance graph will be created.
Raises
------
InterfaceError
if the client does not connect to a server
Examples
--------
>>> client = Client("http://127.0.0.1:6363/")
>>> client.create_database("someDB", "admin", "Database Label", "My Description")
"""
self._check_connection(check_db=False)
details: Dict[str, Any] = {}
if label:
details["label"] = label
else:
details["label"] = dbid
if description:
details["comment"] = description
else:
details["comment"] = ""
if include_schema:
details["schema"] = True
else:
details["schema"] = False
if prefixes:
details["prefixes"] = prefixes
if team is None:
team = self.team
self.team = team
self._connected = True
self.db = dbid
_finish_response(
self._session.post(
self._db_url(),
headers=self._default_headers,
json=details,
auth=self._auth(),
)
)
def delete_database(
self,
dbid: Optional[str] = None,
team: Optional[str] = None,
force: bool = False,
) -> None:
"""Delete a TerminusDB database.
If ``team`` is provided, then the team in the config will be updated
and the new value will be used in future requests to the server.
Parameters
----------
dbid : str
ID of the database to delete
team : str, optional
the team in which the database resides (defaults to "admin")
force : bool
Raises
------
UserWarning
If the value of dbid is None.
InterfaceError
if the client does not connect to a server.
Examples
--------
>>> client = Client("http://127.0.0.1:6363/")
>>> client.delete_database("<database>", "<team>")
"""
self._check_connection(check_db=False)
if dbid is None:
raise UserWarning(
f"You are currently using the database: {self.team}/{self.db}. If you want to delete it, please do 'delete_database({self.db},{self.team})' instead."
)
self.db = dbid
if team is None:
warnings.warn(
f"Delete Database Warning: You have not specify the team, assuming {self.team}/{self.db}",
stacklevel=2,
)
else:
self.team = team
payload = {}
if force:
payload["force"] = "true"
_finish_response(
self._session.delete(
self._db_url(),
headers=self._default_headers,
auth=self._auth(),
params=payload,
)
)
self.db = None
def get_triples(self, graph_type: GraphType) -> str:
"""Retrieves the contents of the specified graph as triples encoded in turtle format
Parameters
----------
graph_type : GraphType
Graph type, either GraphType.INSTANCE or GraphType.SCHEMA.
Raises
------
InterfaceError
if the client does not connect to a database
Returns
-------
str
"""
self._check_connection()
result = self._session.get(
self._triples_url(graph_type),
headers=self._default_headers,
auth=self._auth(),
)
return json.loads(_finish_response(result))
def update_triples(self, graph_type: GraphType, content: str, commit_msg: str) -> None:
"""Updates the contents of the specified graph with the triples encoded in turtle format.
Replaces the entire graph contents
Parameters
----------
graph_type : GraphType
Graph type, either GraphType.INSTANCE or GraphType.SCHEMA.
content
Valid set of triples in Turtle or Trig format.
commit_msg : str
Commit message.
Raises
------
InterfaceError
if the client does not connect to a database
"""
self._check_connection()
params = {"commit_info": self._generate_commit(commit_msg),
"turtle": content,
}
result = self._session.post(
self._triples_url(graph_type),
headers=self._default_headers,
json=params,
auth=self._auth(),
)
return json.loads(_finish_response(result))
def insert_triples(
self, graph_type: GraphType, content: str, commit_msg: Optional[str] = None
) -> None:
"""Inserts into the specified graph with the triples encoded in turtle format.
Parameters
----------
graph_type : GraphType
Graph type, either GraphType.INSTANCE or GraphType.SCHEMA.
content
Valid set of triples in Turtle or Trig format.
commit_msg : str
Commit message.
Raises
------
InterfaceError
if the client does not connect to a database
"""
self._check_connection()
params = {"commit_info": self._generate_commit(commit_msg),
"turtle": content
}
result = self._session.put(
self._triples_url(graph_type),
headers=self._default_headers,
json=params,
auth=self._auth(),
)
return json.loads(_finish_response(result))
def query_document(
self,
document_template: dict,
graph_type: GraphType = GraphType.INSTANCE,
skip: int = 0,
count: Optional[int] = None,
as_list: bool = False,
get_data_version: bool = False,
**kwargs,
) -> Union[Iterable, list]:
"""Retrieves all documents that match a given document template
Parameters
----------
document_template : dict
Template for the document that is being retrived
graph_type : GraphType
Graph type, either GraphType.INSTANCE or GraphType.SCHEMA.
as_list : bool
If the result returned as list rather than an iterator.
get_data_version : bool
If the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
Raises
------
InterfaceError
if the client does not connect to a database
Returns
-------
Iterable
"""
self._check_connection()
payload = {"query": document_template, "graph_type": graph_type}
payload["skip"] = skip
if count is not None:
payload["count"] = count
add_args = ["prefixed", "minimized", "unfold"]
for the_arg in add_args:
if the_arg in kwargs:
payload[the_arg] = kwargs[the_arg]
headers = self._default_headers.copy()
headers["X-HTTP-Method-Override"] = "GET"
result = self._session.post(
self._documents_url(),
headers=headers,
json=payload,
auth=self._auth(),
)
if get_data_version:
result, version = _finish_response(result, get_data_version)
return_obj = _result2stream(result)
if as_list:
return list(return_obj), version
else:
return return_obj, version
return_obj = _result2stream(_finish_response(result))
if as_list:
return list(return_obj)
else:
return return_obj
def get_document(
self,
iri_id: str,
graph_type: GraphType = GraphType.INSTANCE,
get_data_version: bool = False,
**kwargs,
) -> dict:
"""Retrieves the document of the iri_id
Parameters
----------
iri_id : str
Iri id for the document that is to be retrieved
graph_type : GraphType
Graph type, either GraphType.INSTANCE or GraphType.SCHEMA.
get_data_version : bool
If the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargs :
Additional boolean flags for retriving. Currently avaliable: "prefixed", "minimized", "unfold"
Raises
------
InterfaceError
if the client does not connect to a database
Returns
-------
dict
"""
add_args = ["prefixed", "minimized", "unfold"]
self._check_connection()
payload = {"id": iri_id, "graph_type": graph_type}
for the_arg in add_args:
if the_arg in kwargs:
payload[the_arg] = kwargs[the_arg]
result = self._session.get(
self._documents_url(),
headers=self._default_headers,
params=payload,