EntityView¶
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.
API reference¶
synapseclient.models.EntityView
dataclass
¶
Bases: AccessControllable
, ViewBase
, ViewStoreMixin
, DeleteMixin
, ColumnMixin
, GetMixin
, QueryMixin
, ViewUpdateMixin
, ViewSnapshotMixin
, EntityViewSynchronousProtocol
, BaseJSONSchema
A view of Entities within a defined scope. The purpose of a EntityView
, also known
as an FileView
, is to create a SQL-like view of entities within a
defined scope. The scope is defined by the scope_ids
attribute. The scope_ids
attribute is a list of syn
container ids that define where to search for rows to
include in the view. Entities within the scope are included in the view if they
match the criteria defined by the view_type_mask
attribute. The view_type_mask
attribute is a bit mask representing the types to include in the view. You may set
this to a single value using the ViewTypeMask
enum or you may set this to multiple values using the bitwise OR operator.
ATTRIBUTE | DESCRIPTION |
---|---|
id |
The unique immutable ID for this dataset. A new ID will be generated for new Datasets. Once issued, this ID is guaranteed to never change or be re-issued |
name |
The name of this dataset. Must be 256 characters or less. Names may only contain: letters, numbers, spaces, underscores, hyphens, periods, plus signs, apostrophes, and parentheses |
description |
The description of this entity. Must be 1000 characters or less. |
etag |
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 |
The date this dataset was created. |
modified_on |
The date this dataset was last modified. In YYYY-MM-DD-Thh:mm:ss.sssZ format |
created_by |
The ID of the user that created this dataset. |
modified_by |
The ID of the user that last modified this dataset. |
parent_id |
The ID of the Entity that is the parent of this dataset. |
version_number |
The version number issued to this version on the object. |
version_label |
The version label for this dataset. |
version_comment |
The version comment for this dataset. |
is_latest_version |
If this is the latest version of the object. |
columns |
The columns of this view. This is an ordered dictionary where the key
is the name of the column and the value is the Column object. When creating
a new instance of a View object you may pass any of the following types as
the
The order of the columns will be the order they are stored in Synapse. If
you need to reorder the columns the recommended approach is to use the
You may modify the attributes of the Column object to change the column type, name, or other attributes. For example suppose I'd like to change a column from a INTEGER to a DOUBLE. I can do so by changing the column type attribute of the Column object. The next time you store the view the column will be updated in Synapse with the new type.
Note that the keys in this dictionary should match the column names as they are in Synapse. However, know that the name attribute of the Column object is used for all interactions with the Synapse API. The OrderedDict key is purely for the usage of this interface. For example, if you wish to rename a column you may do so by changing the name attribute of the Column object. The key in the OrderedDict does not need to be changed. The next time you store the view the column will be updated in Synapse with the new name and the key in the OrderedDict will be updated.
TYPE:
|
include_default_columns |
When creating a entityview or view, specifies if default columns should be included. Default columns are columns that are automatically added to the entityview or view. These columns are managed by Synapse and cannot be modified. If you attempt to create a column with the same name as a default column, you will receive a warning when you store the entityview.
The column you are overriding will not behave the same as a default column.
For example, suppose you create a column called |
is_search_enabled |
When creating or updating a dataset or view specifies if full text search should be enabled. Note that enabling full text search might slow down the indexing of the dataset or view. |
view_type_mask |
Bit mask representing the types to include in the view. You may set this to a single value using the ViewTypeMask enum or you may set this to multiple values using the bitwise OR operator. When this is returned after storing or reading from Synapse it will be returned as an integer. The following are the possible types (type=):
To include multiple types in the view you will be using the bitwise OR operator to combine the types. For example, if you want to include both Files and Folders in the view you would use the following code:
TYPE:
|
scope_ids |
The list of container ids that define the scope of this view. This
may be a single container or multiple containers. A container in this
context may refer to a Project or Folder which contains zero or more
entities. The entities in the container(s) will be included in the view if
they match the criteria defined by the |
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 entityview. 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:
|
Source code in synapseclient/models/entityview.py
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 |
|
Functions¶
store
¶
store(dry_run: bool = False, *, job_timeout: int = 600, synapse_client: Optional[Synapse] = None) -> Self
Store non-row information about a view including the columns and annotations.
Note the following behavior for the order of columns:
- If a column is added via the
add_column
method it will be added at the index you specify, or at the end of the columns list. - If column(s) are added during the contruction of your
EntityView
instance, ie.EntityView(columns=[Column(name="foo")])
, they will be added at the begining of the columns list. - If you use the
store_rows
method and theschema_storage_strategy
is set toINFER_FROM_DATA
the columns will be added at the end of the columns list.
PARAMETER | DESCRIPTION |
---|---|
dry_run
|
If True, will not actually store the entityview but will log to the console what would have been stored.
TYPE:
|
job_timeout
|
The maximum amount of time to wait for a job to complete.
This is used when updating the entityview schema. If the timeout
is reached a
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The EntityView instance stored in synapse. |
Source code in synapseclient/models/entityview.py
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 |
|
get
¶
get(include_columns: bool = True, include_activity: bool = False, *, synapse_client: Optional[Synapse] = None) -> Self
Get the metadata about the entityview from synapse.
PARAMETER | DESCRIPTION |
---|---|
include_columns
|
If True, will include fully filled column objects in the
TYPE:
|
include_activity
|
If True the activity will be included in the file if it exists. Defaults to False.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The EntityView instance stored in synapse. |
Getting metadata about a entityview using id
Get a entityview by ID and print out the columns and activity. include_columns
defaults to True and include_activity
defaults to False. When you need to
update existing columns or activity these need to be set to True during the
get
call, then you'll make the changes, and finally call the
.store()
method.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
entityview = EntityView(id="syn4567").get(include_activity=True)
print(entityview)
# Columns are retrieved by default
print(entityview.columns)
print(entityview.activity)
Getting metadata about a entityview using name and parent_id
Get a entityview by name/parent_id and print out the columns and activity.
include_columns
defaults to True and include_activity
defaults to
False. When you need to update existing columns or activity these need to
be set to True during the get
call, then you'll make the changes,
and finally call the .store()
method.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
entityview = EntityView(name="my_table", parent_id="syn1234").get(include_columns=True, include_activity=True)
print(entityview)
print(entityview.columns)
print(entityview.activity)
Source code in synapseclient/models/entityview.py
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 |
|
delete
¶
Delete the entity from synapse. This is not version specific. If you'd like to delete a specific version of the entity you must use the synapseclient.api.delete_entity function directly.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Deleting a entityview
Deleting a entityview is only supported by the ID of the entityview.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
EntityView(id="syn4567").delete()
Source code in synapseclient/models/entityview.py
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 |
|
update_rows
¶
update_rows(values: Union[str, Dict[str, Any], DATA_FRAME_TYPE], primary_keys: List[str], dry_run: bool = False, *, rows_per_query: int = 50000, update_size_bytes: int = 1.9 * MB, insert_size_bytes: int = 900 * MB, job_timeout: int = 600, wait_for_eventually_consistent_view: bool = False, wait_for_eventually_consistent_view_timeout: int = 600, synapse_client: Optional[Synapse] = None, **kwargs) -> None
This method leverages the logic provided by upsert_rows_async to provide
an interface for updating rows in a View
-like entity. Update functionality will only work for
values in custom columns within a View
-like entity.
Limitations:
- When updating many rows the requests to Synapse will be chunked into smaller requests. The limit is 2MB per request. This chunking will happen automatically and should not be a concern for most users. If you are having issues with the request being too large you may lower the number of rows you are trying to update.
- The
primary_keys
argument must contain at least one column. - The
primary_keys
argument cannot contain columns that are a LIST type. - The
primary_keys
argument cannot contain columns that are a JSON type. - The values used as the
primary_keys
must be unique in the entityview. If there are multiple rows with the same values in theprimary_keys
the behavior is that an exception will be raised. - The columns used in
primary_keys
cannot contain updated values. Since the values in these columns are used to determine if a row exists, they cannot be updated in the same transaction.
PARAMETER | DESCRIPTION |
---|---|
values
|
Supports storing data from the following sources:
|
primary_keys
|
The columns to use to determine if a row already exists. If a row exists with the same values in the columns specified in this list the row will be updated. If a row does not exist nothing will be done. |
dry_run
|
If set to True the data will not be updated in Synapse. A message
will be printed to the console with the number of rows that would have
been updated and inserted. If you would like to see the data that would
be updated and inserted you may set the
TYPE:
|
rows_per_query
|
The number of rows that will be queried from Synapse per request. Since we need to query for the data that is being updated this will determine the number of rows that are queried at a time. The default is 50,000 rows.
TYPE:
|
update_size_bytes
|
The maximum size of the request that will be sent to Synapse when updating rows of data. The default is 1.9MB.
TYPE:
|
insert_size_bytes
|
The maximum size of the request that will be sent to Synapse when inserting rows of data. The default is 900MB.
TYPE:
|
job_timeout
|
The maximum amount of time to wait for a job to complete.
This is used when inserting, and updating rows of data. Each individual
request to Synapse will be sent as an independent job. If the timeout
is reached a
TYPE:
|
wait_for_eventually_consistent_view
|
Only used if the table is a view. If set to True this will wait for the view to reflect any changes that you've made to the view. This is useful if you need to query the view after making changes to the data.
TYPE:
|
wait_for_eventually_consistent_view_timeout
|
The maximum amount of time to wait for a view to be eventually consistent. The default is 600 seconds.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
**kwargs
|
Additional arguments that are passed to the
DEFAULT:
|
Source code in synapseclient/models/entityview.py
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 |
|
query
staticmethod
¶
query(query: str, include_row_id_and_row_version: bool = True, convert_to_datetime: bool = False, download_location=None, quote_character='"', escape_character='\\', line_end=str(linesep), separator=',', header=True, *, synapse_client: Optional[Synapse] = None, **kwargs) -> Union[DATA_FRAME_TYPE, str]
Query for data on a table stored in Synapse. The results will always be
returned as a Pandas DataFrame unless you specify a download_location
in which
case the results will be downloaded to that location. There are a number of
arguments that you may pass to this function depending on if you are getting
the results back as a DataFrame or downloading the results to a file.
PARAMETER | DESCRIPTION |
---|---|
query
|
The query to run. The query must be valid syntax that Synapse can understand. See this document that describes the expected syntax of the query: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html
TYPE:
|
include_row_id_and_row_version
|
If True the
TYPE:
|
convert_to_datetime
|
(DataFrame only) If set to True, will convert all Synapse DATE columns from UNIX timestamp integers into UTC datetime objects
TYPE:
|
download_location
|
(CSV Only) If set to a path the results will be downloaded to that directory. The results will be downloaded as a CSV file. A path to the downloaded file will be returned instead of a DataFrame.
DEFAULT:
|
quote_character
|
(CSV Only) The character to use to quote fields. The default is a double quote.
DEFAULT:
|
escape_character
|
(CSV Only) The character to use to escape special characters. The default is a backslash.
DEFAULT:
|
line_end
|
(CSV Only) The character to use to end a line. The default is the system's line separator. |
separator
|
(CSV Only) The character to use to separate fields. The default is a comma.
DEFAULT:
|
header
|
(CSV Only) If set to True the first row will be used as the header row. The default is True.
DEFAULT:
|
**kwargs
|
(DataFrame only) Additional keyword arguments to pass to pandas.read_csv. See https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html for complete list of supported arguments. This is exposed as internally the query downloads a CSV from Synapse and then loads it into a dataframe.
DEFAULT:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Union[DATA_FRAME_TYPE, str]
|
The results of the query as a Pandas DataFrame or a path to the downloaded |
Union[DATA_FRAME_TYPE, str]
|
query results if |
Querying for data
This example shows how you may query for data in a table and print out the results.
from synapseclient import Synapse
from synapseclient.models import query
syn = Synapse()
syn.login()
results = query(query="SELECT * FROM syn1234")
print(results)
Source code in synapseclient/models/mixins/table_components.py
2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 |
|
query_part_mask
staticmethod
¶
query_part_mask(query: str, part_mask: int, *, synapse_client: Optional[Synapse] = None, **kwargs) -> QueryResultOutput
Query for data on a table stored in Synapse. This is a more advanced use case
of the query
function that allows you to determine what addiitional metadata
about the table or query should also be returned. If you do not need this
additional information then you are better off using the query
function.
The query for this method uses this Rest API: https://rest-docs.synapse.org/rest/POST/entity/id/table/query/async/start.html
PARAMETER | DESCRIPTION |
---|---|
query
|
The query to run. The query must be valid syntax that Synapse can understand. See this document that describes the expected syntax of the query: https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html
TYPE:
|
part_mask
|
The bitwise OR of the part mask values you want to return in the results. The following list of part masks are implemented to be returned in the results: - Query Results (queryResults) = 0x1 - Query Count (queryCount) = 0x2 - The sum of the file sizes (sumFileSizesBytes) = 0x40 - The last updated on date of the table (lastUpdatedOn) = 0x80
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
QueryResultOutput
|
The results of the query as a Pandas DataFrame. |
Querying for data with a part mask
This example shows how to use the bitwise OR
of Python to combine the
part mask values and then use that to query for data in a table and print
out the results.
In this case we are getting the results of the query, the count of rows, and the last updated on date of the table.
from synapseclient import Synapse
from synapseclient.models import query_part_mask
syn = Synapse()
syn.login()
QUERY_RESULTS = 0x1
QUERY_COUNT = 0x2
LAST_UPDATED_ON = 0x80
# Combine the part mask values using bitwise OR
part_mask = QUERY_RESULTS | QUERY_COUNT | LAST_UPDATED_ON
result = query_part_mask(query="SELECT * FROM syn1234", part_mask=part_mask)
print(result)
Source code in synapseclient/models/mixins/table_components.py
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 |
|
snapshot
¶
snapshot(*, comment: Optional[str] = None, label: Optional[str] = None, include_activity: bool = True, associate_activity_to_new_version: bool = True, synapse_client: Optional[Synapse] = None) -> TableUpdateTransaction
Creates a snapshot of the View
-like entity.
Synapse handles snapshot creation differently for Table
- and View
-like
entities. View
snapshots are created using the asyncronous job API.
Making a snapshot of a view allows you to create an immutable version of the view at the time of the snapshot. This is useful to create checkpoints in time that you may go back and reference, or use in a publication. Snapshots are immutable and cannot be changed. They may only be deleted.
PARAMETER | DESCRIPTION |
---|---|
comment
|
A unique comment to associate with the snapshot. |
label
|
A unique label to associate with the snapshot. If this is not a unique label an exception will be raised when you store this to Synapse. |
include_activity
|
If True the activity will be included in snapshot if it
exists. In order to include the activity, the activity must have already
been stored in Synapse by using the
TYPE:
|
associate_activity_to_new_version
|
If True the activity will be associated with the new version of the table. If False the activity will not be associated with the new version of the table. Defaults to True.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
TableUpdateTransaction
|
A |
Creating a snapshot of a view with an activity
Create a snapshot of a view and include the activity. The activity must
have been stored in Synapse by using the activity
attribute on the EntityView
and calling the store()
method on the EntityView instance. Adding an activity
to a snapshot of a entityview is meant to capture the provenance of the data at
the time of the snapshot.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
view = EntityView(id="syn4567")
snapshot = view.snapshot(label="Q1 2025", comment="Results collected in Lab A", include_activity=True, associate_activity_to_new_version=True)
print(snapshot)
Creating a snapshot of a view without an activity
Create a snapshot of a view without including the activity. This is used in cases where we do not have any Provenance to associate with the snapshot and we do not want to persist any activity that may be present on the view to the new version of the view.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
view = EntityView(id="syn4567")
snapshot = view.snapshot(label="Q1 2025", comment="Results collected in Lab A", include_activity=False, associate_activity_to_new_version=False)
print(snapshot)
Source code in synapseclient/models/entityview.py
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 |
|
add_column
¶
Add column(s) to the entityview. Note that this does not store the column(s) in
Synapse. You must call the .store()
function on this entityview class instance to
store the column(s) in Synapse. This is a convenience function to eliminate
the need to manually add the column(s) to the dictionary.
This function will add an item to the .columns
attribute of this class
instance. .columns
is a dictionary where the key is the name of the column
and the value is the Column object.
PARAMETER | DESCRIPTION |
---|---|
column
|
The column(s) to add, may be a single Column object or a list of Column objects. |
index
|
The index to insert the column at. If not passed in the column will be added to the end of the list.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Adding a single column
This example shows how you may add a single column to a entityview and then store the change back in Synapse.
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
entityview = EntityView(
id="syn1234"
).get(include_columns=True)
entityview.add_column(
Column(name="my_column", column_type=ColumnType.STRING)
)
entityview.store()
Adding multiple columns
This example shows how you may add multiple columns to a entityview and then store the change back in Synapse.
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
entityview = EntityView(
id="syn1234"
).get(include_columns=True)
entityview.add_column([
Column(name="my_column", column_type=ColumnType.STRING),
Column(name="my_column2", column_type=ColumnType.INTEGER),
])
entityview.store()
Adding a column at a specific index
This example shows how you may add a column at a specific index to a entityview and then store the change back in Synapse. If the index is out of bounds the column will be added to the end of the list.
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
entityview = EntityView(
id="syn1234"
).get(include_columns=True)
entityview.add_column(
Column(name="my_column", column_type=ColumnType.STRING),
# Add the column at the beginning of the list
index=0
)
entityview.store()
Adding a single column (async)
This example shows how you may add a single column to a entityview and then store the change back in Synapse.
import asyncio
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
async def main():
entityview = await EntityView(
id="syn1234"
).get_async(include_columns=True)
entityview.add_column(
Column(name="my_column", column_type=ColumnType.STRING)
)
await entityview.store_async()
asyncio.run(main())
Adding multiple columns (async)
This example shows how you may add multiple columns to a entityview and then store the change back in Synapse.
import asyncio
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
async def main():
entityview = await EntityView(
id="syn1234"
).get_async(include_columns=True)
entityview.add_column([
Column(name="my_column", column_type=ColumnType.STRING),
Column(name="my_column2", column_type=ColumnType.INTEGER),
])
await entityview.store_async()
asyncio.run(main())
Adding a column at a specific index (async)
This example shows how you may add a column at a specific index to a entityview and then store the change back in Synapse. If the index is out of bounds the column will be added to the end of the list.
import asyncio
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
async def main():
entityview = await EntityView(
id="syn1234"
).get_async(include_columns=True)
entityview.add_column(
Column(name="my_column", column_type=ColumnType.STRING),
# Add the column at the beginning of the list
index=0
)
await entityview.store_async()
asyncio.run(main())
Source code in synapseclient/models/entityview.py
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 |
|
reorder_column
¶
Reorder a column in the entityview. Note that this does not store the column in
Synapse. You must call the .store()
function on this entityview class instance to
store the column in Synapse. This is a convenience function to eliminate
the need to manually reorder the .columns
attribute dictionary.
You must ensure that the index is within the bounds of the number of columns in the entityview. If you pass in an index that is out of bounds the column will be added to the end of the list.
PARAMETER | DESCRIPTION |
---|---|
name
|
The name of the column to reorder.
TYPE:
|
index
|
The index to move the column to starting with 0.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Reordering a column
This example shows how you may reorder a column in a entityview and then store the change back in Synapse.
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
entityview = EntityView(
id="syn1234"
).get(include_columns=True)
# Move the column to the beginning of the list
entityview.reorder_column(name="my_column", index=0)
entityview.store()
Reordering a column (async)
This example shows how you may reorder a column in a entityview and then store the change back in Synapse.
import asyncio
from synapseclient import Synapse
from synapseclient.models import Column, ColumnType, EntityView
syn = Synapse()
syn.login()
async def main():
entityview = await EntityView(
id="syn1234"
).get_async(include_columns=True)
# Move the column to the beginning of the list
entityview.reorder_column(name="my_column", index=0)
entityview.store_async()
asyncio.run(main())
Source code in synapseclient/models/entityview.py
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 |
|
delete_column
¶
delete_column(name: str) -> None
Mark a column for deletion. Note that this does not delete the column from
Synapse. You must call the .store()
function on this entityview class instance to
delete the column from Synapse. This is a convenience function to eliminate
the need to manually delete the column from the dictionary and add it to the
._columns_to_delete
attribute.
PARAMETER | DESCRIPTION |
---|---|
name
|
The name of the column to delete.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Deleting a column
This example shows how you may delete a column from a entityview and then store the change back in Synapse.
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
entityview = EntityView(
id="syn1234"
).get(include_columns=True)
entityview.delete_column(name="my_column")
entityview.store()
Deleting a column (async)
This example shows how you may delete a column from a entityview and then store the change back in Synapse.
import asyncio
from synapseclient import Synapse
from synapseclient.models import EntityView
syn = Synapse()
syn.login()
async def main():
entityview = await EntityView(
id="syn1234"
).get_async(include_columns=True)
entityview.delete_column(name="my_column")
await entityview.store_async()
asyncio.run(main())
Source code in synapseclient/models/entityview.py
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 |
|
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 |
|
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 |
|
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.api.ViewTypeMask
¶
Bit mask representing the types to include in the view. As defined in the Synapse REST API: https://rest-docs.synapse.org/rest/GET/column/tableview/defaults.html
Source code in synapseclient/api/table_services.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|