예제 #1
0
  def fromXML(cls, sgSchema, sgXmlElement):
    '''
    From the passed XML data a new SgEntitySchemaInfo is returned.
    '''

    if sgXmlElement.tag != 'SgEntity':
      raise RuntimeError('invalid tag "%s"' % sgXmlElement.tag)

    entityFieldInfos = {}

    fields = sgXmlElement.find('fields')

    if fields == None:
      raise RuntimeError('could not find fields element')

    entityName = sgXmlElement.attrib.get('name')
    entityLabel = sgXmlElement.attrib.get('label')

    for field in fields:
      # Skip fields that have an unsupported return type!
      fieldInfo = ShotgunORM.SgFieldSchemaInfo.fromXML(entityName, entityLabel, field)

      if fieldInfo.returnType() == ShotgunORM.SgField.RETURN_TYPE_UNSUPPORTED:
        ShotgunORM.LoggerEntity.warning('field %s.%s ignored because of return type unsupported' % (fieldInfo.name(), entityName))

        continue

      entityFieldInfos[field.attrib.get('name')] = fieldInfo

    result = cls(sgSchema, entityName, entityLabel, entityFieldInfos)

    try:
      ShotgunORM.onEntitySchemaInfoCreate(result)
    except Exception, e:
      ShotgunORM.LoggerORM.warn(e)
예제 #2
0
  def fromSg(cls, sgSchema, sgEntityName, sgEntityLabel, sgFieldSchemas):
    '''
    From the passed Shotgun schema info a new SgEntitySchemaInfo is returned.
    '''

    fieldInfos = {}
    fieldInfosUnsupported = {}

    for fieldName, schemaData in sgFieldSchemas.items():
      if fieldName.startswith('step_'):
        continue

      fieldInfo = ShotgunORM.SgFieldSchemaInfo.fromSg(sgEntityName, sgEntityLabel, fieldName, schemaData)

      # Skip fields that have an unsupported return type!
      if fieldInfo.returnType() == ShotgunORM.SgField.RETURN_TYPE_UNSUPPORTED:
        ShotgunORM.LoggerSchema.warn(
          'ignoring unsupported return type "%s", %s.%s' % (
            fieldInfo.returnTypeName(),
            sgEntityName, fieldInfo.name()
          )
        )

        fieldInfosUnsupported[fieldName] = fieldInfo
      else:
        fieldInfos[fieldName] = fieldInfo

    result = cls(sgSchema, sgEntityName, sgEntityLabel, fieldInfos, fieldInfosUnsupported)

    try:
      ShotgunORM.onEntitySchemaInfoCreate(result)
    except Exception, e:
      ShotgunORM.LoggerORM.warn(e)
예제 #3
0
  def __init__(self, url, login, key, baseEntityClasses={}):
    super(SgConnection, self).__init__(url, login, key)

    self.__lockCache = threading.RLock()

    self._fieldQueryDefaults = 'default'
    self._fieldQueryDefaultsFallback = 'default'

    baseClasses = self.baseEntityClasses()

    if baseClasses == None:
      baseClasses = {}

    if baseEntityClasses == None:
      baseEntityClasses = {}

    baseClasses.update(baseEntityClasses)

    self.__qEngine = ShotgunORM.SgQueryEngine(self)
    self.__asyncEngine = ShotgunORM.SgAsyncSearchEngine(self)
    self.__schema = ShotgunORM.SgSchema.createSchema(self._url)
    self._factory = ShotgunORM.SgEntityClassFactory(
      self,
      baseClasses
    )

    self.__entityCache = {}
    self.__entityCaching = ShotgunORM.config.DEFAULT_CONNECTION_CACHING

    self.__currentUser = None
    def toLogicalOp(self, sgConnection, operator='and'):
        '''
    Returns a SgLogicalOp of this search filter.
    '''

        if operator != 'and' and operator != 'or':
            raise ValueError('invalid operator name "%s"' % operator)

        logical_op = ShotgunORM.SgLogicalOp()

        e_info = sgConnection.schema().entityInfo(self._entity_type)

        filters = self.toSearchFilters()

        for i in self._filters:
            if i.isLogicalOp() == True:
                logical_op.appendCondition(i)
            else:
                op_cond = ShotgunORM.convertToLogicalOpCond(
                    e_info, i.toFilter())

                logical_op.appendCondition(
                    ShotgunORM.SgLogicalOpCondition(**op_cond))

        return logical_op
예제 #5
0
  def fromSg(cls, sgSchema, sgEntityName, sgEntityLabel, sgFieldSchemas):
    '''
    From the passed Shotgun schema info a new SgEntitySchemaInfo is returned.
    '''

    fieldInfos = {}
    fieldInfosUnsupported = {}

    for fieldName, schemaData in sgFieldSchemas.items():
      if fieldName.startswith('step_'):
        continue

      fieldInfo = ShotgunORM.SgFieldSchemaInfo.fromSg(sgEntityName, sgEntityLabel, fieldName, schemaData)

      # Skip fields that have an unsupported return type!
      if fieldInfo.returnType() == ShotgunORM.SgField.RETURN_TYPE_UNSUPPORTED:
        ShotgunORM.LoggerSchema.warn(
          'ignoring unsupported return type "%s", %s.%s' % (
            fieldInfo.returnTypeName(),
            sgEntityName, fieldInfo.name()
          )
        )

        fieldInfosUnsupported[fieldName] = fieldInfo
      else:
        fieldInfos[fieldName] = fieldInfo

    result = cls(sgSchema, sgEntityName, sgEntityLabel, fieldInfos, fieldInfosUnsupported)

    try:
      ShotgunORM.onEntitySchemaInfoCreate(result)
    except Exception, e:
      ShotgunORM.LoggerORM.warn(e)
예제 #6
0
    def changed(self):
        '''
    Called whenever the schemas info changes.

    Calls SgSchema._changed() and then ShotgunORM.onSchemaChanged() callback.
    '''

        self._changed()

        ShotgunORM.onSchemaChanged(self)
예제 #7
0
  def changed(self):
    '''
    Called whenever the schemas info changes.

    Calls SgSchema._changed() and then ShotgunORM.onSchemaChanged() callback.
    '''

    self._changed()

    ShotgunORM.onSchemaChanged(self)
예제 #8
0
  def buildFields(self):
    '''
    Creates all the fields for the Entity.

    After _buildFields(...) has been called buildUserFiels() is called.

    Note:
      This is called by the class factory after the Entity has been created and
      will immediately return anytime afterwards.
    '''

    # Only build the fields once!
    if self.__hasBuiltFields:
      return

    entityFieldInfos = self.schemaInfo().fieldInfos()

    # Add the type field.
    self._fields['type'] = ShotgunORM.SgFieldType(self, entityFieldInfos['type'])
    self._fields['id'] = ShotgunORM.SgFieldID(self, entityFieldInfos['id'])

    # Dont pass the "id" field as its manually built as a user field.  Same
    # for the type field.
    del entityFieldInfos['id']
    del entityFieldInfos['type']

    fieldClasses = ShotgunORM.SgField.__fieldclasses__

    for fieldInfo in entityFieldInfos.values():
      fieldName = fieldInfo.name()

      fieldClass = fieldClasses.get(fieldInfo.returnType(), None)

      newField = fieldClass(None, sgFieldSchemaInfo=fieldInfo)

      newField._SgField__setParentEntity(self)

      if hasattr(self.__class__, fieldName):
        ShotgunORM.LoggerField.warn(
          'Entity type %(entity)s field name "%(name)s confilicts with class method of same name' % {
            'entity': self.schemaInfo().name(),
            'name': fieldName
          }
        )

      self._fields[fieldName] = newField

    self._buildFields()

    self.__hasBuiltFields = True
예제 #9
0
  def __init__(self, url, login, key):
    super(SgConnection, self).__init__(url, login, key)

    self.__lockCache = threading.RLock()

    self._fieldQueryDefaults = 'default'
    self._fieldQueryDefaultsFallback = 'default'

    self.__qEngine = ShotgunORM.SgQueryEngine(self)
    self.__schema = ShotgunORM.SgSchema.createSchema(self._url)
    self._factory = ShotgunORM.SgEntityClassFactory(self)

    self.__entityCache = {}
    self.__entityCaching = ShotgunORM.config.DEFAULT_CONNECTION_CACHING
  def __init__(
    self,
    sgConnection,
    startProcessingAtId=None,
    updateInterval=10
  ):
    super(SgEventWatcher, self).__init__()

    self.__lock = threading.RLock()
    self.__connection = sgConnection
    self.__handlers = []
    self.__updateInterval = int(updateInterval)
    self.__search_filters = ShotgunORM.SgEntitySearchFilters(
      'EventLogEntry'
    )

    if self.__updateInterval < self.UPDATE_INTERVAL_MIN:
      self.__updateInterval = self.UPDATE_INTERVAL_MIN

    if startProcessingAtId == None:
      startProcessingAtId = self.LAST_EVENT
    elif startProcessingAtId < self.NO_EVENT:
      startProcessingAtId = self.NO_EVENT

    self.__aborted = False
    self.__running = False
    self.__lastEvent = None
    self.__threadData = {
      'event': threading.Event(),
      'start_at_id': startProcessingAtId,
      'batch_size': self.batchSize()
    }

    self.__monitorThread = None
  def toLogicalOp(self, sgConnection, operator='and'):
    '''
    Returns a SgLogicalOp of this search filter.
    '''

    if operator != 'and' and operator != 'or':
      raise ValueError('invalid operator name "%s"' % operator)

    logical_op = ShotgunORM.SgLogicalOp()

    e_info = sgConnection.schema().entityInfo(self._entity_type)

    filters = self.toSearchFilters()

    for i in self._filters:
      if i.isLogicalOp() == True:
        logical_op.appendCondition(i)
      else:
        op_cond = ShotgunORM.convertToLogicalOpCond(
          e_info,
          i.toFilter()
        )

        logical_op.appendCondition(
          ShotgunORM.SgLogicalOpCondition(**op_cond)
        )

    return logical_op
예제 #12
0
  def fromFieldData(self, sgData):
    '''
    Sets the fields value from data returned by a Shotgun query.

    Returns True on success.

    Args:
      * (dict) sgData:
        Dict of Shotgun formatted Entity field values.
    '''

    with self:
      ShotgunORM.LoggerField.debug('%(sgField)s.fromFieldData()', {'sgField': self})
      ShotgunORM.LoggerField.debug('    * sgData: %(sgData)s', {'sgData': sgData})

      parent = self.parentEntity()

      if not self.isEditable():
        raise RuntimeError('%s is not editable!' % ShotgunORM.mkEntityFieldString(self))

      if not ShotgunORM.config.DISABLE_FIELD_VALIDATE_ON_SET_VALUE:
        self.validate(forReal=True)

      result = self._fromFieldData(sgData)

      if not result:
        return False

      self.setValid(True)
      self.setHasCommit(True)

      self.changed()

      return True
예제 #13
0
  def _sg_find_one(
    self,
    entity_type,
    filters=[],
    fields=None,
    order=None,
    filter_operator=None,
    retired_only=False,
  ):
    '''
    Calls the Shotgun Python API find_one function.

    This will lock the global Shotgun Python API lock.
    '''

    if fields != None:
      fields = list(fields)

    with ShotgunORM.SHOTGUN_API_LOCK:
      result = self.connection().find_one(
        entity_type,
        filters,
        fields,
        order,
        filter_operator,
        retired_only,
      )

      return ShotgunORM.onSearchResult(
        self,
        entity_type,
        fields,
        [result]
      )[0]
예제 #14
0
  def facility(self):
    '''
    Returns the facility name from the Shotgun url.
    '''

    if self._facility == None:
      self._facility = ShotgunORM.facilityNameFromUrl(self._url)

    return self._facility
    def setLogicalOp(self, logicalOp):
        '''
    Sets the logical operator
    '''

        if isinstance(logicalOp, SgSearchFilterLogicalOp):
            self._op = logicalOp._op.copy()
        else:
            self._op = ShotgunORM.SgLogicalOp(logicalOp)
예제 #16
0
  def facility(self):
    '''
    Returns the facility name from the Shotgun url.
    '''

    if self._facility == None:
      self._facility = ShotgunORM.facilityNameFromUrl(self._url)

    return self._facility
예제 #17
0
  def fromXML(cls, sgSchema, sgXmlElement):
    '''
    From the passed XML data a new SgEntitySchemaInfo is returned.
    '''

    if sgXmlElement.tag != 'SgEntity':
      raise RuntimeError('invalid tag "%s"' % sgXmlElement.tag)

    entityFieldInfos = {}
    entityFieldInfosUnsupported = {}

    fields = sgXmlElement.find('fields')

    if fields == None:
      raise RuntimeError('could not find fields element')

    entityName = sgXmlElement.attrib.get('name')
    entityLabel = sgXmlElement.attrib.get('label')

    for field in fields:
      # Skip fields that have an unsupported return type!
      fieldInfo = ShotgunORM.SgFieldSchemaInfo.fromXML(entityName, entityLabel, field)

      if fieldInfo.returnType() == ShotgunORM.SgField.RETURN_TYPE_UNSUPPORTED:
        ShotgunORM.LoggerEntity.warning('field %s.%s ignored because of return type unsupported' % (fieldInfo.name(), entityName))

        entityFieldInfosUnsupported[fieldInfo.name()] = fieldInfo
      else:
        entityFieldInfos[fieldInfo.name()] = fieldInfo

    result = cls(
      sgSchema,
      entityName,
      entityLabel,
      entityFieldInfos,
      entityFieldInfosUnsupported
    )

    try:
      ShotgunORM.onEntitySchemaInfoCreate(result)
    except Exception, e:
      ShotgunORM.LoggerORM.warn(e)
예제 #18
0
  def searchIterator(
    self,
    sgEntityType,
    sgSearchExp,
    sgFields=None,
    sgSearchArgs=[],
    order=None,
    filter_operator=None,
    limit=100,
    retired_only=False,
    page=1,
    include_archived_projects=True,
    additional_filter_presets=None,
    buffered=False
  ):
    '''
    Returns a SgSearchIterator which is used to iterate over the search filter
    by page.
    '''

    schema = self.schema()

    sgEntityType = schema.entityApiName(sgEntityType)

    sgFilters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(sgEntityType),
      sgSearchExp,
      sgSearchArgs
    )

    sgFilters = self._flattenFilters(sgFilters)

    iterClass = None

    if buffered:
      iterClass = ShotgunORM.SgBufferedSearchIterator
    else:
      iterClass = ShotgunORM.SgSearchIterator

    return iterClass(
      self,
      sgEntityType,
      sgFilters,
      sgFields,
      order,
      filter_operator,
      limit,
      retired_only,
      page,
      include_archived_projects,
      additional_filter_presets
    )
    def formatMessage(self, sgEvent):
        '''
    Returns a formatted string for the event.

    Subclasses can override this function to return custom msgs.

    Args:
      * (SgEvent) sgEvent:
        Event to build message for.
    '''

        return (ShotgunORM.formatSerializable(sgEvent.event().fieldValues()) +
                '\n')
  def setSearchFilters(self, sgSearchFilters):
    '''

    '''

    if self.isRunning() == True:
      raise RuntimeError(
        'can not set EventLog search filters while watcher is running'
      )

    self.__search_filters = ShotgunORM.SgSearchFilters(
      sgSearchFilters
    )
예제 #21
0
  def fieldChanged(self, sgField):
    '''
    Called when a field changes values.

    If SgEntity.widget() is not None then SgEntity.widget().fieldChanged()
    will be called as well.

    Args:
      * (SgField) sgField:
        Field that changed.
    '''

    ShotgunORM.LoggerEntity.debug('%(entity)s.fieldChanged("%(sgField)s")', {'entity': self, 'sgField': sgField.name()})

    self._fieldChanged(sgField)

    w = self.widget()

    if w != None:
      w.fieldChanged(sgField)

    if not self.isBuildingFields():
      ShotgunORM.onFieldChanged(sgField)
예제 #22
0
  def fieldChanged(self, sgField):
    '''
    Called when a field changes values.

    If SgEntity.widget() is not None then SgEntity.widget().fieldChanged()
    will be called as well.

    Args:
      * (SgField) sgField:
        Field that changed.
    '''

    ShotgunORM.LoggerEntity.debug('%(entity)s.fieldChanged("%(sgField)s")', {'entity': self, 'sgField': sgField.name()})

    self._fieldChanged(sgField)

    w = self.widget()

    if w != None:
      w.fieldChanged(sgField)

    if not self.isBuildingFields():
      ShotgunORM.onFieldChanged(sgField)
예제 #23
0
def _defaultOnEntitySchemaInfoCreate(sgEntitySchemaInfo):
    fieldInfoData = ShotgunORM.SgFieldSchemaInfo.createSchemaData(
        sgEntitySchemaInfo.name(),
        'type',
        ShotgunORM.SgField.RETURN_TYPE_TEXT,
        editable=False,
        label='Type')

    fieldInfoData['commitable'] = False
    fieldInfoData['queryable'] = False

    fieldInfo = ShotgunORM.SgFieldSchemaInfo(fieldInfoData)

    sgEntitySchemaInfo._fieldInfos['type'] = fieldInfo
예제 #24
0
  def searchIterator(
    self,
    sgEntityType,
    sgSearchExp,
    sgFields=None,
    sgSearchArgs=[],
    order=None,
    filter_operator=None,
    limit=100,
    retired_only=False,
    page=1,
    buffered=False
  ):
    '''
    Returns a SgSearchIterator which is used to iterate over the search filter
    by page.
    '''

    schema = self.schema()

    sgEntityType = schema.entityApiName(sgEntityType)

    sgFilters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(sgEntityType),
      sgSearchExp,
      sgSearchArgs
    )

    sgFilters = self._flattenFilters(sgFilters)

    iterClass = None

    if buffered:
      iterClass = ShotgunORM.SgBufferedSearchIterator
    else:
      iterClass = ShotgunORM.SgSearchIterator

    return iterClass(
      self,
      sgEntityType,
      sgFilters,
      sgFields,
      order,
      filter_operator,
      limit,
      retired_only,
      page
    )
  def formatMessage(self, sgEvent):
    '''
    Returns a formatted string for the event.

    Subclasses can override this function to return custom msgs.

    Args:
      * (SgEvent) sgEvent:
        Event to build message for.
    '''

    return (
      ShotgunORM.formatSerializable(
        sgEvent.event().fieldValues()
      ) + '\n'
    )
예제 #26
0
  def createEntity(self, sgConnection, sgEntityType, sgData):
    '''
    Creates a new Entity object of type sgEntityType.
    '''

    entityClass = self._classCache.get(sgEntityType, None)

    if entityClass == None:
      raise RuntimeError('unknown Entity type "%s"' % sgEntityType)

    sgData = ShotgunORM.beforeEntityCreate(sgConnection, sgEntityType, sgData)

    result = entityClass(sgConnection)

    result.buildFields()
    result._fromFieldData(sgData)

    return result
  def createEntity(self, sgEntityType, sgData):
    '''
    Creates a new Entity object of type sgEntityType.
    '''

    entityClass = self._classCache.get(sgEntityType, None)

    if entityClass == None:
      raise RuntimeError('unknown Entity type "%s"' % sgEntityType)

    sgData = ShotgunORM.beforeEntityCreate(self.connection(), sgEntityType, sgData)

    result = entityClass()

    result.buildFields()
    result._fromFieldData(sgData)

    return result
예제 #28
0
  def searchAsync(
    self,
    sgEntityType,
    sgSearchExp,
    sgFields=None,
    sgSearchArgs=[],
    order=None,
    filter_operator=None,
    limit=100,
    retired_only=False,
    page=1,
    include_archived_projects=True,
    additional_filter_presets=None
  ):
    '''
    Performs an async search().

    See search() for a more detailed description.
    '''

    schema = self.schema()

    sgEntityType = schema.entityApiName(sgEntityType)

    sgFilters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(sgEntityType),
      sgSearchExp,
      sgSearchArgs
    )

    sgFilters = self._flattenFilters(sgFilters)

    return self.__asyncEngine.appendSearchToQueue(
      sgEntityType,
      sgFilters,
      sgFields,
      order,
      filter_operator,
      limit,
      retired_only,
      page,
      include_archived_projects,
      additional_filter_presets
    )
예제 #29
0
  def _sg_find(
    self,
    entity_type,
    filters,
    fields=None,
    order=None,
    filter_operator=None,
    limit=0,
    retired_only=False,
    page=0,
    include_archived_projects=True,
    additional_filter_presets=None
  ):
    '''
    Calls the Shotgun Python API find function.

    This will lock the global Shotgun Python API lock.
    '''

    if fields != None:
      fields = list(fields)

    with ShotgunORM.SHOTGUN_API_LOCK:
      result = self.connection().find(
        entity_type,
        filters,
        fields,
        order,
        filter_operator,
        limit,
        retired_only,
        page,
        include_archived_projects,
        additional_filter_presets
      )

      return ShotgunORM.onSearchResult(
        self,
        entity_type,
        fields,
        result
      )
예제 #30
0
    def setValue(self, sgData):
        '''
    Set the value of the field.

    Returns True on success.

    Args:
      * (object) sgData:
        New field value.
    '''

        with self:
            ShotgunORM.LoggerField.debug('%(sgField)s.setValue(...)',
                                         {'sgField': self})
            ShotgunORM.LoggerField.debug('    * sgData: %(sgData)s',
                                         {'sgData': sgData})

            if not self.isEditable():
                raise RuntimeError('%s is not editable!' %
                                   ShotgunORM.mkEntityFieldString(self))

            if not ShotgunORM.config.DISABLE_FIELD_VALIDATE_ON_SET_VALUE:
                self.validate(forReal=True)

            if sgData == None:
                sgData = self.defaultValue()

            updateResult = self._setValue(sgData)

            if not updateResult:
                if not self.isValid():
                    self.setValid(True)

                return False

            self.setValid(True)
            self.setHasCommit(True)

            self.changed()

            return True
예제 #31
0
  def searchAsync(
    self,
    sgEntityType,
    sgSearchExp,
    sgFields=None,
    sgSearchArgs=[],
    order=None,
    filter_operator=None,
    limit=100,
    retired_only=False,
    page=1
  ):
    '''
    Performs an async search().

    See search() for a more detailed description.
    '''

    schema = self.schema()

    sgEntityType = schema.entityApiName(sgEntityType)

    sgFilters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(sgEntityType),
      sgSearchExp,
      sgSearchArgs
    )

    sgFilters = self._flattenFilters(sgFilters)

    return self.__asyncEngine.appendSearchToQueue(
      sgEntityType,
      sgFilters,
      sgFields,
      order,
      filter_operator,
      limit,
      retired_only,
      page
    )
예제 #32
0
  def searchOneAsync(
    self,
    sgEntityType,
    sgSearchExp,
    sgFields=None,
    sgSearchArgs=[],
    order=None,
    filter_operator=None,
    retired_only=False
  ):
    '''
    Performs an async searchOne().

    See searchOne() for a more detailed description.
    '''

    schema = self.schema()

    sgEntityType = schema.entityApiName(sgEntityType)

    sgFilters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(sgEntityType),
      sgSearchExp,
      sgSearchArgs
    )

    sgFilters = self._flattenFilters(sgFilters)

    return self.__asyncEngine.appendSearchToQueue(
      sgEntityType,
      sgFilters,
      sgFields,
      order,
      filter_operator,
      0,
      retired_only,
      0,
      isSingle=True
    )
예제 #33
0
  def setValue(self, sgData):
    '''
    Set the value of the field.

    Returns True on success.

    Args:
      * (object) sgData:
        New field value.
    '''

    with self:
      ShotgunORM.LoggerField.debug('%(sgField)s.setValue(...)', {'sgField': self})
      ShotgunORM.LoggerField.debug('    * sgData: %(sgData)s', {'sgData': sgData})

      if not self.isEditable():
        raise RuntimeError('%s is not editable!' % ShotgunORM.mkEntityFieldString(self))

      if not ShotgunORM.config.DISABLE_FIELD_VALIDATE_ON_SET_VALUE:
        self.validate(forReal=True)

      if sgData == None:
        sgData = self.defaultValue()

      updateResult = self._setValue(sgData)

      if not updateResult:
        if not self.isValid():
          self.setValid(True)

        return False

      self.setValid(True)
      self.setHasCommit(True)

      self.changed()

      return True
예제 #34
0
    def __addSearch(self, entity_type, filters, fields, order, filter_operator,
                    limit, retired_only, page, include_archived_projects,
                    additional_filter_presets, sgQueryFieldTemplate, isSingle,
                    searchPosition):
        '''
    Internal function for adding a search to the pending queue.

    This function does not obtain a lock!
    '''

        params = ShotgunORM.SgSearchParameters(entity_type, filters, fields,
                                               order, filter_operator, limit,
                                               retired_only, page,
                                               include_archived_projects,
                                               additional_filter_presets,
                                               sgQueryFieldTemplate,
                                               self.connection())

        searchResult = SgAsyncEntitySearchResult(params, isSingle)

        self.__addSearchResult(searchResult, searchPosition)

        return searchResult
예제 #35
0
    def fromFieldData(self, sgData):
        '''
    Sets the fields value from data returned by a Shotgun query.

    Returns True on success.

    Args:
      * (dict) sgData:
        Dict of Shotgun formatted Entity field values.
    '''

        with self:
            ShotgunORM.LoggerField.debug('%(sgField)s.fromFieldData()',
                                         {'sgField': self})
            ShotgunORM.LoggerField.debug('    * sgData: %(sgData)s',
                                         {'sgData': sgData})

            parent = self.parentEntity()

            if not self.isEditable():
                raise RuntimeError('%s is not editable!' %
                                   ShotgunORM.mkEntityFieldString(self))

            if not ShotgunORM.config.DISABLE_FIELD_VALIDATE_ON_SET_VALUE:
                self.validate(forReal=True)

            result = self._fromFieldData(sgData)

            if not result:
                return False

            self.setValid(True)
            self.setHasCommit(True)

            self.changed()

            return True
예제 #36
0
def sgApiInfo():
  '''
  Returns a SgApiInfo object.
  '''

  return ShotgunORM.SgApiInfo()
예제 #37
0
  def __init__(self):
    super(SgVersionCreatedHandler, self).__init__()

    self.addFilter(ShotgunORM.SgVersionCreatedFilter())
  def _createEntity(self, sgEntityType, sgData, sgSyncFields=None):
    '''
    Internal function!

    Locks the connection and if the Entity has an ID the cache is checked to see
    if it already has an SgEntity and if so it returns it otherwise it creates one.
    '''

    ShotgunORM.LoggerConnection.debug('%(connection)s._createEntity(...)', {'connection': self})
    ShotgunORM.LoggerConnection.debug('    * sgEntityType: %(entityName)s', {'entityName': sgEntityType})
    ShotgunORM.LoggerConnection.debug('    * sgData: %(sgData)s', {'sgData': sgData})

    with self:
      sgData = dict(sgData)

      factory = self.classFactory()

      result = None

      eId = None

      if sgData.has_key('id'):
        eId = int(sgData['id'])
      else:
        eId = -1

      if not self.__entityCache.has_key(sgEntityType):
        self.__entityCache[sgEntityType] = {}

      # Return immediately if the Entity does not exist.
      if eId <= -1:
        sgData['id'] = -id(result)

        result = factory.createEntity(self, sgEntityType, sgData)

        ShotgunORM.onEntityCreate(result)

        return result

      onCreate = False

      # Check the cache and if its found update any non-valid fields that
      # have data contained in the passed sgData.  If not found create the
      # Entity and add it to the cache.]
      if self.__entityCache[sgEntityType].has_key(eId):
        result = self.__entityCache[sgEntityType][eId]['entity']

        if result != None:
          result = result()

        if result == None:
          cacheData = self.__entityCache[sgEntityType][eId]['cache']

          tmpData = {
            'id': eId,
            'type': sgEntityType
          }

          tmpData.update(cacheData)

          result = factory.createEntity(self, sgEntityType, tmpData)

          self.__entityCache[sgEntityType][eId]['entity'] = weakref.ref(result)

          onCreate = True

        with result:
          del sgData['id']
          del sgData['type']

          for field, value in sgData.items():
            fieldObj = result.field(field)

            if fieldObj.isValid() or fieldObj.hasCommit() or fieldObj.hasSyncUpdate():
              continue

            fieldObj.invalidate()

            fieldObj._updateValue = value

            fieldObj.setHasSyncUpdate(True)
      else:
        result = factory.createEntity(self, sgEntityType, sgData)

        self.__entityCache[sgEntityType][eId] = {
          'entity': weakref.ref(result),
          'cache': {}
        }

        onCreate = True

      if sgSyncFields != None:
        result.sync(sgSyncFields, ignoreValid=True, ignoreWithUpdate=True, backgroundPull=True)

      if onCreate:
        ShotgunORM.onEntityCreate(result)

      return result
예제 #39
0
 def __repr__(self):
   return '<%s>' % ShotgunORM.mkEntityFieldString(self)
예제 #40
0
          fieldNames = batch['data'].keys()

          for field in self.fields(fieldNames).values():
            field.setIsCommitting(False)

    error = None

    try:
      self._afterCommit(sgBatchData, sgBatchResult, sgCommitData, sgDryRun, sgCommitError)
    except Exception, e:
      error = e

    batchDataCopy = copy.deepcopy(sgBatchData)

    try:
      ShotgunORM.afterEntityCommit(self, batchDataCopy, sgBatchResult, sgCommitData, sgDryRun, sgCommitError)
    except Exception, e:
      if error == None:
        error = e

    if error != None:
      raise error

  def _beforeCommit(self, sgBatchData, sgCommitData, sgDryRun):
    '''
    Subclass portion of SgEntity.beforeCommit().

    ** The Entity is locked down when this is called **

    Args:
      * (dict) sgBatchData:
  def search(self, sgEntityType, sgSearchExp, sgFields=None, sgSearchArgs=[], order=None, limit=0, retired_only=False, page=0):
    '''
    Uses a search string to find entities in Shotgun instead of a list.

    For more information on the search syntax check the ShotgunORM documentation.

    Args:
      * (str) sgEntityType:
        Entity type to find.

      * (str) sgSearchExp:
        Search expression string.

      * (list) sgFields:
        Fields that return results will have filled in with data from Shotgun.

      * (list) sgSearchArgs:
        Args used by the search expression string during evaluation.

      * (list) order:
        List of Shotgun formatted order filters.

      * (int) limit:
        Limits the amount of Entities can be returned.

      * (bool) retired_only:
        Return only retired entities.

      * (int) page:
        Return a single specified page number of records instead of the entire
        result set.
    '''

    schema = self.schema()

    sgconnection = self.connection()

    entity_type = schema.entityApiName(sgEntityType)

    ShotgunORM.LoggerConnection.debug('%(sgConnection)s.search(...)', {'sgConnection': self})
    ShotgunORM.LoggerConnection.debug('    * entity_type: %(entityType)s', {'entityType': entity_type})
    ShotgunORM.LoggerConnection.debug('    * search_exp: "%(sgSearchExp)s"', {'sgSearchExp': sgSearchExp})
    ShotgunORM.LoggerConnection.debug('    * fields: %(sgFields)s', {'sgFields': sgFields})

    filters = ShotgunORM.parseToLogicalOp(
      schema.entityInfo(entity_type),
      sgSearchExp,
      sgSearchArgs
    )

    filters = self._flattenFilters(filters)

    if sgFields == None:
      sgFields = self.defaultEntityQueryFields(entity_type)
    else:
      if isinstance(sgFields, str):
        sgFields = [sgFields]

      sgFields = set(sgFields)

      if 'default' in sgFields:
        sgFields.discard('default')

        sgFields.update(self.defaultEntityQueryFields(entity_type))

    return self.find(
      entity_type,
      filters,
      sgFields,
      order=order,
      limit=limit,
      retired_only=retired_only,
      page=page
    )
예제 #42
0
def _entityFix(schema, schemaData):
  '''
  Returns Entities that dont exist in the API but fields return them as values.

  * Currently returns *

    1: Banner Entity
    2: AppWelcome Entity
  '''

  idInfoData = ShotgunORM.SgFieldSchemaInfo.createSchemaData(
    'Banner',
    'id',
    ShotgunORM.SgField.RETURN_TYPE_INT,
    editable=False,
    doc='Entity ID',
    label='Id'
  )

  nameInfoData = ShotgunORM.SgFieldSchemaInfo.createSchemaData(
    'Banner',
    'name',
    ShotgunORM.SgField.RETURN_TYPE_TEXT,
    editable=False,
    label='Name'
  )

  bannerFieldInfos = {
    'name': ShotgunORM.SgFieldSchemaInfo(nameInfoData),
    'id': ShotgunORM.SgFieldSchemaInfo(idInfoData)
  }

  BannerEntity = ShotgunORM.SgEntitySchemaInfo(
    schema,
    'Banner',
    'Banner',
    bannerFieldInfos,
    {}
  )

  ShotgunORM.onEntitySchemaInfoCreate(BannerEntity)

  idInfoData = ShotgunORM.SgFieldSchemaInfo.createSchemaData(
    'AppWelcome',
    'id',
    ShotgunORM.SgField.RETURN_TYPE_INT,
    doc='Entity ID',
    editable=False,
    label='Id'
  )

  nameInfoData = ShotgunORM.SgFieldSchemaInfo.createSchemaData(
    'AppWelcome',
    'name',
    ShotgunORM.SgField.RETURN_TYPE_TEXT,
    editable=False,
    label='Name'
  )

  appwelcomeFieldInfos = {
    'name': ShotgunORM.SgFieldSchemaInfo(nameInfoData),
    'id': ShotgunORM.SgFieldSchemaInfo(idInfoData)
  }

  AppWelcomeEntity = ShotgunORM.SgEntitySchemaInfo(
    schema,
    'AppWelcome',
    'AppWelcome',
    appwelcomeFieldInfos,
    {}
  )

  ShotgunORM.onEntitySchemaInfoCreate(AppWelcomeEntity)

  schemaData['AppWelcome'] = AppWelcomeEntity
  schemaData['Banner'] = BannerEntity
  def toSearchString(self, sgConnection):
    '''
    Returns a search string of this search filter.
    '''

    return ShotgunORM.parseFromLogicalOp(self.toLogicalOp())
예제 #44
0
 def __repr__(self):
     return '<%s>' % ShotgunORM.mkEntityFieldString(self)
예제 #45
0
 def __init__(self, sgUrl):
   self._url = sgUrl
   self._name = ShotgunORM.facilityNameFromUrl(sgUrl)
예제 #46
0
  def __init__(self):
    super(SgPublishedFileCreatedHandler, self).__init__()

    self.addFilter(ShotgunORM.SgPublishedFileCreatedFilter())
예제 #47
0
  def __init__(self, project):
    super(SgProjectVersionCreatedHandler, self).__init__()

    self._project = project

    self.addFilter(ShotgunORM.SgProjectFilter(project))
예제 #48
0
  def __init__(self):
    super(SgHumanUserCreatedHandler, self).__init__()

    self.addFilter(ShotgunORM.SgHumanUserCreatedFilter())
# The callback that will be registered to onEntityCreate() and will add the
# name field to ApiUser Entity objects.
#
################################################################################

def addApiUserNameField(sgEntity):
  '''
  This example callback shows how to add user fields to Entity objects as they
  are created.

  A SgUserField will be created for all ApiUser Entity objects that adds a name
  field for the Entity.  ApiUsers do not contain a "name" field as part of the
  Shotgun schema.
  '''

  if sgEntity.type == 'ApiUser':
    if not sgEntity.hasField('name'):
      sgEntity.addField(ApiUserNameField())

################################################################################
#
# Register the callback with ShotgunORM onEntityCreate().
#
################################################################################

ShotgunORM.addOnEntityCreate(
  addApiUserNameField,
  filterName='ApiUser',
  description='callback that adds a name field to ApiUser Entity objects'
)
예제 #50
0
  def __init__(self):
    super(SgProjectCreatedHandler, self).__init__()

    self.addFilter(ShotgunORM.SgProjectCreatedFilter())
예제 #51
0
  def __init__(self):
    super(SgSequenceCreatedHandler, self).__init__()

    self.addFilter(ShotgunORM.SgSequenceCreatedFilter())
예제 #52
0
          fieldNames = batch['data'].keys()

          for field in self.fields(fieldNames).values():
            field.setIsCommitting(False)

    error = None

    try:
      self._afterCommit(sgBatchData, sgBatchResult, sgCommitData, sgCommitError)
    except Exception, e:
      error = e

    batchDataCopy = copy.deepcopy(sgBatchData)

    try:
      ShotgunORM.afterEntityCommit(self, batchDataCopy, sgBatchResult, sgCommitData, sgCommitError)
    except Exception, e:
      if error == None:
        error = e

    if error != None:
      raise error

  def _beforeCommit(self, sgBatchData, sgCommitData):
    '''
    Subclass portion of SgEntity.beforeCommit().

    ** The Entity is locked down when this is called **

    Args:
      * (dict) sgBatchData: