File¶
Contained within this file are experimental interfaces for working with the Synapse Python Client. Unless otherwise noted these interfaces are subject to change at any time. Use at your own risk.
Example Script¶
Working with files
"""
Expects that ~/temp exists and is a directory.
The purpose of this script is to demonstrate how to use the new OOP interface for files.
The following actions are shown in this script:
1. Creating a file
2. Storing a file
3. Storing a file in a sub-folder
4. Renaming a file
5. Downloading a file
6. Deleting a file
7. Copying a file
8. Storing an activity to a file
9. Retrieve an activity from a file
"""
import os
from datetime import date, datetime, timedelta, timezone
import synapseclient
from synapseclient.core import utils
from synapseclient.models import Activity, File, Folder, UsedEntity, UsedURL
PROJECT_ID = "syn52948289"
syn = synapseclient.Synapse(debug=True)
syn.login()
def create_random_file(
path: str,
) -> None:
"""Create a random file with random data.
:param path: The path to create the file at.
"""
with open(path, "wb") as f:
f.write(os.urandom(1))
def store_file():
# Cleanup synapse for previous runs - Does not delete local files/directories:
try:
Folder(name="file_script_folder", parent_id=PROJECT_ID).get().delete()
except Exception:
pass
if not os.path.exists(os.path.expanduser("~/temp/myNewFolder")):
os.mkdir(os.path.expanduser("~/temp/myNewFolder"))
script_file_folder = Folder(name="file_script_folder", parent_id=PROJECT_ID).store()
# Creating annotations for my file ==================================================
annotations_for_my_file = {
"my_single_key_string": "a",
"my_key_string": ["b", "a", "c"],
"my_key_bool": [False, False, False],
"my_key_double": [1.2, 3.4, 5.6],
"my_key_long": [1, 2, 3],
"my_key_date": [date.today(), date.today() - timedelta(days=1)],
"my_key_datetime": [
datetime.today(),
datetime.today() - timedelta(days=1),
datetime.now(tz=timezone(timedelta(hours=-5))),
datetime(2023, 12, 7, 13, 0, 0, tzinfo=timezone(timedelta(hours=0))),
datetime(2023, 12, 7, 13, 0, 0, tzinfo=timezone(timedelta(hours=-7))),
],
}
name_of_file = "file_script_my_file_with_random_data.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
# 1. Creating a file =================================================================
file = File(
path=path_to_file,
annotations=annotations_for_my_file,
parent_id=script_file_folder.id,
description="This is a file with random data.",
)
# 2. Storing a file ==================================================================
file = file.store()
print(f"File created: ID: {file.id}, Parent ID: {file.parent_id}")
name_of_file = "file_in_a_sub_folder.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
# 3. Storing a file to a sub-folder ==================================================
script_sub_folder = Folder(
name="file_script_sub_folder", parent_id=script_file_folder.id
).store()
file_in_a_sub_folder = File(
path=path_to_file,
annotations=annotations_for_my_file,
parent_id=script_sub_folder.id,
description="This is a file with random data.",
)
file_in_a_sub_folder = file_in_a_sub_folder.store()
print(
f"File created in sub folder: ID: {file_in_a_sub_folder.id}, Parent ID: {file_in_a_sub_folder.parent_id}"
)
# 4. Renaming a file =================================================================
name_of_file = "file_script_my_file_to_rename.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
# The name of the entity, and the name of the file is disjointed.
# For example, the name of the file is "file_script_my_file_to_rename.txt"
# and the name of the entity is "this_name_is_different"
file: File = File(
path=path_to_file,
name="this_name_is_different",
parent_id=script_file_folder.id,
).store()
print(f"File created with name: {file.name}")
print(f"The path of the file is: {file.path}")
# You can change the name of the entity without changing the name of the file.
file.name = "modified_name_attribute"
file.store()
print(f"File renamed to: {file.name}")
# You can then change the name of the file that would be downloaded like:
file.change_metadata(download_as="new_name_for_downloading.txt")
print(f"File download values changed to: {file.file_handle.file_name}")
# 5. Downloading a file ===============================================================
# Downloading a file to a location has a default beahvior of "keep.both"
downloaded_file = File(
id=file.id, path=os.path.expanduser("~/temp/myNewFolder")
).get()
print(f"Downloaded file: {downloaded_file.path}")
# I can also specify how collisions are handled when downloading a file.
# This will replace the file on disk if it already exists and is different (after).
path_to_file = downloaded_file.path
create_random_file(path_to_file)
print(f"Before file md5: {utils.md5_for_file(path_to_file).hexdigest()}")
downloaded_file = File(
id=downloaded_file.id,
path=os.path.expanduser("~/temp/myNewFolder"),
if_collision="overwrite.local",
).get()
print(f"After file md5: {utils.md5_for_file(path_to_file).hexdigest()}")
# This will keep the file on disk (before), and no file is downloaded
path_to_file = downloaded_file.path
create_random_file(path_to_file)
print(f"Before file md5: {utils.md5_for_file(path_to_file).hexdigest()}")
downloaded_file = File(
id=downloaded_file.id,
path=os.path.expanduser("~/temp/myNewFolder"),
if_collision="keep.local",
).get()
print(f"After file md5: {utils.md5_for_file(path_to_file).hexdigest()}")
# 6. Deleting a file =================================================================
# Suppose I have a file that I want to delete.
name_of_file = "file_to_delete.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
file_to_delete = File(path=path_to_file, parent_id=script_file_folder.id).store()
file_to_delete.delete()
# 7. Copying a file ===================================================================
print(
f"File I am going to copy: ID: {file_in_a_sub_folder.id}, Parent ID: {file_in_a_sub_folder.parent_id}"
)
new_sub_folder = Folder(
name="sub_sub_folder", parent_id=script_file_folder.id
).store()
copied_file_instance = file_in_a_sub_folder.copy(parent_id=new_sub_folder.id)
print(
f"File I copied: ID: {copied_file_instance.id}, Parent ID: {copied_file_instance.parent_id}"
)
# 8. Storing an activity to a file =====================================================
activity = Activity(
name="some_name",
description="some_description",
used=[
UsedURL(name="example", url="https://www.synapse.org/"),
UsedEntity(target_id="syn456", target_version_number=1),
],
executed=[
UsedURL(name="example", url="https://www.synapse.org/"),
UsedEntity(target_id="syn789", target_version_number=1),
],
)
name_of_file = "file_with_an_activity.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
file_with_activity = File(
path=path_to_file, parent_id=script_file_folder.id, activity=activity
).store()
print(file_with_activity.activity)
# 9. When I am retrieving that file later on I can get the activity like =============
# By also specifying download_file=False, I can get the activity without downloading the file.
new_file_with_activity_instance = File(
id=file_with_activity.id, download_file=False
).get(include_activity=True)
print(new_file_with_activity_instance.activity)
store_file()
API Reference¶
synapseclient.models.File
dataclass
¶
Bases: FileSynchronousProtocol
, AccessControllable
, BaseJSONSchema
A file within Synapse.
ATTRIBUTE | DESCRIPTION |
---|---|
id |
The unique immutable ID for this file. A new ID will be generated for new Files. Once issued, this ID is guaranteed to never change or be re-issued. |
name |
The name of this entity. Must be 256 characters or less. Names may only contain: letters, numbers, spaces, underscores, hyphens, periods, plus signs, apostrophes, and parentheses. If not specified, the name will be derived from the file name. |
path |
The path to the file on disk. Using shorthand This is used during a This is also used during a |
description |
The description of this file. Must be 1000 characters or less. |
parent_id |
The ID of the Entity that is the parent of this Entity. Setting this to a new value and storing it will move this File under the new parent. |
version_label |
The version label for this entity. Updates to the entity will increment the version number. |
version_comment |
The version comment for this entity |
data_file_handle_id |
ID of the file associated with this entity. You may define an existing data_file_handle_id to use the existing data_file_handle_id. The creator of the file must also be the owner of the data_file_handle_id to have permission to store the file. |
external_url |
The external URL of this file. If this is set AND |
activity |
The Activity model represents the main record of Provenance in Synapse. It is analygous to the Activity defined in the W3C Specification on Provenance. Activity cannot be removed during a store operation by setting it to None. You must use: synapseclient.models.Activity.delete_async or synapseclient.models.Activity.disassociate_from_entity_async. |
annotations |
Additional metadata associated with the folder. The key is the name
of your desired annotations. The value is an object containing a list of
values (use empty list to represent no values for key) and the value type
associated with all values in the list. To remove all annotations set this
to an empty dict
TYPE:
|
ATTRIBUTE | DESCRIPTION |
---|---|
content_type |
(New Upload Only) Used to manually specify Content-type header, for example 'application/png' or 'application/json; charset=UTF-8'. If not specified, the content type will be derived from the file extension. This can be specified only during the initial store of this file or any time there is a new file to upload. In order to change this after the File has been created use synapseclient.models.File.change_metadata. |
content_size |
(New Upload Only)
The size of the file in bytes. This can be specified only during the initial
creation of the File. This is also only applicable to files not uploaded to
Synapse. ie: |
ATTRIBUTE | DESCRIPTION |
---|---|
content_md5 |
(Store only) The MD5 of the file is known. If not supplied this
will be computed in the client is possible. If supplied for a file entity
already stored in Synapse it will be calculated again to check if a new
upload needs to occur. This will not be filled in during a read for data. It
is only used during a store operation. To retrieve the md5 of the file after
read from synapse use the |
create_or_update |
(Store only)
Indicates whether the method should automatically perform an
update if the
TYPE:
|
force_version |
(Store only) Indicates whether the method should increment the version of the object if something within the entity has changed. For example updating the description or name. You may set this to False and an update to the entity will not increment the version. Updating the An update to the MD5 of the file will force a version update regardless of this flag.
TYPE:
|
is_restricted |
(Store only) If set to true, an email will be sent to the Synapse access control team to start the process of adding terms-of-use or review board approval for this entity. You will be contacted with regards to the specific data being restricted and the requirements of access. This may be used only by an administrator of the specified file.
TYPE:
|
merge_existing_annotations |
(Store only)
Works in conjunction with
TYPE:
|
associate_activity_to_new_version |
(Store only)
Works in conjunction with
TYPE:
|
synapse_store |
(Store only) Whether the File should be uploaded or if false: only the path should be stored when synapseclient.models.File.store is called.
TYPE:
|
ATTRIBUTE | DESCRIPTION |
---|---|
download_file |
(Get only) If True the file will be downloaded.
TYPE:
|
if_collision |
(Get only) Determines how to handle file collisions. Defaults to "keep.both". May be:
TYPE:
|
synapse_container_limit |
(Get only) A Synanpse ID used to limit the search in Synapse if file is specified as a local file. That is, if the file is stored in multiple locations in Synapse only the ones in the specified folder/project will be returned. |
ATTRIBUTE | DESCRIPTION |
---|---|
etag |
(Read Only) Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent updates. Since the E-Tag changes every time an entity is updated it is used to detect when a client's current representation of an entity is out-of-date. |
created_on |
(Read Only) The date this entity was created. |
modified_on |
(Read Only) The date this entity was last modified. |
created_by |
(Read Only) The ID of the user that created this entity. |
modified_by |
(Read Only) The ID of the user that last modified this entity. |
version_number |
(Read Only) The version number issued to this version on the object. |
is_latest_version |
(Read Only) If this is the latest version of the object. |
file_handle |
(Read Only) The file handle associated with this entity.
TYPE:
|
Source code in synapseclient/models/file.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 |
|
Functions¶
get
¶
Get the file from Synapse. You may retrieve a File entity by either:
- id
- path
If you specify both, the id
will take precedence.
If you specify the path
and the file is stored in multiple locations in Synapse
only the first one found will be returned. The other matching files will be
printed to the console.
You may also specify a version_number
to get a specific version of the file.
PARAMETER | DESCRIPTION |
---|---|
include_activity
|
If True the activity will be included in the file if it exists.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The file object. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the file does not have an ID or path to get. |
Using this function
Assuming you have a file with the ID "syn123":
file_instance = File(id="syn123").get()
Assuming you want to download a file to this directory: "path/to/directory":
file_instance = File(path="path/to/directory").get()
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
store
¶
store(parent: Optional[Union[Folder, Project]] = None, *, synapse_client: Optional[Synapse] = None) -> File
Store the file in Synapse. With this method you may:
- Upload a file into Synapse
- Update the metadata of a file in Synapse
- Store a File object in Synapse without updating a file by setting
synapse_store
to False. - Change the name of a file in Synapse by setting the
name
attribute of the File object. Also see the synapseclient.models.File.change_metadata method for changing the name of the downloaded file. - Moving a file to a new parent by setting the
parent_id
attribute of the File object.
PARAMETER | DESCRIPTION |
---|---|
parent
|
The parent folder or project to store the file in. May also be
specified in the File object. If both are provided the parent passed
into |
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The file object. |
Using this function
File with the ID syn123
at path path/to/file.txt
:
file_instance = File(id="syn123", path="path/to/file.txt").store()
File at the path path/to/file.txt
and a parent folder with the ID syn456
:
file_instance = File(path="path/to/file.txt", parent_id="syn456").store()
File at the path path/to/file.txt
and a parent folder with the ID syn456
:
file_instance = File(path="path/to/file.txt").store(parent=Folder(id="syn456"))
Rename a file (Does not update the file on disk or the name of the downloaded file):
file_instance = File(id="syn123", download_file=False).get()
print(file_instance.name) ## prints, e.g., "my_file.txt"
file_instance.change_metadata(name="my_new_name_file.txt")
Rename a file, and the name of the file as downloaded (Does not update the file on disk):
file_instance = File(id="syn123", download_file=False).get()
print(file_instance.name) ## prints, e.g., "my_file.txt"
file_instance.change_metadata(name="my_new_name_file.txt", download_as="my_new_name_file.txt")
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
copy
¶
copy(parent_id: str, update_existing: bool = False, copy_annotations: bool = True, copy_activity: Union[str, None] = 'traceback', *, synapse_client: Optional[Synapse] = None) -> File
Copy the file to another Synapse location. Defaults to the latest version of the file, or the version_number specified in the instance.
PARAMETER | DESCRIPTION |
---|---|
parent_id
|
Synapse ID of a folder/project that the copied entity is being copied to
TYPE:
|
update_existing
|
When the destination has a file that has the same name, users can choose to update that file.
TYPE:
|
copy_annotations
|
True to copy the annotations.
TYPE:
|
copy_activity
|
Has three options to set the activity of the copied file:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The copied file object. |
Using this function
Assuming you have a file with the ID "syn123" and you want to copy it to a folder with the ID "syn456":
new_file_instance = File(id="syn123").copy(parent_id="syn456")
Copy the file but do not persist annotations or activity:
new_file_instance = File(id="syn123").copy(parent_id="syn456", copy_annotations=False, copy_activity=None)
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the file does not have an ID and parent_id to copy. |
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
delete
¶
Delete the file from Synapse.
PARAMETER | DESCRIPTION |
---|---|
version_only
|
If True only the version specified in the |
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the file does not have an ID to delete. |
ValueError
|
If the file does not have a version number to delete a version,
and |
Using this function
Assuming you have a file with the ID "syn123":
File(id="syn123").delete()
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
from_id
classmethod
¶
Wrapper for synapseclient.models.File.get.
PARAMETER | DESCRIPTION |
---|---|
synapse_id
|
The ID of the file in Synapse.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The file object. |
Using this function
Assuming you have a file with the ID "syn123":
file_instance = File.from_id(synapse_id="syn123")
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
from_path
classmethod
¶
Get the file from Synapse. If the path of the file matches multiple files within Synapse the first one found will be returned. The other matching files will be printed to the console.
Wrapper for synapseclient.models.File.get.
PARAMETER | DESCRIPTION |
---|---|
path
|
The path to the file on disk.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The file object. |
Using this function
Assuming you have a file at the path "path/to/file.txt":
file_instance = File.from_path(path="path/to/file.txt")
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
change_metadata
¶
change_metadata(name: Optional[str] = None, download_as: Optional[str] = None, content_type: Optional[str] = None, *, synapse_client: Optional[Synapse] = None) -> File
Change File Entity metadata for properties that are immutable after creation through the store method.
PARAMETER | DESCRIPTION |
---|---|
name
|
Specify to change the filename of a file as seen on Synapse. |
download_as
|
Specify filename to change the filename of a filehandle. |
content_type
|
Specify content type to change the content type of a filehandle. |
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
File
|
The file object. |
Using this function
Can be used to change the filename, the filename when the file is downloaded, or the file content-type without downloading:
file_entity = File(id="syn123", download_file=False).get()
print(os.path.basename(file_entity.path)) ## prints, e.g., "my_file.txt"
file_entity = file_entity.change_metadata(name="my_new_name_file.txt", download_as="my_new_downloadAs_name_file.txt", content_type="text/plain")
print(os.path.basename(file_entity.path)) ## prints, "my_new_downloadAs_name_file.txt"
print(file_entity.name) ## prints, "my_new_name_file.txt"
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the file does not have an ID to change metadata. |
Source code in synapseclient/models/protocols/file_protocol.py
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 |
|
get_permissions
¶
get_permissions(*, synapse_client: Optional[Synapse] = None) -> Permissions
Get the permissions that the caller has on an Entity.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Permissions
|
A Permissions object |
Using this function:
Getting permissions for a Synapse Entity
from synapseclient import Synapse
from synapseclient.models import File
syn = Synapse()
syn.login()
permissions = File(id="syn123").get_permissions()
Getting access types list from the Permissions object
permissions.access_types
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|
get_acl
¶
get_acl(principal_id: int = None, check_benefactor: bool = True, *, synapse_client: Optional[Synapse] = None) -> List[str]
Get the ACL that a user or group has on an Entity.
Note: If the entity does not have local sharing settings, or ACL set directly on it, this will look up the ACL on the benefactor of the entity. The benefactor is the entity that the current entity inherits its permissions from. The benefactor is usually the parent entity, but it can be any ancestor in the hierarchy. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project or Folder. If the entity already has local sharing settings, the benefactor would be itself.
PARAMETER | DESCRIPTION |
---|---|
principal_id
|
Identifier of a user or group (defaults to PUBLIC users)
TYPE:
|
check_benefactor
|
If True (default), check the benefactor for the entity to get the ACL. If False, only check the entity itself. This is useful for checking the ACL of an entity that has local sharing settings, but you want to check the ACL of the entity itself and not the benefactor it may inherit from.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
List[str]
|
An array containing some combination of ['READ', 'UPDATE', 'CREATE', 'DELETE', 'DOWNLOAD', 'MODERATE', 'CHANGE_PERMISSIONS', 'CHANGE_SETTINGS'] or an empty array |
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|
list_acl
¶
list_acl(recursive: bool = False, include_container_content: bool = False, target_entity_types: Optional[List[str]] = None, log_tree: bool = False, *, synapse_client: Optional[Synapse] = None, _progress_bar: Optional[tqdm] = None) -> AclListResult
List the Access Control Lists (ACLs) for this entity and optionally its children.
This function returns the local sharing settings for the entity and optionally its children. It provides a mapping of all ACLs for the given container/entity.
Important Note: This function returns the LOCAL sharing settings only, not the effective permissions that each Synapse User ID/Team has on the entities. More permissive permissions could be granted via a Team that the user has access to that has permissions on the entity, or through inheritance from parent entities.
PARAMETER | DESCRIPTION |
---|---|
recursive
|
If True and the entity is a container (e.g., Project or Folder),
recursively process child containers. Note that this must be used with
include_container_content=True to have any effect. Setting recursive=True
with include_container_content=False will raise a ValueError.
Only works on classes that support the
TYPE:
|
include_container_content
|
If True, include ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.
TYPE:
|
target_entity_types
|
Specify which entity types to process when listing ACLs. Allowed values are "folder" and "file" (case-insensitive). If None, defaults to ["folder", "file"]. |
log_tree
|
If True, logs the ACL results to console in ASCII tree format showing entity hierarchies and their ACL permissions in a tree-like structure. Defaults to False.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
_progress_bar
|
Internal parameter. Progress bar instance to use for updates when called recursively. Should not be used by external callers.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
AclListResult
|
An AclListResult object containing a structured representation of ACLs where: |
AclListResult
|
|
AclListResult
|
|
AclListResult
|
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the entity does not have an ID or if an invalid entity type is provided. |
SynapseHTTPError
|
If there are permission issues accessing ACLs. |
Exception
|
For any other errors that may occur during the process. |
List ACLs for a single entity
from synapseclient import Synapse
from synapseclient.models import File
syn = Synapse()
syn.login()
acl_result = File(id="syn123").list_acl()
print(acl_result)
# Access entity ACLs (entity_acls is a list, not a dict)
for entity_acl in acl_result.all_entity_acls:
if entity_acl.entity_id == "syn123":
# Access individual ACL entries
for acl_entry in entity_acl.acl_entries:
if acl_entry.principal_id == "273948":
print(f"Principal 273948 has permissions: {acl_entry.permissions}")
# I can also access the ACL for the file itself
print(acl_result.entity_acl)
print(acl_result)
List ACLs recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder
syn = Synapse()
syn.login()
acl_result = Folder(id="syn123").list_acl(
recursive=True,
include_container_content=True
)
# Access each entity's ACL (entity_acls is a list)
for entity_acl in acl_result.all_entity_acls:
print(f"Entity {entity_acl.entity_id} has ACL with {len(entity_acl.acl_entries)} principals")
# I can also access the ACL for the folder itself
print(acl_result.entity_acl)
# List ACLs for only folder entities
folder_acl_result = Folder(id="syn123").list_acl(
recursive=True,
include_container_content=True,
target_entity_types=["folder"]
)
List ACLs with ASCII tree visualization
When log_tree=True
, the ACLs will be logged in a tree format. Additionally,
the ascii_tree
attribute of the AclListResult will contain the ASCII tree
representation of the ACLs.
from synapseclient import Synapse
from synapseclient.models import Folder
syn = Synapse()
syn.login()
acl_result = Folder(id="syn123").list_acl(
recursive=True,
include_container_content=True,
log_tree=True, # Enable ASCII tree logging
)
# The ASCII tree representation of the ACLs will also be available
# in acl_result.ascii_tree
print(acl_result.ascii_tree)
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|
set_permissions
¶
set_permissions(principal_id: int = None, access_type: List[str] = None, modify_benefactor: bool = False, warn_if_inherits: bool = True, overwrite: bool = True, *, synapse_client: Optional[Synapse] = None) -> Dict[str, Union[str, list]]
Sets permission that a user or group has on an Entity. An Entity may have its own ACL or inherit its ACL from a benefactor.
PARAMETER | DESCRIPTION |
---|---|
principal_id
|
Identifier of a user or group.
TYPE:
|
access_type
|
Type of permission to be granted. One or more of CREATE, READ, DOWNLOAD, UPDATE, DELETE, CHANGE_PERMISSIONS. Defaults to ['READ', 'DOWNLOAD'] |
modify_benefactor
|
Set as True when modifying a benefactor's ACL. The term 'benefactor' is used to indicate which Entity an Entity inherits its ACL from. For example, a newly created Project will be its own benefactor, while a new FileEntity's benefactor will start off as its containing Project. If the entity already has local sharing settings the benefactor would be itself. It may also be the immediate parent, somewhere in the parent tree, or the project itself.
TYPE:
|
warn_if_inherits
|
When
TYPE:
|
overwrite
|
By default this function overwrites existing permissions for the specified user. Set this flag to False to add new permissions non-destructively.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Dict[str, Union[str, list]]
|
An Access Control List object |
Setting permissions
Grant all registered users download access
from synapseclient import Synapse
from synapseclient.models import File
syn = Synapse()
syn.login()
File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
Grant the public view access
from synapseclient import Synapse
from synapseclient.models import File
syn = Synapse()
syn.login()
File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|
delete_permissions
¶
delete_permissions(include_self: bool = True, include_container_content: bool = False, recursive: bool = False, target_entity_types: Optional[List[str]] = None, dry_run: bool = False, show_acl_details: bool = True, show_files_in_containers: bool = True, *, benefactor_tracker: Optional[BenefactorTracker] = None, synapse_client: Optional[Synapse] = None) -> None
Delete the entire Access Control List (ACL) for a given Entity. This is not scoped to a specific user or group, but rather removes all permissions associated with the Entity. After this operation, the Entity will inherit permissions from its benefactor, which is typically its parent entity or the Project it belongs to.
In order to remove permissions for a specific user or group, you
should use the set_permissions
method with the access_type
set to
an empty list.
By default, Entities such as FileEntity and Folder inherit their permission from their containing Project. For such Entities the Project is the Entity's 'benefactor'. This permission inheritance can be overridden by creating an ACL for the Entity. When this occurs the Entity becomes its own benefactor and all permission are determined by its own ACL.
If the ACL of an Entity is deleted, then its benefactor will automatically be set to its parent's benefactor.
Special notice for Projects: The ACL for a Project cannot be deleted, you must individually update or revoke the permissions for each user or group.
PARAMETER | DESCRIPTION |
---|---|
include_self
|
If True (default), delete the ACL of the current entity. If False, skip deleting the ACL of the current entity.
TYPE:
|
include_container_content
|
If True, delete ACLs from contents directly within containers (files and folders inside self). This must be set to True for recursive to have any effect. Defaults to False.
TYPE:
|
recursive
|
If True and the entity is a container (e.g., Project or Folder),
recursively process child containers. Note that this must be used with
include_container_content=True to have any effect. Setting recursive=True
with include_container_content=False will raise a ValueError.
Only works on classes that support the
TYPE:
|
target_entity_types
|
Specify which entity types to process when deleting ACLs.
Allowed values are "folder" and "file" (case-insensitive).
If None, defaults to ["folder", "file"]. This does not affect the
entity type of the current entity, which is always processed if
|
dry_run
|
If True, log the changes that would be made instead of actually performing the deletions. When enabled, all ACL deletion operations are simulated and logged at info level. Defaults to False.
TYPE:
|
show_acl_details
|
When dry_run=True, controls whether current ACL details are displayed for entities that will have their permissions changed. If True (default), shows detailed ACL information. If False, hides ACL details for cleaner output. Has no effect when dry_run=False.
TYPE:
|
show_files_in_containers
|
When dry_run=True, controls whether files within containers are displayed in the preview. If True (default), shows all files. If False, hides files when their only change is benefactor inheritance (but still shows files with local ACLs being deleted). Has no effect when dry_run=False.
TYPE:
|
benefactor_tracker
|
Optional tracker for managing benefactor relationships. Used for recursive functionality to track which entities will be affected
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the entity does not have an ID or if an invalid entity type is provided. |
SynapseHTTPError
|
If there are permission issues or if the entity already inherits permissions. |
Exception
|
For any other errors that may occur during the process. |
Note: The caller must be granted ACCESS_TYPE.CHANGE_PERMISSIONS on the Entity to call this method.
Delete permissions for a single entity
from synapseclient import Synapse
from synapseclient.models import File
syn = Synapse()
syn.login()
File(id="syn123").delete_permissions()
Delete permissions recursively for a folder and all its children
from synapseclient import Synapse
from synapseclient.models import Folder
syn = Synapse()
syn.login()
# Delete permissions for this folder only (does not affect children)
Folder(id="syn123").delete_permissions()
# Delete permissions for all files and folders directly within this folder,
# but not the folder itself
Folder(id="syn123").delete_permissions(
include_self=False,
include_container_content=True
)
# Delete permissions for all items in the entire hierarchy (folders and their files)
# Both recursive and include_container_content must be True
Folder(id="syn123").delete_permissions(
recursive=True,
include_container_content=True
)
# Delete permissions only for folder entities within this folder recursively
# and their contents
Folder(id="syn123").delete_permissions(
recursive=True,
include_container_content=True,
target_entity_types=["folder"]
)
# Delete permissions only for files within this folder and all subfolders
Folder(id="syn123").delete_permissions(
include_self=False,
recursive=True,
include_container_content=True,
target_entity_types=["file"]
)
# Dry run example: Log what would be deleted without making changes
Folder(id="syn123").delete_permissions(
recursive=True,
include_container_content=True,
dry_run=True
)
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|
bind_schema
¶
bind_schema(json_schema_uri: str, *, enable_derived_annotations: Optional[bool] = False, synapse_client: Optional[Synapse] = None) -> JSONSchemaBinding
Bind a JSON schema to the entity.
PARAMETER | DESCRIPTION |
---|---|
json_schema_uri
|
The URI of the JSON schema to bind to the entity.
TYPE:
|
enable_derived_annotations
|
If true, enable derived annotations. Defaults to False. |
synapse_client
|
The Synapse client instance. If not provided, the last created instance from the Synapse class constructor will be used. |
RETURNS | DESCRIPTION |
---|---|
JSONSchemaBinding
|
An object containing details about the JSON schema binding. |
Using this function
Binding JSON schema to a folder or a file. This example expects that you
have a Synapse project to use, and a file to upload. Set the PROJECT_NAME
and FILE_PATH
variables to your project name and file path respectively.
from synapseclient import Synapse
from synapseclient.models import File, Folder
syn = Synapse()
syn.login()
# Define Project and JSON schema info
PROJECT_NAME = "test_json_schema_project" # replace with your project name
FILE_PATH = "~/Sample.txt" # replace with your test file path
PROJECT_ID = syn.findEntityId(name=PROJECT_NAME)
ORG_NAME = "UniqueOrg" # replace with your organization name
SCHEMA_NAME = "myTestSchema" # replace with your schema name
FOLDER_NAME = "test_script_folder"
VERSION = "0.0.1"
SCHEMA_URI = f"{ORG_NAME}-{SCHEMA_NAME}-{VERSION}"
# Create organization (if not already created)
js = syn.service("json_schema")
all_orgs = js.list_organizations()
for org in all_orgs:
if org["name"] == ORG_NAME:
print(f"Organization {ORG_NAME} already exists: {org}")
break
else:
print(f"Creating organization {ORG_NAME}.")
created_organization = js.create_organization(ORG_NAME)
print(f"Created organization: {created_organization}")
my_test_org = js.JsonSchemaOrganization(ORG_NAME)
test_schema = my_test_org.get_json_schema(SCHEMA_NAME)
if not test_schema:
# Create the schema (if not already created)
schema_definition = {
"$id": "mySchema",
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "integer"},
},
"required": ["foo"]
}
test_schema = my_test_org.create_json_schema(schema_definition, SCHEMA_NAME, VERSION)
# Create a test folder
test_folder = Folder(name=FOLDER_NAME, parent_id=PROJECT_ID)
test_folder.store()
# Bind JSON schema to the folder
bound_schema = test_folder.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Result from binding schema to folder: {bound_schema}")
# Bind the same schema to a file
example_file = File(
path=FILE_PATH, # Replace with your test file path
parent_id=test_folder.id,
).store()
bound_schema_file = example_file.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Result from binding schema to file: {bound_schema_file}")
Source code in synapseclient/models/protocols/json_schema_protocol.py
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 |
|
get_schema
¶
get_schema(*, synapse_client: Optional[Synapse] = None) -> JSONSchemaBinding
Get the JSON schema bound to the entity.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
The Synapse client instance. If not provided, the last created instance from the Synapse class constructor will be used. |
RETURNS | DESCRIPTION |
---|---|
JSONSchemaBinding
|
An object containing details about the bound JSON schema. |
Using this function
Retrieving the bound JSON schema from a folder or file. This example demonstrates
how to get existing schema bindings from entities that already have schemas bound.
Set the PROJECT_NAME
variable to your project name.
from synapseclient import Synapse
from synapseclient.models import File, Folder
syn = Synapse()
syn.login()
# Define Project and JSON schema info
PROJECT_NAME = "test_json_schema_project" # replace with your project name
FILE_PATH = "~/Sample.txt" # replace with your test file path
PROJECT_ID = syn.findEntityId(name=PROJECT_NAME)
ORG_NAME = "UniqueOrg" # replace with your organization name
SCHEMA_NAME = "myTestSchema" # replace with your schema name
FOLDER_NAME = "test_script_folder"
VERSION = "0.0.1"
SCHEMA_URI = f"{ORG_NAME}-{SCHEMA_NAME}-{VERSION}"
# Create organization (if not already created)
js = syn.service("json_schema")
all_orgs = js.list_organizations()
for org in all_orgs:
if org["name"] == ORG_NAME:
print(f"Organization {ORG_NAME} already exists: {org}")
break
else:
print(f"Creating organization {ORG_NAME}.")
created_organization = js.create_organization(ORG_NAME)
print(f"Created organization: {created_organization}")
my_test_org = js.JsonSchemaOrganization(ORG_NAME)
test_schema = my_test_org.get_json_schema(SCHEMA_NAME)
if not test_schema:
# Create the schema (if not already created)
schema_definition = {
"$id": "mySchema",
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "integer"},
},
"required": ["foo"]
}
test_schema = my_test_org.create_json_schema(schema_definition, SCHEMA_NAME, VERSION)
print(f"Created new schema: {SCHEMA_NAME}")
# Create a test folder
test_folder = Folder(name=FOLDER_NAME, parent_id=PROJECT_ID)
test_folder.store()
print(f"Created test folder: {FOLDER_NAME}")
# Bind JSON schema to the folder first
bound_schema = test_folder.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to folder: {bound_schema}")
# Create and bind schema to a file
example_file = File(
path=FILE_PATH, # Replace with your test file path
parent_id=test_folder.id,
).store()
bound_schema_file = example_file.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to file: {bound_schema_file}")
# Retrieve the bound schema from the folder
retrieved_folder_schema = test_folder.get_schema()
print(f"Retrieved schema from folder: {retrieved_folder_schema}")
# Retrieve the bound schema from the file
retrieved_file_schema = example_file.get_schema()
print(f"Retrieved schema from file: {retrieved_file_schema}")
Source code in synapseclient/models/protocols/json_schema_protocol.py
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 |
|
unbind_schema
¶
Unbind the JSON schema from the entity.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
The Synapse client instance. If not provided, the last created instance from the Synapse class constructor will be used. |
Using this function
Unbinding a JSON schema from a folder or file. This example demonstrates
how to remove schema bindings from entities. Assumes entities already have
schemas bound. Set the PROJECT_NAME
variable to your project name.
from synapseclient import Synapse
from synapseclient.models import File, Folder
syn = Synapse()
syn.login()
# Define Project and JSON schema info
PROJECT_NAME = "test_json_schema_project" # replace with your project name
FILE_PATH = "~/Sample.txt" # replace with your test file path
PROJECT_ID = syn.findEntityId(name=PROJECT_NAME)
ORG_NAME = "UniqueOrg" # replace with your organization name
SCHEMA_NAME = "myTestSchema" # replace with your schema name
FOLDER_NAME = "test_script_folder"
VERSION = "0.0.1"
SCHEMA_URI = f"{ORG_NAME}-{SCHEMA_NAME}-{VERSION}"
# Create organization (if not already created)
js = syn.service("json_schema")
all_orgs = js.list_organizations()
for org in all_orgs:
if org["name"] == ORG_NAME:
print(f"Organization {ORG_NAME} already exists: {org}")
break
else:
print(f"Creating organization {ORG_NAME}.")
created_organization = js.create_organization(ORG_NAME)
print(f"Created organization: {created_organization}")
my_test_org = js.JsonSchemaOrganization(ORG_NAME)
test_schema = my_test_org.get_json_schema(SCHEMA_NAME)
if not test_schema:
# Create the schema (if not already created)
schema_definition = {
"$id": "mySchema",
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "integer"},
},
"required": ["foo"]
}
test_schema = my_test_org.create_json_schema(schema_definition, SCHEMA_NAME, VERSION)
print(f"Created new schema: {SCHEMA_NAME}")
# Create a test folder
test_folder = Folder(name=FOLDER_NAME, parent_id=PROJECT_ID)
test_folder.store()
print(f"Created test folder: {FOLDER_NAME}")
# Bind JSON schema to the folder first
bound_schema = test_folder.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to folder: {bound_schema}")
# Create and bind schema to a file
example_file = File(
path=FILE_PATH, # Replace with your test file path
parent_id=test_folder.id,
).store()
bound_schema_file = example_file.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to file: {bound_schema_file}")
# Unbind the schema from the folder
test_folder.unbind_schema()
print("Successfully unbound schema from folder")
# Unbind the schema from the file
example_file.unbind_schema()
print("Successfully unbound schema from file")
Source code in synapseclient/models/protocols/json_schema_protocol.py
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 |
|
validate_schema
¶
validate_schema(*, synapse_client: Optional[Synapse] = None) -> Union[JSONSchemaValidation, InvalidJSONSchemaValidation]
Validate the entity against the bound JSON schema.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
The Synapse client instance. If not provided, the last created instance from the Synapse class constructor will be used. |
RETURNS | DESCRIPTION |
---|---|
Union[JSONSchemaValidation, InvalidJSONSchemaValidation]
|
The validation results. |
Using this function
Validating a folder or file against the bound JSON schema. This example demonstrates
how to validate entities with annotations against their bound schemas. Requires entities
to have schemas already bound. Set the PROJECT_NAME
variable to your project name.
from synapseclient import Synapse
from synapseclient.models import File, Folder
import time
syn = Synapse()
syn.login()
# Define Project and JSON schema info
PROJECT_NAME = "test_json_schema_project" # replace with your project name
FILE_PATH = "~/Sample.txt" # replace with your test file path
PROJECT_ID = syn.findEntityId(name=PROJECT_NAME)
ORG_NAME = "UniqueOrg" # replace with your organization name
SCHEMA_NAME = "myTestSchema" # replace with your schema name
FOLDER_NAME = "test_script_folder"
VERSION = "0.0.1"
SCHEMA_URI = f"{ORG_NAME}-{SCHEMA_NAME}-{VERSION}"
# Create organization (if not already created)
js = syn.service("json_schema")
all_orgs = js.list_organizations()
for org in all_orgs:
if org["name"] == ORG_NAME:
print(f"Organization {ORG_NAME} already exists: {org}")
break
else:
print(f"Creating organization {ORG_NAME}.")
created_organization = js.create_organization(ORG_NAME)
print(f"Created organization: {created_organization}")
my_test_org = js.JsonSchemaOrganization(ORG_NAME)
test_schema = my_test_org.get_json_schema(SCHEMA_NAME)
if not test_schema:
# Create the schema (if not already created)
schema_definition = {
"$id": "mySchema",
"type": "object",
"properties": {
"foo": {"type": "string"},
"bar": {"type": "integer"},
},
"required": ["foo"]
}
test_schema = my_test_org.create_json_schema(schema_definition, SCHEMA_NAME, VERSION)
print(f"Created new schema: {SCHEMA_NAME}")
# Create a test folder
test_folder = Folder(name=FOLDER_NAME, parent_id=PROJECT_ID)
test_folder.store()
print(f"Created test folder: {FOLDER_NAME}")
# Bind JSON schema to the folder
bound_schema = test_folder.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to folder: {bound_schema}")
# Create and bind schema to a file
example_file = File(
path=FILE_PATH, # Replace with your test file path
parent_id=test_folder.id,
).store()
bound_schema_file = example_file.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to file: {bound_schema_file}")
# Validate the folder entity against the bound schema
test_folder.annotations = {"foo": "test_value", "bar": 42} # Example annotations
test_folder.store()
print("Added annotations to folder and stored")
time.sleep(2) # Allow time for processing
validation_response = test_folder.validate_schema()
print(f"Folder validation response: {validation_response}")
# Validate the file entity against the bound schema
example_file.annotations = {"foo": "test_value", "bar": 43} # Example annotations
example_file.store()
print("Added annotations to file and stored")
time.sleep(2) # Allow time for processing
validation_response_file = example_file.validate_schema()
print(f"File validation response: {validation_response_file}")
Source code in synapseclient/models/protocols/json_schema_protocol.py
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 |
|
get_schema_derived_keys
¶
get_schema_derived_keys(*, synapse_client: Optional[Synapse] = None) -> JSONSchemaDerivedKeys
Retrieve derived JSON schema keys for the entity.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
The Synapse client instance. If not provided, the last created instance from the Synapse class constructor will be used. |
RETURNS | DESCRIPTION |
---|---|
JSONSchemaDerivedKeys
|
An object containing the derived keys for the entity. |
Using this function
Retrieving derived keys from a folder or file. This example demonstrates
how to get derived annotation keys from schemas with constant values.
Set the PROJECT_NAME
variable to your project name.
from synapseclient import Synapse
from synapseclient.models import File, Folder
syn = Synapse()
syn.login()
# Define Project and JSON schema info
PROJECT_NAME = "test_json_schema_project" # replace with your project name
FILE_PATH = "~/Sample.txt" # replace with your test file path
PROJECT_ID = syn.findEntityId(name=PROJECT_NAME)
ORG_NAME = "UniqueOrg" # replace with your organization name
DERIVED_TEST_SCHEMA_NAME = "myTestDerivedSchema" # replace with your derived schema name
FOLDER_NAME = "test_script_folder"
VERSION = "0.0.1"
SCHEMA_URI = f"{ORG_NAME}-{DERIVED_TEST_SCHEMA_NAME}-{VERSION}"
# Create organization (if not already created)
js = syn.service("json_schema")
all_orgs = js.list_organizations()
for org in all_orgs:
if org["name"] == ORG_NAME:
print(f"Organization {ORG_NAME} already exists: {org}")
break
else:
print(f"Creating organization {ORG_NAME}.")
created_organization = js.create_organization(ORG_NAME)
print(f"Created organization: {created_organization}")
my_test_org = js.JsonSchemaOrganization(ORG_NAME)
test_schema = my_test_org.get_json_schema(DERIVED_TEST_SCHEMA_NAME)
if not test_schema:
# Create the schema (if not already created)
schema_definition = {
"$id": "mySchema",
"type": "object",
"properties": {
"foo": {"type": "string"},
"baz": {"type": "string", "const": "example_value"}, # Example constant for derived annotation
"bar": {"type": "integer"},
},
"required": ["foo"]
}
test_schema = my_test_org.create_json_schema(schema_definition, DERIVED_TEST_SCHEMA_NAME, VERSION)
print(f"Created new derived schema: {DERIVED_TEST_SCHEMA_NAME}")
# Create a test folder
test_folder = Folder(name=FOLDER_NAME, parent_id=PROJECT_ID)
test_folder.store()
print(f"Created test folder: {FOLDER_NAME}")
# Bind JSON schema to the folder
bound_schema = test_folder.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to folder with derived annotations: {bound_schema}")
# Create and bind schema to a file
example_file = File(
path=FILE_PATH, # Replace with your test file path
parent_id=test_folder.id,
).store()
bound_schema_file = example_file.bind_schema(
json_schema_uri=SCHEMA_URI,
enable_derived_annotations=True
)
print(f"Bound schema to file with derived annotations: {bound_schema_file}")
# Get the derived keys from the bound schema of the folder
test_folder.annotations = {"foo": "test_value_new", "bar": 42} # Example annotations
test_folder.store()
print("Added annotations to folder and stored")
derived_keys = test_folder.get_schema_derived_keys()
print(f"Derived keys from folder: {derived_keys}")
# Get the derived keys from the bound schema of the file
example_file.annotations = {"foo": "test_value_new", "bar": 43} # Example annotations
example_file.store()
print("Added annotations to file and stored")
derived_keys_file = example_file.get_schema_derived_keys()
print(f"Derived keys from file: {derived_keys_file}")
Source code in synapseclient/models/protocols/json_schema_protocol.py
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 |
|
synapseclient.models.file.FileHandle
dataclass
¶
A file handle is a pointer to a file stored in a specific location.
ATTRIBUTE | DESCRIPTION |
---|---|
id |
The ID of this FileHandle. All references to this FileHandle will use this ID. Synapse will generate this ID when the FileHandle is created. |
etag |
FileHandles are immutable from the perspective of the API. The only field that can be change is the previewId. When a new previewId is set, the etag will change. |
created_by |
The ID Of the user that created this file. |
created_on |
The date when this file was uploaded. |
modified_on |
The date when the file was modified. This is handled by the backend and cannot be modified. |
concrete_type |
This is used to indicate the implementation of this interface. For example, an S3FileHandle should be set to: org.sagebionetworks.repo.model.file.S3FileHandle |
content_type |
|
content_md5 |
The file's content MD5. |
file_name |
The short, user visible name for this file. |
storage_location_id |
The optional storage location descriptor. |
content_size |
The size of the file in bytes. |
status |
The status of the file handle as computed by the backend. This value cannot be changed, any file handle that is not AVAILABLE should not be used. |
bucket_name |
The name of the bucket where this file resides. |
key |
The path or resource name for this object. |
preview_id |
If this file has a preview, then this will be the file ID of the preview. |
is_preview |
Whether or not this is a preview of another file. |
external_url |
The URL of the file if it is stored externally. |
Source code in synapseclient/models/file.py
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 |
|