Skip To Content

Ejemplo: Registrar carpetas y bases de datos listados en un archivo de texto

Este script de ejemplo utiliza una lista de archivos de texto de las carpetas y las bases de datos que desea registrar con un sitio de ArcGIS Server. Aunque puede registrar bases de datos y carpetas con sitios de ArcGIS Server federados utilizando ArcGIS Pro o el portal de ArcGIS Enterprise y registrar bases de datos y carpetas con sitios de ArcGIS Server independientes usando ArcGIS Pro o ArcGIS Server Manager, puede ser más rápido usar esta secuencia de comandos si tiene que registrar muchas ubicaciones de fuente de datos.

Sugerencia:

Consulte Fuentes de datos para ArcGIS Server para obtener más información sobre por qué registra ubicaciones de datos con un sitio de ArcGIS Server.

Estructure el archivo de texto de entrada de la siguiente manera:

#dsName|dsType|serverPath|clientPath|hostname

dsName=<data store name>|dsType={FOLDER | DATABASE}|serverPath=<path to folder or database connection file used by the ArcGIS Server site>|clientPath=<path to folder or database connection file used by the publishing client>

  • dsName: nombre para el elemento del data store. Puede ser cualquier nombre.
  • dsType: tipo de elemento del data store que se registra. Para este ejemplo, puede utilizar FOLDER o DATABASE.
  • serverPath: ruta hasta los datos tal como la ve el equipo del servidor.
  • clientPath: la ruta hasta los datos tal como la ven los equipos de los publicadores. Si no se indica, se utilizará la ruta del servidor. Si suministra la palabra clave managed, significa que se registra el elemento de data store como la base de datos gestionada del sitio de ArcGIS Server.
  • hostname: el nombre del equipo del publicador. Esto solo es necesario cuando clientPath es una ruta basada en carpetas. Si se omite esta propiedad, se utiliza el nombre del equipo donde se ejecuta la secuencia de comandos.

En este ejemplo, se muestran dos rutas de carpeta y dos archivos de conexión de base de datos en el archivo de texto. La segunda ruta de carpeta (testData) tiene una ubicación diferente para el sitio de ArcGIS Server y el cliente de ArcGIS local.

#dsName|dsType|serverPath|clientPath|hostname

dsName=sharedData|dsType=FOLDER|serverPath=\\sharedserver\data|clientPath=\\sharedserver\data
dsName=testData|dsType=FOLDER|serverPath=\\test_server\data|clientPath=c:\mydata|hostname=qalab_publisher
dsName=entGeodatabase|dsType=DATABASE|serverPath=C:\data\db_connections\Connection to enterprisegdb1.sde|clientPath=C:\data\db_Connections\Connection to enterprisegdb1.sde
dsName=spatialDatabase|dsType=DATABASE|serverPath=C:\data\db_Connections\Connection to projectdb.sde|clientPath=C:\data\db_Connections\Connection to projectdb.sde

La siguiente secuencia de comandos de muestra le solicita información de conexión del sitio de ArcGIS Server para crear un archivo de conexión de ArcGIS Server. También le solicita que especifique la ubicación del archivo de texto que contiene la lista de fuentes de datos y registra las fuentes de datos en el archivo con el sitio de ArcGIS Server.

import sys
import os
import getpass
import arcpy
import codecs


def main(argv=None):
    
    # Ask for admin user name and password
    
    username = input("Enter user name: ")
    password = getpass.getpass("Enter password: ")
    
    # Ask for server name & port
    serverName = input("Enter server name: ")
    serverPort = input("Enter server port: ")
 
    # Create a connection file to the server and save it in the same location as that of the script
    serverURL="http://"+serverName+":"+str(serverPort)+"/arcgis/admin"
    try:
        arcpy.mapping.CreateGISServerConnectionFile("PUBLISH_GIS_SERVICES",os.curdir,serverName+".ags",serverURL,"ARCGIS_SERVER",username=username,password=password)
    except Exception as e:
        print(e)
    
    agsConnection = os.path.join(os.curdir, serverName+".ags")
    
    if not os.path.isfile(agsConnection):
        print("Unable to connect to ArcGIS Server. Exiting.")
        sys.exit(1)

    # Input File that contains the data store information
    dataStoresFile = input("Path to pipe-delimited text file containing datastore information: ")
    
    num = 0 
    datastores = {}
    
    for datastoreRow in readlinesFromInputFile(dataStoresFile):
            
        datastoreEntry = {}
        
        for index in range(len(datastoreRow)):
            
            datastoreProp = datastoreRow[index].split("=")
            
            if datastoreProp[0] == "dsName":
                datastoreEntry["connection_name"] = datastoreProp[1]
            if datastoreProp[0] == "dsType":
                datastoreEntry["datastore_type"] = datastoreProp[1]
            if datastoreProp[0] == "serverPath":
                datastoreEntry["server_path"] = datastoreProp[1]
            if datastoreProp[0] == "clientPath":
                datastoreEntry["client_path"] = datastoreProp[1]
            if datastoreProp[0] == "hostname":
                datastoreEntry["hostname"] = datastoreProp[1]
         
            # Add the datastore information to a dictionary
            datastores["datastore" + str(num)] = datastoreEntry
        
        num +=1

    # Call helper functions to register datastores
    addDataStores(datastores,agsConnection)


# A function that reads lines from the input file
def readlinesFromInputFile(filename, delim='|'):
    file = codecs.open(filename,'r','utf-8-sig')
    for line in file.readlines():
        # Remove the trailing whitespaces and the newline characters
        line = line.rstrip()
        
        if line.startswith('#') or len(line) == 0:
            pass # Skip the lines that contain # at the beginning or any empty lines
        else:
            # Split the current line into list
            yield line.split(delim)
    file.close()


def addDataStores(datastoresDict,agsConnection):
    
    for datastoreToAdd in datastoresDict:
        # Build the dictionary with the role name and description               
        datastoresDict[datastoreToAdd]["connection_file"] =  agsConnection
        
        print("Adding the datastore: " + datastoresDict[datastoreToAdd]['connection_name'])
        
        try:
            arcpy.AddDataStoreItem(**datastoresDict[datastoreToAdd])
            print("Successfully added the datastore: " + datastoresDict[datastoreToAdd]['connection_name'])
        except Exception as e:
            print("Adding of the datastore: " + datastoresDict[datastoreToAdd]['connection_name'] + " failed.")
            print(e)

if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))