def connect(self):
        sg = None
        if self.user_auth_method:
            try:
                if not self.__user_token:
                    sg = shotgun_api3.Shotgun(self.__host,
                                              login=self.__user,
                                              password=self.__user_password)
                elif self.__user_token:
                    sg = shotgun_api3.Shotgun(self.__host,
                                              login=self.__user,
                                              token=self.__user_token)
                else:
                    raise RuntimeError(
                        "You must provide a valid user authentication or script authentication."
                    )
            except Exception as e:
                raise RuntimeError(
                    "Error while connect with Shotgun - {}".format(e))
        elif self.script_auth_method:
            try:
                sg = shotgun_api3.Shotgun(
                    self.__host,
                    script_name=self.__script_name,
                    api_key=self.__script_pass,
                )
            except Exception as e:
                raise RuntimeError(
                    "Error while connect with Shotgun - {}".format(e))

        return sg
示例#2
0
 def test_http_proxy_server_and_port_with_authentication(self):
     proxy_server = "someserver.com"
     proxy_port = 1234
     proxy_user = "******"
     proxy_pass = "******"
     http_proxy = "%s:%s@%s:%d" % (proxy_user, proxy_pass, proxy_server,
                                   proxy_port)
     sg = api.Shotgun(self.server_path,
                      self.script_name,
                      self.api_key,
                      http_proxy=http_proxy,
                      connect=False)
     self.assertEquals(sg.config.proxy_server, proxy_server)
     self.assertEquals(sg.config.proxy_port, proxy_port)
     self.assertEquals(sg.config.proxy_user, proxy_user)
     self.assertEquals(sg.config.proxy_pass, proxy_pass)
     proxy_server = "123.456.789.012"
     proxy_port = 1234
     proxy_user = "******"
     proxy_pass = "******"
     http_proxy = "%s:%s@%s:%d" % (proxy_user, proxy_pass, proxy_server,
                                   proxy_port)
     sg = api.Shotgun(self.server_path,
                      self.script_name,
                      self.api_key,
                      http_proxy=http_proxy,
                      connect=False)
     self.assertEquals(sg.config.proxy_server, proxy_server)
     self.assertEquals(sg.config.proxy_port, proxy_port)
     self.assertEquals(sg.config.proxy_user, proxy_user)
     self.assertEquals(sg.config.proxy_pass, proxy_pass)
示例#3
0
文件: base.py 项目: DenTas/python-api
    def setUp(self, auth_mode='ApiUser'):
        self.config = SgTestConfig()
        self.config.read_config(CONFIG_PATH)
        self.human_login = self.config.human_login
        self.human_password = self.config.human_password
        self.server_url = self.config.server_url
        self.script_name = self.config.script_name
        self.api_key = self.config.api_key
        self.http_proxy = self.config.http_proxy
        self.session_uuid = self.config.session_uuid

        if auth_mode == 'ApiUser':
            self.sg = api.Shotgun(self.config.server_url,
                                  self.config.script_name,
                                  self.config.api_key,
                                  http_proxy=self.config.http_proxy,
                                  connect=self.connect)
        elif auth_mode == 'HumanUser':
            self.sg = api.Shotgun(self.config.server_url,
                                  login=self.human_login,
                                  password=self.human_password,
                                  http_proxy=self.config.http_proxy,
                                  connect=self.connect)
        else:
            raise ValueError("Unknown value for auth_mode: %s" % auth_mode)

        if self.config.session_uuid:
            self.sg.set_session_uuid(self.config.session_uuid)
示例#4
0
    def test_bad_auth(self):
        '''test_bad_auth invalid script name or api key raises fault'''
        server_url = self.config.server_url
        script_name = 'not_real_script_name'
        api_key = self.config.api_key
        sg = shotgun_api3.Shotgun(server_url, script_name, api_key)
        self.assertRaises(shotgun_api3.Fault, sg.find_one, 'Shot', [])

        script_name = self.config.script_name
        api_key = 'notrealapikey'
        sg = shotgun_api3.Shotgun(server_url, script_name, api_key)
        self.assertRaises(shotgun_api3.Fault, sg.find_one, 'Shot', [])
示例#5
0
文件: utils.py 项目: vfxetc/sgsession
def shotgun_api3_connect(*args, **kwargs):

    eps = []
    for ep in pkg_resources.iter_entry_points('shotgun_api3_connect'):
        eps.append((ep, True))
    for ep in pkg_resources.iter_entry_points('shotgun_api3_kwargs'):
        eps.append((ep, False))
    eps.sort(key=lambda (ep, _): ep.name)

    for ep, is_direct in eps:

        func = ep.load()
        res = func(*args, **kwargs)
        if not res:
            continue

        if is_direct:
            return res

        import shotgun_api3
        return shotgun_api3.Shotgun(**res)

    # Fall back onto the shotgun_api3_registry module.
    try:
        import shotgun_api3_registry as m
    except ImportError:
        pass
    else:
        return m.connect(*args, **kwargs)

    raise ValueError(
        "No shotgun_api3_connect/shotgun_api3_kwargs entry point or shotgun_api3_registry module found."
    )
def registerCallbacks(reg):
    """
    Register our callbacks.

    :param reg: A Registrar instance provided by the event loop handler.
    """

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(SERVER, script_name=SCRIPT_NAME, api_key=SCRIPT_KEY)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    eventFilter = {
        "Shotgun_Version_Change": ["sg_uploaded_movie"],
    }
    # Temp solution for remote artist
    args = {
        "applied_group": "Remote Artists",
    }
    # Register our callback with the Shotgun_Version_Change event
    reg.registerCallback(
        SCRIPT_NAME,
        SCRIPT_KEY,
        download_submission,
        eventFilter,
        args,
    )
    reg.logger.debug("Registered callback.")
示例#7
0
    def test_url(self):
        """Server url is parsed correctly"""
        login = self.human_user['login']
        password = self.human_password

        self.assertRaises(ValueError,
                          api.Shotgun,
                          None,
                          None,
                          None,
                          connect=False)
        self.assertRaises(ValueError,
                          api.Shotgun,
                          "file://foo.com",
                          None,
                          None,
                          connect=False)

        self.assertEqual("/api3/json", self.sg.config.api_path)

        #support auth details in the url of the form
        login_password = "******" % (login, password)
        # login:password@domain
        auth_url = "%s%s@%s" % (self.uri_prefix, login_password, self.domain)
        sg = api.Shotgun(auth_url, None, None, connect=False)
        expected = "Basic " + base64.encodestring(
            urllib.unquote(login_password)).strip()
        self.assertEqual(expected, sg.config.authorization)
示例#8
0
def registerCallbacks(reg):
    """
    Register our callbacks.
    :param reg: A Registrar instance provided by the event loop handler.
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SGDAEMON_ASSIGNTOPROJECT_NAME"]
    script_key = os.environ["SGDAEMON_ASSIGNTOPROJECT_KEY"]

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    # Register our callback with the Shotgun_%s_Change event and tell the logger
    # about it.
    reg.registerCallback(
        script_name,
        script_key,
        chief_cmt,
        {"Shotgun_Note_Change": "user"
         },  #, ['user', 'is', {'type':'HumanUser', 'id':'yizeon' }]
        None,
    )
    reg.logger.debug("Registered callback.")
示例#9
0
    def _connect_to_sg(self):
        """
        Adds sg handles to the self._sites dict and removes credentials.
        """

        # Grab a Python API handle for each Shotgun Site and add it to the
        # self._sites dict.
        for site_url, credentials in self._sites.iteritems():

            if not credentials.get("script_name") or not credentials.get(
                    "script_key"):
                raise ValueError(
                    "Bad or missing settings for %s in settings.yml, exiting."
                    % site_url)

            logging.info("Connecting to %s..." % site_url)
            credentials["sg"] = shotgun_api3.Shotgun(
                site_url,
                script_name=credentials["script_name"],
                api_key=credentials["script_key"],
            )

            # We don't need these anymore, so lets clear them out of memory.
            credentials.pop("script_name", None)
            credentials.pop("script_key", None)
示例#10
0
    def __init__(self, configPath):
        """
        """
        self._continue = True
        self._eventIdData = {}

        # Read/parse the config
        config = ConfigParser.ConfigParser()
        config.read(configPath)

        # Get config values
        self._logFactory = self._logFactory = LogFactory(config)
        self._log = self._logFactory.getLogger('engine', emails=True)
        self._pluginCollections = [
            PluginCollection(self, s.strip())
            for s in config.get('plugins', 'paths').split(',')
        ]
        self._server = config.get('shotgun', 'server')
        self._sg = sg.Shotgun(self._server, config.get('shotgun', 'name'),
                              config.get('shotgun', 'key'))
        self._eventIdFile = config.get('daemon', 'eventIdFile')
        self._max_conn_retries = config.getint('daemon', 'max_conn_retries')
        self._conn_retry_sleep = config.getint('daemon', 'conn_retry_sleep')
        self._fetch_interval = config.getint('daemon', 'fetch_interval')
        self._use_session_uuid = config.getboolean('shotgun',
                                                   'use_session_uuid')

        super(Engine, self).__init__('shotgunEvent',
                                     config.get('daemon', 'pidFile'))
示例#11
0
def process(id, name, conf):
    engine = EngineCli("shotgunEventDaemon.conf")

    # Get The EventLogEntry ID
    print(engine.config.getShotgunURL())
    print(engine.config.getEngineScriptName())
    print(engine.config.getEngineScriptKey())

    sgConnection = sg.Shotgun(engine.config.getShotgunURL(),
                              engine.config.getEngineScriptName(),
                              engine.config.getEngineScriptKey())

    event = sgConnection.find_one("EventLogEntry",
                                  [["id", "is", int(id)]],
                                  fields=[
                                      'id', 'event_type', 'attribute_name',
                                      'meta', 'entity', 'user', 'project',
                                      'session_uuid', 'created_at'
                                  ])

    # Initialise the plugin.
    plugcollections = [
        sgED.PluginCollection(engine, s)
        for s in engine.config.getPluginPaths()
    ]

    for plugc in plugcollections:
        plugc.load()

    for plugc in plugcollections:
        plugc.process(event)
def registerCallbacks(reg):
    """
    Register all necessary or appropriate callbacks for this plugin.
    """
    file_object = open(
        r"//genesisnx/genesisnx/Animation/Shotgun/System/Tools/shotgun/create_project_directory.txt",
        "r")

    eventFilter = {
        "Shotgun_Project_Change": ["name", "sg_client", "sg_brand"],
        "Shotgun_Asset_Change": ["code"],
        "Shotgun_Shot_Change": ["code"]
    }
    server = "https://vaynerproductions.shotgunstudio.com"
    script_name = os.path.basename(__file__).split(".")[0] + ".py"
    script_key = file_object.readline()

    file_object.close()

    sg = shotgun_api3.Shotgun(server, script_name, script_key)

    reg.registerCallback(
        script_name,
        script_key,
        create_project_directory,
        eventFilter,
        None,
    )
    reg.logger.debug("Registered callback.")
示例#13
0
def createShotgunNote(PROJECT_ID,shotTable,sendTaskCombo):
    sg = shotgun.Shotgun(SERVER_PATH, SCRIPT_USER, SCRIPT_KEY)
    import getpass
    user=getpass.getuser()
    fields = ['id', 'name','login']
    filters = [['login', 'is',user]]
    userReturn = sg.find_one('HumanUser',filters,fields)
    #get shot id, task id
    #get shot
    shotName=shotTable.selectedItems()[0].text()
    filters = [['project','is', {'type':'Project','id':PROJECT_ID}],['code', 'is',shotName]]
    shot = sg.find_one('Shot',filters)
    task=sendTaskCombo.currentText()
    filters = [ ['entity','is',{'type':'Shot','id':shot['id']}] ,  ['content','is', task]]
    taskID = sg.find_one('Task',filters)
    content=self.notesTextEdit.toPlainText()
    for line in content.split('\n'):
        # enter data here for a note to create
        data = {'subject':task+' Note','content':line,'user':userReturn,'project': {"type":"Project","id": PROJECT_ID},'note_links':[{'type': 'Shot', 'id': shot['id'], 'name':shotName}],'tasks': [{'type': 'Task', 'id': taskID['id'], 'name': task}]}
        # create the note
        noteID = sg.create('Note',data)
    self.notesTextEdit.setPlainText("")
    self.shotgunNotes,self.shotgunShotData=sgMethods.getShotgunData(PROJECT_ID)
    if task=='Composite':
        sg.update('Task', taskID['id'], {'sg_status_list': 'fkd'})
示例#14
0
def resetCompStatus(PROJECT_ID,Sequences):
    sg = shotgun.Shotgun(SERVER_PATH, SCRIPT_USER, SCRIPT_KEY)
    task = nuke.ProgressTask('reseting shotgun comp status:')
    for sq in Sequences:
        fields = ['id', 'code', 'sg_status_list','shots']
        filters = [['project','is', {'type':'Project','id':PROJECT_ID}],['code', 'is',sq]]
        seq = sg.find_one('Sequence',filters,fields)
        for shot in seq['shots']:
            fields = ['id', 'code', 'sg_status_list','open_notes']
            filters = [['id', 'is',shot['id']],['sg_status_list', 'is_not','omt']]
            sh= sg.find_one('Shot',filters,fields)
            if sh:
                fields = ['id', 'code', 'sg_status_list']
                filters = [ ['entity','is',{'type':'Shot','id':sh['id']}] ,  ['content','is', 'Composite' ],['sg_status_list', 'is_not','na'],['sg_status_list', 'is_not','wtg']]
                taskID = sg.find_one('Task',filters,fields)
                task.setMessage(sh['code'])
                if taskID:
                    sg.update('Task', taskID['id'], {'sg_status_list': 'cmpt'})
                    #if notes, change to problem
                    for n in sh['open_notes']:
                        id= n['id']
                        fields = ['sg_status_list','tasks','name']
                        filters = [['id', 'is',id]]
                        note = sg.find_one('Note',filters,fields)
                        for t in note['tasks']:
                            if 'Composite' in t['name']:
                                fields = ['id', 'code', 'sg_status_list']
                                filters = [ ['entity','is',{'type':'Shot','id':sh['id']}] ,  ['content','is', 'Composite' ]]
                                taskID = sg.find_one('Task',filters,fields)
                                sg.update('Task', taskID['id'], {'sg_status_list': 'fkd'})
              
    del(task)
示例#15
0
    def __init__(self, configPath):
        """
        """
        self._continue = True
        self._eventIdData = {}

        # Read/parse the config
        self.config = Config(configPath)

        # Get config values
        self._pluginCollections = [
            PluginCollection(self, s) for s in self.config.getPluginPaths()
        ]
        print self.config.getShotgunURL()
        print self.config.getEngineScriptName()
        print self.config.getEngineScriptKey()
        print self.config.getEngineProxyServer()
        sg.shotgun.NO_SSL_VALIDATION = True
        self._sg = sg.Shotgun(self.config.getShotgunURL(),
                              self.config.getEngineScriptName(),
                              self.config.getEngineScriptKey(),
                              http_proxy=self.config.getEngineProxyServer())
        self._max_conn_retries = self.config.getint('daemon',
                                                    'max_conn_retries')
        self._conn_retry_sleep = self.config.getint('daemon',
                                                    'conn_retry_sleep')
        self._fetch_interval = self.config.getint('daemon', 'fetch_interval')
        self._use_session_uuid = self.config.getboolean(
            'shotgun', 'use_session_uuid')

        # Setup the loggers for the main engine
        if self.config.getLogMode() == 0:
            # Set the root logger for file output.
            rootLogger = logging.getLogger()
            rootLogger.config = self.config
            _setFilePathOnLogger(rootLogger, self.config.getLogFile())
            print self.config.getLogFile()

            # Set the engine logger for email output.
            self.log = logging.getLogger('engine')
            self.setEmailsOnLogger(self.log, True)
        else:
            # Set the engine logger for file and email output.
            self.log = logging.getLogger('engine')
            self.log.config = self.config
            _setFilePathOnLogger(self.log, self.config.getLogFile())
            self.setEmailsOnLogger(self.log, True)

        self.log.setLevel(self.config.getLogLevel())

        # Setup the timing log file
        timing_log_filename = self.config.getTimingLogFile()
        if timing_log_filename:
            self.timing_logger = logging.getLogger('timing')
            self.timing_logger.setLevel(self.config.getLogLevel())
            _setFilePathOnLogger(self.timing_logger, timing_log_filename)
        else:
            self.timing_logger = None

        super(Engine, self).__init__()
示例#16
0
 def __init__(self, hostname: str, login: str, password: str):
     self.hostname = hostname
     self.login = login
     self.password = password
     self.sg = shotgun_api3.Shotgun(self.hostname,
                                    login=self.login,
                                    password=self.password)
示例#17
0
 def registerCallback(
     self,
     sgScriptName,
     sgScriptKey,
     callback,
     matchEvents=None,
     args=None,
     stopOnError=True,
 ):
     """
     Register a callback in the plugin.
     """
     global sg
     sgConnection = sg.Shotgun(
         self._engine.config.getShotgunURL(),
         sgScriptName,
         sgScriptKey,
         http_proxy=self._engine.config.getEngineProxyServer(),
     )
     self._callbacks.append(
         Callback(
             callback,
             self,
             self._engine,
             sgConnection,
             matchEvents,
             args,
             stopOnError,
         ))
示例#18
0
 def registerCallback(self, sgScriptName, sgScriptKey, callback, matchEvents=None, args=None):
     """
     Register a callback in the plugin.
     """
     global sg
     sgConnection = sg.Shotgun(self._engine.config.getShotgunURL(), sgScriptName, sgScriptKey)
     self._callbacks.append(Callback(callback, self, self._engine, sgConnection, matchEvents, args))
示例#19
0
 def execute(self):
     import shotgun_api3
     apihandle = shotgun_api3.Shotgun(self.host.value(),
                                      script_name=self.apiScript.value(),
                                      api_key=self.apiKey.value(),
                                      connect=False)
     self.output.setValue(apihandle)
示例#20
0
def _getShotgunConnection():
    try:
        #### Get Shotgun Connection and Context when in SGTK session

        # get the engine we are currently running in
        current_engine = sgtk.platform.current_engine()

        # get hold of the shotgun api instance used by the engine, (or we could have created a new one)
        sg = current_engine.shotgun
        return sg

    except:
        #### Get Shotgun Connection and Context when not in SGTK session (example: farm)

        #####################################################
        logBig("Importing Shotgun API3")
        #####################################################
        shotgun_api3_location = os.environ["SHOTGUN_API3"]
        sys.path.append(shotgun_api3_location)
        import shotgun_api3
        log("Imported the Shotgun Standalone API3")

        #####################################################
        logBig("Connecting to Shotgun API")
        #####################################################
        sg = shotgun_api3.Shotgun(os.environ["SHOTGUN_API_SERVER_PATH"],
                                  os.environ["SHOTGUN_API_SCRIPT_NAME"],
                                  os.environ["SHOTGUN_API_SCRIPT_KEY"])
        log("Connected to Shotgun!")
        return sg
def getShotgunTaskData(scriptShot):
    import shotgun_api3 as shotgun
    SERVER_PATH = "https://psyop.shotgunstudio.com"
    SCRIPT_USER = "******"
    SCRIPT_KEY = "e0078c0e80f09ee7a76de2c25afce6bd34a5bc601f598d446daf6a8e848d9089"
    PROJECT_ID = 1674
    sg = shotgun.Shotgun(SERVER_PATH, SCRIPT_USER, SCRIPT_KEY)
    filters = [['project', 'is', {
        'type': 'Project',
        'id': PROJECT_ID
    }], ['code', 'is', scriptShot]]
    shot = sg.find_one('Shot', filters)

    fields = [
        'id', 'entity', 'code', 'sg_status_list', 'task_assignees', 'content',
        'tasks'
    ]
    filters = [['project', 'is', {
        "type": 'Project',
        'id': PROJECT_ID
    }], ['entity', 'is', {
        "type": 'Shot',
        'id': shot['id']
    }]]
    tasks = sg.find('Task', filters, fields)
    taskDict = {}
    for t in tasks:
        taskDict[t['content']] = t['task_assignees'][0]['name']

    return taskDict
示例#22
0
class LocalDBEventSpooler(object):
    """ Continuously spools events from couchdb and transfers them to shotgun """

    src = None  # local database connector
    cur = None
    sg = None

    def _connect(self):
        """ establish the connections
        
        establish a connection to local server and shotgun
        """
        try:
            self.src = connectors.DatabaseModificator()
        except Exception, error:  #IGNORE:W0703
            debug.error("Unable to _connect to database server. " +
                        unicode(error))
            return False

        try:
            self.sg = shotgun_api3.Shotgun(config.SHOTGUN_URL,
                                           config.SHOTGUN_SYNC_SKRIPT,
                                           config.SHOTGUN_SYNC_KEY)
        except Exception, error:  #IGNORE:W0703
            debug.error("Unable to _connect to Shotgun server. " +
                        unicode(error))
            return False
示例#23
0
def registerCallbacks(reg):
    """
    Register our callbacks.

    :param reg: A Registrar instance provided by the event loop handler.
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SG_SCRIPT_NAME"]
    script_key = os.environ["SG_SCRIPT_KEY"]

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    eventFilter = {"Shotgun_Task_Change": "task_assignees"}
    reg.registerCallback(
        script_name,
        script_key,
        task_assignment_alert,
        eventFilter,
        None,
    )
    reg.logger.debug("Registered callback.")
def registerCallbacks(reg):
    """
    Register our callbacks
    :param reg: A Registrar instance provided by the event loop handler
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SGDAEMON_CNFVF_NAME"]
    script_key = os.environ["SGDAEMON_CNFVF_KEY"]

    args = {
        "sg_note_type": "Client",
        "content_field": "description",
        "author_is_artist": True,
    }

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger, args):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    reg.registerCallback(
        script_name,
        script_key,
        version_content_changed,
        {"Shotgun_Version_Change": args["content_field"]},
        args,
    )
def registerCallbacks(reg):
    """
    Register our callbacks.

    :param reg: A Registrar instance provided by the event loop handler.
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SG_SCRIPT_NAME"]
    script_key = os.environ["SG_SCRIPT_KEY"]

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    # Register our callback with the Shotgun_%s_Change event and tell the logger
    # about it.
    reg.registerCallback(
        script_name,
        script_key,
        createChannel,
        {"Shotgun_Project_New": None},
        None,
    )
    reg.logger.debug("Registered callback.")
示例#26
0
def connect(name=None, server=None, *args, **kwargs):

    server = _conform_server(server)

    if server == 'mock':
        from sgmock import Shotgun
        sg = Shotgun()

        if 'SGMOCK_FIXTURE' in os.environ:
            fixture = os.environ['SGMOCK_FIXTURE']
            if ':' in fixture:
                module_name, func_name = fixture.split(':')
            else:
                module_name = 'sgmock.fixture.setup'
                func_name = fixture
            module = __import__(module_name, fromlist=['.'])
            func = getattr(module, func_name)
            func(sg)

        return sg

    kwargs = get_kwargs(name, server, *args, **kwargs)
    kwargs.setdefault('connect', False)

    return shotgun_api3.Shotgun(**kwargs)
示例#27
0
    def getShotgunPublishes(self, *args):
        import tank
        import shotgun_api3 as shotgun

        PROJECT_ID = tank.platform.current_engine().context.project['id']
        SERVER_PATH = "https://psyop.shotgunstudio.com"
        SCRIPT_USER = "******"
        SCRIPT_KEY = "e0078c0e80f09ee7a76de2c25afce6bd34a5bc601f598d446daf6a8e848d9089"
        sg = shotgun.Shotgun(SERVER_PATH, SCRIPT_USER, SCRIPT_KEY)

        # Get handle to Asset Manager tank application
        assetmgr = tank.platform.current_engine().apps["tk-multi-assetmanager"]

        # Grab updated publish data from shotgun
        publish_directory = assetmgr.publish_directory
        publish_directory.update(async=False)

        # list image/lighting render publishes
        paths = []
        for publish in list(publish_directory.all_publishes):
            if publish.component_type == 'image/lighting' and 'sequences' in publish.path:
                meta = []
                for key in publish.metadata['aovs']:
                    meta.append(publish.metadata['aovs'][key].replace(
                        "\\", "/"))
                aovs = publish.metadata['aovs']
                path = publish.path.replace("\\", "/")
                parts = path.split("/")
                newPath = "/".join(
                    [parts[4], parts[6], parts[10], parts[11], parts[-1]])
                verPath = "/".join([parts[4], parts[6], parts[10], parts[11]])
                paths.append(newPath)
                self.publishData[verPath] = meta
        self.publishItems = paths
def registerCallbacks(reg):
    """
    Register our callbacks

    :param reg: A Registrar instance provided by the event loop handler
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SGDAEMON_TSUVS_NAME"]
    script_key = os.environ["SGDAEMON_TSUVS_KEY"]

    # User-defined plugin args, change at will.
    args = {"status_mapping_field": "sg_version_status_mapping"}

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger, args):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    reg.registerCallback(
        script_name,
        script_key,
        task_status_changed,
        {"Shotgun_Task_Change": ["sg_status_list"]},
        args,
    )
    reg.logger.debug("Registered callback.")
    def __init__(self, base_url, script_name=None, *args, **kwargs):
        """
        Instantiate a :class:`shotgun_api3.shotgun.Shotgun` with the sanitized parameters.
        """
        # Note: we use composition rather than inheritance to wrap the Shotgun
        # instance. Otherwise we would have to redefine all the methods we need
        # to wrap with some very similar code which would encode all params,
        # blindly call the original method, decode and return the result.

        safe_args = unicode_to_utf8(args)
        safe_kwargs = unicode_to_utf8(kwargs)
        self._shotgun = shotgun_api3.Shotgun(
            unicode_to_utf8(base_url),
            unicode_to_utf8(script_name),
            *safe_args,
            **safe_kwargs
        )

        self._shotgun_schemas = {}
        # Retrieve our current login, this does not seem to be available from
        # the connection?
        self._shotgun_user = self.find_one(
            "ApiUser", [["firstname", "is", script_name]], ["firstname"]
        )
        logger.info("Connected to %s." % base_url)
示例#30
0
def registerCallbacks(reg):
    """
    Register our callbacks.

    :param reg: A Registrar instance provided by the event loop handler.
    """

    # Grab authentication env vars for this plugin. Install these into the env
    # if they don't already exist.
    server = os.environ["SG_SERVER"]
    script_name = os.environ["SGDAEMON_DATESTAMP_NAME"]
    script_key = os.environ["SGDAEMON_DATESTAMP_KEY"]

    # User-defined plugin args, change at will.
    args = {
        "entity_types": ["Shot"],
        "status_field": "sg_status_list",
        "statuses": ["fin"],
        "date_field": "sg_finaled_on",
        "timezone": "US/Pacific",
        "allow_date_overwrite": False,
        "set_date_on_entity_creation": False,
    }

    # Grab an sg connection for the validator.
    sg = shotgun_api3.Shotgun(server,
                              script_name=script_name,
                              api_key=script_key)

    # Bail if our validator fails.
    if not is_valid(sg, reg.logger, args):
        reg.logger.warning("Plugin is not valid, will not register callback.")
        return

    # Build our event_filter.
    event_filter = {}
    for entity_type in args["entity_types"]:

        # If both status_field and statuses are non-empty, add an entity Change
        # event to the match_events dict.
        if args["status_field"] and args["statuses"]:
            event_filter["Shotgun_%s_Change" %
                         entity_type] = [args["status_field"]]

        # If set_date_on_entity_creation is true, add an entity New event to the
        # match_events dict.
        if args["set_date_on_entity_creation"]:
            event_filter["Shotgun_%s_New" % entity_type] = None

    # Register our callback with the Shotgun_%s_Change event and tell the logger
    # about it.
    reg.registerCallback(
        script_name,
        script_key,
        set_datestamp,
        event_filter,
        args,
    )
    reg.logger.debug("Registered callback.")