Project¶
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 a project
"""
Expects that ~/temp exists and is a directory.
The purpose of this script is to demonstrate how to use the new OOP interface for projects.
The following actions are shown in this script:
1. Creating a project
2. Retrieving a project by id or name
3. Upserting data on a project
4. Storing several files to a project
5. Storing several folders in a project
6. Updating the annotations in bulk for a number of folders and files
7. Downloading an entire project structure to disk
8. Copy a project and all content to a new project
9. Deleting a project
"""
import os
import uuid
from datetime import date, datetime, timedelta, timezone
import synapseclient
from synapseclient.models import File, Folder, Project
syn = synapseclient.Synapse(debug=True)
syn.login()
def create_random_file(
path: str,
) -> None:
"""Create a random file with random data."""
with open(path, "wb") as f:
f.write(os.urandom(1))
def store_project():
# Creating annotations for my project ==================================================
my_annotations = {
"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))),
],
"annotation_i_want_to_delete": "I want to delete this annotation",
}
# 1) Creating a project ==============================================================
project = Project(
name="my_new_project_for_testing",
annotations=my_annotations,
description="This is a project with random data.",
alias="my_project_alias_" + str(uuid.uuid4()).replace("-", "_"),
)
project = project.store()
print(f"Project created with id: {project.id}")
# 2) Retrieving a project by id or name ==============================================
project = Project(name="my_new_project_for_testing").get()
print(f"Project retrieved by name: {project.name} with id: {project.id}")
project = Project(id=project.id).get()
print(f"Project retrieved by id: {project.name} with id: {project.id}")
# 3) Upserting data on a project =====================================================
# When you have not already use `.store()` or `.get()` on a project any updates will
# be a non-destructive upsert. This means that if the project does not exist it will
# be created, if it does exist it will be updated.
project = Project(
name="my_new_project_for_testing", description="my new description"
).store()
print(f"Project description updated to {project.description}")
# After the instance has interacted with Synapse any changes will be destructive,
# meaning changes in the data will act as a replacement instead of an addition.
print(f"Annotations before update: {project.annotations}")
del project.annotations["annotation_i_want_to_delete"]
project = project.store()
print(f"Annotations after update: {project.annotations}")
# 4) Storing several files to a project ==============================================
files_to_store = []
for loop in range(1, 10):
name_of_file = f"my_file_with_random_data_{loop}.txt"
path_to_file = os.path.join(os.path.expanduser("~/temp"), name_of_file)
create_random_file(path_to_file)
file = File(
path=path_to_file,
name=name_of_file,
annotations=my_annotations,
)
files_to_store.append(file)
project.files = files_to_store
project = project.store()
# 5) Storing several folders in a project ============================================
folders_to_store = []
for loop in range(1, 10):
folder_to_store = Folder(
name=f"my_folder_for_this_project_{loop}",
annotations=my_annotations,
)
folders_to_store.append(folder_to_store)
project.folders = folders_to_store
print(
f"Storing project ({project.id}) with {len(project.folders)} folders and {len(project.files)} files"
)
project = project.store()
# 6) Updating the annotations in bulk for a number of folders and files ==============
project_copy = Project(id=project.id).sync_from_synapse(download_file=False)
print(
f"Found {len(project_copy.files)} files and {len(project_copy.folders)} folder at the root level for {project_copy.name} with id: {project_copy.id}"
)
new_annotations = {
"my_new_key_string": ["b", "a", "c"],
}
for file in project_copy.files:
file.annotations = new_annotations
for folder in project_copy.folders:
folder.annotations = new_annotations
project_copy.store()
# 7) Downloading an entire project structure to disk =================================
print(f"Downloading project ({project.id}) to ~/temp")
Project(id=project.id).sync_from_synapse(
download_file=True, path="~/temp/recursiveDownload", recursive=True
)
# 8) Copy a project and all content to a new project =================================
project_to_delete = Project(
name="my_new_project_I_want_to_delete_" + str(uuid.uuid4()).replace("-", "_"),
).store()
print(f"Project created with id: {project_to_delete.id}")
project_to_delete = project.copy(destination_id=project_to_delete.id)
print(
f"Copied to new project, copied {len(project_to_delete.folders)} folders and {len(project_to_delete.files)} files"
)
# 9) Deleting a project ==============================================================
project_to_delete.delete()
print(f"Project with id: {project_to_delete.id} deleted")
store_project()
API reference¶
synapseclient.models.Project
dataclass
¶
Bases: ProjectSynchronousProtocol
, AccessControllable
, StorableContainer
A Project is a top-level container for organizing data in Synapse.
ATTRIBUTE | DESCRIPTION |
---|---|
id |
The unique immutable ID for this project. A new ID will be generated for new Projects. Once issued, this ID is guaranteed to never change or be re-issued |
name |
The name of this project. 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 entity was created. |
modified_on |
The date this entity was last modified. |
created_by |
The ID of the user that created this entity. |
modified_by |
The ID of the user that last modified this entity. |
alias |
The project alias for use in friendly project urls. |
files |
Any files that are at the root directory of the project. |
folders |
Any folders that are at the root directory of the project. |
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:
|
create_or_update |
(Store only) Indicates whether the method should automatically perform an update if the resource conflicts with an existing Synapse object. When True this means that any changes to the resource will be non-destructive. This boolean is ignored if you've already stored or retrieved the resource
from Synapse for this instance at least once. Any changes to the resource
will be destructive in this case. For example if you want to delete the
content for a field you will need to call
TYPE:
|
parent_id |
The parent ID of the project. In practice projects do not have a parent, but this is required for the inner workings of Synapse. |
Creating a project
This example shows how to create a project
from synapseclient.models import Project, File
import synapseclient
synapseclient.login()
my_annotations = {
"my_single_key_string": "a",
"my_key_string": ["b", "a", "c"],
}
project = Project(
name="My unique project name",
annotations=my_annotations,
description="This is a project with random data.",
)
project = project.store()
print(project)
Storing several files to a project
This example shows how to store several files to a project
file_1 = File(
path=path_to_file_1,
name=name_of_file_1,
)
file_2 = File(
path=path_to_file_2,
name=name_of_file_2,
)
project.files = [file_1, file_2]
project = project.store()
Source code in synapseclient/models/project.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 |
|
Functions¶
get
¶
Get the project metadata from Synapse.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Project
|
The project object. |
Using this method
Retrieve the project from Synapse using ID
project = Project(id="syn123").get()
Retrieve the project from Synapse using Name
project = Project(name="my_project").get()
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the project ID or Name is not set. |
SynapseNotFoundError
|
If the project is not found in Synapse. |
Source code in synapseclient/models/protocols/project_protocol.py
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 |
|
store
¶
store(failure_strategy: FailureStrategy = LOG_EXCEPTION, *, synapse_client: Optional[Synapse] = None) -> Project
Store project, files, and folders to synapse. If you have any files or folders
attached to this project they will be stored as well. You may attach files
and folders to this project by setting the files
and folders
attributes.
By default the store operation will non-destructively update the project if
you have not already retrieved the project from Synapse. If you have already
retrieved the project from Synapse then the store operation will be destructive
and will overwrite the project with the current state of this object. See the
create_or_update
attribute for more information.
PARAMETER | DESCRIPTION |
---|---|
failure_strategy
|
Determines how to handle failures when storing attached Files and Folders under this Project and an exception occurs.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Project
|
The project object. |
Using this method to update the description
Store the project to Synapse using ID
project = Project(id="syn123", description="new").store()
Store the project to Synapse using Name
project = Project(name="my_project", description="new").store()
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the project name is not set. |
Source code in synapseclient/models/protocols/project_protocol.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
delete
¶
Delete the project from Synapse.
PARAMETER | DESCRIPTION |
---|---|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
None
|
None |
Using this method
Delete the project from Synapse using ID
Project(id="syn123").delete()
Delete the project from Synapse using Name
Project(name="my_project").delete()
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the project ID or Name is not set. |
SynapseNotFoundError
|
If the project is not found in Synapse. |
Source code in synapseclient/models/protocols/project_protocol.py
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 |
|
sync_from_synapse
¶
sync_from_synapse(path: Optional[str] = None, recursive: bool = True, download_file: bool = True, if_collision: str = COLLISION_OVERWRITE_LOCAL, failure_strategy: FailureStrategy = LOG_EXCEPTION, *, synapse_client: Optional[Synapse] = None) -> Self
Sync this container and all possible sub-folders from Synapse. By default this
will download the files that are found and it will populate the
files
and folders
attributes with the found files and folders. If you only
want to retrieve the full tree of metadata about your container specify
download_file
as False.
This works similar to synapseutils.syncFromSynapse, however, this does not currently support the writing of data to a manifest TSV file. This will be a future enhancement.
Only Files and Folders are supported at this time to be synced from synapse.
PARAMETER | DESCRIPTION |
---|---|
path
|
An optional path where the file hierarchy will be reproduced. If not specified the files will by default be placed in the synapseCache. |
recursive
|
Whether or not to recursively get the entire hierarchy of the folder and sub-folders.
TYPE:
|
download_file
|
Whether to download the files found or not.
TYPE:
|
if_collision
|
Determines how to handle file collisions. May be
TYPE:
|
failure_strategy
|
Determines how to handle failures when retrieving children under this Folder and an exception occurs.
TYPE:
|
synapse_client
|
If not passed in and caching was not disabled by
|
RETURNS | DESCRIPTION |
---|---|
Self
|
The object that was called on. This will be the same object that was called on to start the sync. |
Using this function
Suppose I want to walk the immediate children of a folder without downloading the files:
from synapseclient import Synapse
from synapseclient.models import Folder
syn = Synapse()
syn.login()
my_folder = Folder(id="syn12345")
my_folder.sync_from_synapse(download_file=False, recursive=False)
for folder in my_folder.folders:
print(folder.name)
for file in my_folder.files:
print(file.name)
Suppose I want to download the immediate children of a folder:
from synapseclient import Synapse
from synapseclient.models import Folder
syn = Synapse()
syn.login()
my_folder = Folder(id="syn12345")
my_folder.sync_from_synapse(path="/path/to/folder", recursive=False)
for folder in my_folder.folders:
print(folder.name)
for file in my_folder.files:
print(file.name)
Suppose I want to download the immediate all children of a Project and all sub-folders and files:
from synapseclient import Synapse
from synapseclient.models import Project
syn = Synapse()
syn.login()
my_project = Project(id="syn12345")
my_project.sync_from_synapse(path="/path/to/folder")
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the folder does not have an id set. |
A sequence diagram for this method is as follows:
sequenceDiagram
autonumber
participant project_or_folder
activate project_or_folder
project_or_folder->>sync_from_synapse: Recursive search and download files
activate sync_from_synapse
opt Current instance not retrieved from Synapse
sync_from_synapse->>project_or_folder: Call `.get()` method
project_or_folder-->>sync_from_synapse: .
end
loop For each return of the generator
sync_from_synapse->>client: call `.getChildren()` method
client-->>sync_from_synapse: .
note over sync_from_synapse: Append to a running list
end
loop For each child
note over sync_from_synapse: Create all `pending_tasks` at current depth
alt Child is File
note over sync_from_synapse: Append `file.get()` method
else Child is Folder
note over sync_from_synapse: Append `folder.get()` method
alt Recursive is True
note over sync_from_synapse: Append `folder.sync_from_synapse()` method
end
end
end
loop For each task in pending_tasks
par `file.get()`
sync_from_synapse->>File: Retrieve File metadata and Optionally download
File->>client: `.get()`
client-->>File: .
File-->>sync_from_synapse: .
and `folder.get()`
sync_from_synapse->>Folder: Retrieve Folder metadataa
Folder->>client: `.get()`
client-->>Folder: .
Folder-->>sync_from_synapse: .
and `folder.sync_from_synapse()`
note over sync_from_synapse: This is a recursive call to `sync_from_synapse`
sync_from_synapse->>sync_from_synapse: Recursive call to `.sync_from_synapse()`
end
end
deactivate sync_from_synapse
deactivate project_or_folder
Source code in synapseclient/models/protocols/storable_container_protocol.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
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
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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
get_acl
¶
Get the ACL that a user or group has on an Entity.
PARAMETER | DESCRIPTION |
---|---|
principal_id
|
Identifier of a user or group (defaults to PUBLIC users)
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
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
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
TYPE:
|
warn_if_inherits
|
Set as False, when creating a new ACL. Trying to modify the ACL of an Entity that inherits its ACL will result in a warning
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
File(id="syn123").set_permissions(principal_id=273948, access_type=['READ','DOWNLOAD'])
Grant the public view access
File(id="syn123").set_permissions(principal_id=273949, access_type=['READ'])
Source code in synapseclient/models/protocols/access_control_protocol.py
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 |
|