SG API - bootstrap and get context from filepath

Hi,

I wanted to create a small script that allows me to get a shotgun context only from a given file path (no engine available). I found some topics about the bootstrap API and was kind of able to get it working with the following code (I am working with a distributed config):

import sgtk // from centralized tk-core on the server
import shotgun_api3 // also from tk-core

path_to_file = "xyz"
project_name = "TEST_PROJECT" // I can extract that from the path_to_file at any time

# get sg
sg = shotgun_api3.shotgun.Shotgun(
    base_url=sg_base_url,
    script_name="sg_script_name",
    api_key=sg_api_key)

# get project entity based on project name
project_entity = sg.find_one("Project", [["name", "is", project_name]], ["id"])

# start up a Toolkit Manager
mgr = sgtk.bootstrap.ToolkitManager()
mgr.plugin_id = "basic.shotgun"

# use the primary config
mgr.base_configuration = "sgtk:descriptor:shotgun?entity_type=PipelineConfiguration&name=Primary&field=sg_uploaded_config"

# start engine
engine = mgr.bootstrap_engine("tk-shotgun", entity=project_entity)

# get tk and context
tk = engine.sgtk
ctx = tk.context_from_path(path_to_file)

It gives me the right context so far, but I am not quite sure about my approach.
Before I go too far with my scripts, would that be a valid way to go here?

Thanks,
cheers

Sebastian

2 Likes

I believe you’re pretty much on the right track

There is still the conceptual problem that you have to extract the project name from the path before bootstrapping, which is not exactly standardized, and something you have to implement, probably for various platforms, etc.
Not proposing an answer - we do the same, but I find it slightly problematic.

2 Likes

thanks for the answer - yes, indeed thats not the most elegant solution - but for now I cant think about another way - only given a string file path. luckily we already have some helper functions that return the project name - probably enough for now…

cheers
Sebastian

1 Like