Skip to content

context_tools

Core pipeline functionality

change_current_context(folder_entity, task_entity, template_key=None)

Update active Session to a new task work area.

This updates the live Session to a different task under folder.

Parameters:

Name Type Description Default
folder_entity Dict[str, Any]

Folder entity to set.

required
task_entity Dict[str, Any]

Task entity to set.

required
template_key Union[str, None]

Prepared template key to be used for workfile template in Anatomy.

None

Returns:

Type Description

Dict[str, str]: The changed key, values in the current Session.

Source code in client/ayon_core/pipeline/context_tools.py
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
def change_current_context(folder_entity, task_entity, template_key=None):
    """Update active Session to a new task work area.

    This updates the live Session to a different task under folder.

    Args:
        folder_entity (Dict[str, Any]): Folder entity to set.
        task_entity (Dict[str, Any]): Task entity to set.
        template_key (Union[str, None]): Prepared template key to be used for
            workfile template in Anatomy.

    Returns:
        Dict[str, str]: The changed key, values in the current Session.
    """

    project_name = get_current_project_name()
    workdir = None
    folder_path = None
    task_name = None
    if folder_entity:
        folder_path = folder_entity["path"]
        if task_entity:
            task_name = task_entity["name"]
        project_entity = ayon_api.get_project(project_name)
        host_name = get_current_host_name()
        workdir = get_workdir(
            project_entity,
            folder_entity,
            task_entity,
            host_name,
            template_key=template_key
        )

    envs = {
        "AYON_PROJECT_NAME": project_name,
        "AYON_FOLDER_PATH": folder_path,
        "AYON_TASK_NAME": task_name,
        "AYON_WORKDIR": workdir,
    }

    # Update the Session and environments. Pop from environments all keys with
    # value set to None.
    for key, value in envs.items():
        if value is None:
            os.environ.pop(key, None)
        else:
            os.environ[key] = value

    data = envs.copy()

    # Convert env keys to human readable keys
    data["project_name"] = project_name
    data["folder_path"] = folder_path
    data["task_name"] = task_name
    data["workdir_path"] = workdir

    # Emit session change
    emit_event("taskChanged", data)

    return data

get_current_context_custom_workfile_template(project_settings=None)

Filter and fill workfile template profiles by current context.

This function can be used only inside host where current context is set.

Parameters:

Name Type Description Default
project_settings Optional[dict[str, Any]]

Project settings

None

Returns:

Name Type Description
str

Path to template or None if none of profiles match current context. (Existence of formatted path is not validated.)

Source code in client/ayon_core/pipeline/context_tools.py
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def get_current_context_custom_workfile_template(project_settings=None):
    """Filter and fill workfile template profiles by current context.

    This function can be used only inside host where current context is set.

    Args:
        project_settings (Optional[dict[str, Any]]): Project settings

    Returns:
        str: Path to template or None if none of profiles match current
            context. (Existence of formatted path is not validated.)

    """
    context = get_current_context()
    return get_custom_workfile_template_by_string_context(
        context["project_name"],
        context["folder_path"],
        context["task_name"],
        get_current_host_name(),
        project_settings=project_settings
    )

get_current_context_template_data(settings=None)

Prepare template data for current context.

Parameters:

Name Type Description Default
settings Optional[Dict[str, Any]]

Prepared studio or project settings.

None

Returns:

Type Description

Dict[str, Any] Template data for current context.

Source code in client/ayon_core/pipeline/context_tools.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def get_current_context_template_data(settings=None):
    """Prepare template data for current context.

    Args:
        settings (Optional[Dict[str, Any]]): Prepared studio or
            project settings.

    Returns:
        Dict[str, Any] Template data for current context.
    """

    context = get_current_context()
    project_name = context["project_name"]
    folder_path = context["folder_path"]
    task_name = context["task_name"]
    host_name = get_current_host_name()

    return get_template_data_with_names(
        project_name, folder_path, task_name, host_name, settings
    )

get_current_folder_entity(fields=None)

Helper function to get folder entity based on current context.

This function should be called only in process where host is installed.

Folder is based on current context project name and folder path.

Parameters:

Name Type Description Default
fields Optional[Iterable[str]]

Limit returned data of folder entity to specific keys.

None

Returns:

Type Description

Union[dict[str, Any], None]: Folder entity or None.

Source code in client/ayon_core/pipeline/context_tools.py
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
def get_current_folder_entity(fields=None):
    """Helper function to get folder entity based on current context.

    This function should be called only in process where host is installed.

    Folder is based on current context project name and folder path.

    Args:
        fields (Optional[Iterable[str]]): Limit returned data of folder entity
            to specific keys.

    Returns:
        Union[dict[str, Any], None]: Folder entity or None.

    """
    context = get_current_context()
    project_name = context["project_name"]
    folder_path = context["folder_path"]

    # Skip if is not set even on context
    if not project_name or not folder_path:
        return None
    return ayon_api.get_folder_by_path(
        project_name, folder_path, fields=fields
    )

get_current_host_name()

Current host name.

Function is based on currently registered host integration or environment variable 'AYON_HOST_NAME'.

Returns:

Type Description

Union[str, None]: Name of host integration in current process or None.

Source code in client/ayon_core/pipeline/context_tools.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
def get_current_host_name():
    """Current host name.

    Function is based on currently registered host integration or environment
    variable 'AYON_HOST_NAME'.

    Returns:
        Union[str, None]: Name of host integration in current process or None.
    """

    host = registered_host()
    if isinstance(host, HostBase):
        return host.name
    return os.environ.get("AYON_HOST_NAME")

get_current_project_entity(fields=None)

Helper function to get project document based on global Session.

This function should be called only in process where host is installed.

Parameters:

Name Type Description Default
fields Optional[Iterable[str]]

Limit returned data of project entity.

None

Returns:

Type Description

Union[dict[str, Any], None]: Project entity of current project or None.

Source code in client/ayon_core/pipeline/context_tools.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
def get_current_project_entity(fields=None):
    """Helper function to get project document based on global Session.

    This function should be called only in process where host is installed.

    Args:
        fields (Optional[Iterable[str]]): Limit returned data of project
            entity.

    Returns:
        Union[dict[str, Any], None]: Project entity of current project or None.

    """
    project_name = get_current_project_name()
    return ayon_api.get_project(project_name, fields=fields)

get_current_task_entity(fields=None)

Helper function to get task entity based on current context.

This function should be called only in process where host is installed.

Task is based on current context project name, folder path and task name.

Parameters:

Name Type Description Default
fields Optional[Iterable[str]]

Limit returned data of task entity to specific keys.

None

Returns:

Type Description

Union[dict[str, Any], None]: Task entity or None.

Source code in client/ayon_core/pipeline/context_tools.py
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
def get_current_task_entity(fields=None):
    """Helper function to get task entity based on current context.

    This function should be called only in process where host is installed.

    Task is based on current context project name, folder path
        and task name.

    Args:
        fields (Optional[Iterable[str]]): Limit returned data of task entity
            to specific keys.

    Returns:
        Union[dict[str, Any], None]: Task entity or None.

    """
    context = get_current_context()
    project_name = context["project_name"]
    folder_path = context["folder_path"]
    task_name = context["task_name"]

    # Skip if is not set even on context
    if not project_name or not folder_path or not task_name:
        return None
    folder_entity = ayon_api.get_folder_by_path(
        project_name, folder_path, fields={"id"}
    )
    if not folder_entity:
        return None
    return ayon_api.get_task_by_name(
        project_name, folder_entity["id"], task_name, fields=fields
    )

get_global_context()

Global context defined in environment variables.

Values here may not reflect current context of host integration. The function can be used on startup before a host is registered.

Use 'get_current_context' to make sure you'll get current host integration context info.

Example::

{
    "project_name": "Commercial",
    "folder_path": "Bunny",
    "task_name": "Animation",
}

Returns:

Type Description

dict[str, Union[str, None]]: Context defined with environment variables.

Source code in client/ayon_core/pipeline/context_tools.py
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
def get_global_context():
    """Global context defined in environment variables.

    Values here may not reflect current context of host integration. The
    function can be used on startup before a host is registered.

    Use 'get_current_context' to make sure you'll get current host integration
    context info.

    Example::

        {
            "project_name": "Commercial",
            "folder_path": "Bunny",
            "task_name": "Animation",
        }

    Returns:
        dict[str, Union[str, None]]: Context defined with environment
            variables.
    """

    return {
        "project_name": os.environ.get("AYON_PROJECT_NAME"),
        "folder_path": os.environ.get("AYON_FOLDER_PATH"),
        "task_name": os.environ.get("AYON_TASK_NAME"),
    }

get_process_id()

Fake process id created on demand using uuid.

Can be used to create process specific folders in temp directory.

Returns:

Name Type Description
str

Process id.

Source code in client/ayon_core/pipeline/context_tools.py
569
570
571
572
573
574
575
576
577
578
579
580
581
def get_process_id():
    """Fake process id created on demand using uuid.

    Can be used to create process specific folders in temp directory.

    Returns:
        str: Process id.
    """

    global _process_id
    if _process_id is None:
        _process_id = str(uuid.uuid4())
    return _process_id

install_ayon_plugins(project_name=None, host_name=None)

Install AYON core plugins and make sure the core is initialized.

Parameters:

Name Type Description Default
project_name Optional[str]

Name of project to install plugins for.

None
host_name Optional[str]

Name of host to install plugins for.

None
Source code in client/ayon_core/pipeline/context_tools.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
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
def install_ayon_plugins(project_name=None, host_name=None):
    """Install AYON core plugins and make sure the core is initialized.

    Args:
        project_name (Optional[str]): Name of project to install plugins for.
        host_name (Optional[str]): Name of host to install plugins for.

    """
    # Make sure global AYON connection has set site id and version
    # - this is necessary if 'install_host' is not called
    initialize_ayon_connection()
    # Make sure addons are loaded
    load_addons()

    log.info("Registering global plug-ins..")
    pyblish.api.register_plugin_path(PUBLISH_PATH)
    pyblish.api.register_discovery_filter(filter_pyblish_plugins)
    register_loader_plugin_path(LOAD_PATH)
    register_inventory_action_path(INVENTORY_PATH)

    if host_name is None:
        host_name = os.environ.get("AYON_HOST_NAME")

    addons_manager = _get_addons_manager()
    publish_plugin_dirs = addons_manager.collect_publish_plugin_paths(
        host_name)
    for path in publish_plugin_dirs:
        pyblish.api.register_plugin_path(path)

    create_plugin_paths = addons_manager.collect_create_plugin_paths(
        host_name)
    for path in create_plugin_paths:
        register_creator_plugin_path(path)

    load_plugin_paths = addons_manager.collect_load_plugin_paths(
        host_name)
    for path in load_plugin_paths:
        register_loader_plugin_path(path)

    inventory_action_paths = addons_manager.collect_inventory_action_paths(
        host_name)
    for path in inventory_action_paths:
        register_inventory_action_path(path)

    if project_name is None:
        project_name = os.environ.get("AYON_PROJECT_NAME")

    # Register studio specific plugins
    if project_name:
        anatomy = Anatomy(project_name)
        anatomy.set_root_environments()
        register_root(anatomy.roots)

        project_settings = get_project_settings(project_name)
        platform_name = platform.system().lower()
        project_plugins = (
            project_settings
            ["core"]
            ["project_plugins"]
            .get(platform_name)
        ) or []
        for path in project_plugins:
            try:
                path = str(path.format(**os.environ))
            except KeyError:
                pass

            if not path or not os.path.exists(path):
                continue

            pyblish.api.register_plugin_path(path)
            register_loader_plugin_path(path)
            register_creator_plugin_path(path)
            register_inventory_action_path(path)

install_host(host)

Install host into the running Python session.

Parameters:

Name Type Description Default
host HostBase

A host interface object.

required
Source code in client/ayon_core/pipeline/context_tools.py
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
def install_host(host):
    """Install `host` into the running Python session.

    Args:
        host (HostBase): A host interface object.

    """
    global _is_installed

    _is_installed = True

    # Make sure global AYON connection has set site id and version
    initialize_ayon_connection()

    addons_manager = _get_addons_manager()

    project_name = os.getenv("AYON_PROJECT_NAME")
    # WARNING: This might be an issue
    #   - commented out because 'traypublisher' does not have set project
    # if not project_name:
    #     raise ValueError(
    #         "AYON_PROJECT_NAME is missing in environment variables."
    #     )

    log.info("Activating {}..".format(project_name))

    # Optional host install function
    if hasattr(host, "install"):
        host.install()

    register_host(host)

    def modified_emit(obj, record):
        """Method replacing `emit` in Pyblish's MessageHandler."""
        try:
            record.msg = record.getMessage()
        except Exception:
            record.msg = str(record.msg)
        obj.records.append(record)

    MessageHandler.emit = modified_emit

    if os.environ.get("AYON_REMOTE_PUBLISH"):
        # target "farm" == rendering on farm, expects AYON_PUBLISH_DATA
        # target "remote" == remote execution, installs host
        print("Registering pyblish target: remote")
        pyblish.api.register_target("remote")
    else:
        pyblish.api.register_target("local")

    if is_in_tests():
        print("Registering pyblish target: automated")
        pyblish.api.register_target("automated")

    host_name = os.environ.get("AYON_HOST_NAME")

    # Give option to handle host installation
    for addon in addons_manager.get_enabled_addons():
        addon.on_host_install(host, host_name, project_name)

    install_ayon_plugins(project_name, host_name)

is_installed()

Return state of installation

Returns:

Type Description

True if installed, False otherwise

Source code in client/ayon_core/pipeline/context_tools.py
261
262
263
264
265
266
267
268
269
def is_installed():
    """Return state of installation

    Returns:
        True if installed, False otherwise

    """

    return _is_installed

is_representation_from_latest(representation)

Return whether the representation is from latest version

Parameters:

Name Type Description Default
representation dict

The representation document from the database.

required

Returns:

Name Type Description
bool

Whether the representation is of latest version.

Source code in client/ayon_core/pipeline/context_tools.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
def is_representation_from_latest(representation):
    """Return whether the representation is from latest version

    Args:
        representation (dict): The representation document from the database.

    Returns:
        bool: Whether the representation is of latest version.
    """

    project_name = get_current_project_name()
    return ayon_api.version_is_latest(
        project_name, representation["versionId"]
    )

register_host(host)

Register a new host for the current process

Parameters:

Name Type Description Default
host ModuleType

A module implementing the Host API interface. See the Host API documentation for details on what is required, or browse the source code.

required
Source code in client/ayon_core/pipeline/context_tools.py
272
273
274
275
276
277
278
279
280
281
282
283
def register_host(host):
    """Register a new host for the current process

    Arguments:
        host (ModuleType): A module implementing the
            Host API interface. See the Host API
            documentation for details on what is
            required, or browse the source code.

    """

    _registered_host["_"] = host

register_root(path)

Register currently active root

Source code in client/ayon_core/pipeline/context_tools.py
76
77
78
79
def register_root(path):
    """Register currently active root"""
    log.info("Registering root: %s" % path)
    _registered_root["_"] = path

registered_host()

Return currently registered host

Source code in client/ayon_core/pipeline/context_tools.py
286
287
288
def registered_host():
    """Return currently registered host"""
    return _registered_host["_"]

registered_root()

Return registered roots from current project anatomy.

Consider this does return roots only for current project and current platforms, only if host was installer using 'install_host'.

Deprecated

Please use project 'Anatomy' to get roots. This function is still used at current core functions of load logic, but that will change in future and this function will be removed eventually. Using this function at new places can cause problems in the future.

Returns:

Type Description

dict[str, str]: Root paths.

Source code in client/ayon_core/pipeline/context_tools.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def registered_root():
    """Return registered roots from current project anatomy.

    Consider this does return roots only for current project and current
        platforms, only if host was installer using 'install_host'.

    Deprecated:
        Please use project 'Anatomy' to get roots. This function is still used
            at current core functions of load logic, but that will change
            in future and this function will be removed eventually. Using this
            function at new places can cause problems in the future.

    Returns:
        dict[str, str]: Root paths.
    """

    return _registered_root["_"]

uninstall_host()

Undo all of what install() did

Source code in client/ayon_core/pipeline/context_tools.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def uninstall_host():
    """Undo all of what `install()` did"""
    host = registered_host()

    try:
        host.uninstall()
    except AttributeError:
        pass

    log.info("Deregistering global plug-ins..")
    pyblish.api.deregister_plugin_path(PUBLISH_PATH)
    pyblish.api.deregister_discovery_filter(filter_pyblish_plugins)
    deregister_loader_plugin_path(LOAD_PATH)
    deregister_inventory_action_path(INVENTORY_PATH)
    log.info("Global plug-ins unregistred")

    deregister_host()

    log.info("Successfully uninstalled Avalon!")

version_up_current_workfile()

Function to increment and save workfile

Source code in client/ayon_core/pipeline/context_tools.py
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
def version_up_current_workfile():
    """Function to increment and save workfile
    """
    host = registered_host()

    project_name = get_current_project_name()
    folder_path = get_current_folder_path()
    task_name = get_current_task_name()
    host_name = get_current_host_name()

    template_key = get_workfile_template_key_from_context(
        project_name,
        folder_path,
        task_name,
        host_name,
    )
    anatomy = Anatomy(project_name)

    data = get_template_data_with_names(
        project_name, folder_path, task_name, host_name
    )
    data["root"] = anatomy.roots

    work_template = anatomy.get_template_item("work", template_key)

    # Define saving file extension
    extensions = host.get_workfile_extensions()
    current_file = host.get_current_workfile()
    if current_file:
        extensions = [os.path.splitext(current_file)[-1]]

    work_root = work_template["directory"].format_strict(data)
    file_template = work_template["file"].template
    last_workfile_path = get_last_workfile(
        work_root, file_template, data, extensions, True
    )
    new_workfile_path = version_up(last_workfile_path)
    if os.path.exists(new_workfile_path):
        new_workfile_path = version_up(new_workfile_path)
    host.save_workfile(new_workfile_path)