code: def create_spatial_index(layer):
      
      request = QgsFeatureRequest().setSubsetOfAttributes([])
      try:
          spatial_index = QgsSpatialIndex(layer.getFeatures(request))
      except BaseException:
          # Spatial index is creating an unknown exception.
          # https://github.com/inasafe/inasafe/issues/4304
          # or https://gitter.im/inasafe/inasafe?at=5a2903d487680e6230e0359a
          LOGGER.warning(
              'An Exception has been raised from the spatial index creation. '
              'We will clean your layer and try again.')
          new_layer = clean_layer(layer)
          try:
              spatial_index = QgsSpatialIndex(new_layer.getFeatures())
          except BaseException:
              # We got another exception.
              # We try now to insert feature by feature.
              # It's slower than the using the feature iterator.
              spatial_index = QgsSpatialIndex()
              for feature in new_layer.getFeatures(request):
                  try:
                      spatial_index.insertFeature(feature)
                  except BaseException:
                      LOGGER.critical(
                          'A feature has been removed from the spatial index.')
  
              # # We tried one time to clean the layer, we can't do more.
              # LOGGER.critical(
              #     'An Exception has been raised from the spatial index '
              #     'creation. Unfortunately, we already try to clean your '
              #     'layer. We will stop here the process.')
              # raise SpatialIndexCreationError
      return spatial_index
docs: Helper function to create the spatial index on a vector layer.
  
      This function is mainly used to see the processing time with the decorator.
  
      :param layer: The vector layer.
      :type layer: QgsVectorLayer
  
      :return: The index.
      :rtype: QgsSpatialIndex