MapServiceDraft

Résumé

The MapServiceDraft class allows you to create a service definition draft (.sddraft) file for a map service that copies all data or references registered data to ArcGIS Server.

Discussion

To create a MapServiceDraft object, use the arcpy.sharing.CreateSharingDraft function and set the server_type parameter to STANDALONE_SERVER and the service_type parameter to MAP_SERVICE. The MapServiceDraft object can then be configured by setting service level properties and metadata properties. Use the targetServer property to specify the server to which the map service is published.

Remarque :

If metadata properties (credits, description, summary, tags, and useLimitations) are not set or consist of empty strings, the map service will source metadata from the map.

For more information about authoring metadata, see View and edit metadata.

After the MapServiceDraft object is configured, it can be saved to a service definition draft (.sddraft) file using the exportToSDDraft function. It can then be staged and shared to ArcGIS Server using the Stage Service and Upload Service Definition tools. For more information, see Introduction to arcpy.sharing.

Once the .sddraft file has been staged and uploaded to the server, the tools in the Caching toolset can be used to create and manage map server caches for faster display of map services, such as the Manage Map Server Cache Tiles tool. The tiling scheme can also be modified by editing the .sddraft file using XML libraries such as the xml.dom.minidom library. However, due to the complexity of the tiling scheme XML structure, it is recommended that you use the Caching toolset whenever possible.

Code samples are available for the following:

Propriétés

PropriétéExplicationType de données
checkUniqueIDAssignment
(Lecture et écriture)

A Boolean that indicates whether your map is analyzed to confirm that the Allow assignment of unique numeric IDs for sharing web layers option in Map Properties is enabled. For more information, see Assign layer IDs.

Boolean
copyDataToServer
(Lecture et écriture)

Specifies whether the data in your map will be copied to the server. A value of True will copy all of the data in your map, including data that is registered with your server. A value of False will only copy data that is not registered with your server; data registered with your server will be referenced by the service.

Boolean
credits
(Lecture et écriture)

The credits of the map service draft.

String
description
(Lecture et écriture)

The description of the map service draft.

String
offline
(Lecture et écriture)

Specifies whether to use a server connection. If set to False, you must provide a server URL or an ArcGIS Server connection file (.ags) to the targetServer property to create a service definition draft (.sddraft) file using the exportToSDDraft function. If set to True, a service definition draft file can be created without populating the targetServer property.

Boolean
overwriteExistingService
(Lecture et écriture)

Specifies whether an existing service with the same name will be overwritten.

Boolean
serverFolder
(Lecture et écriture)

The name of a server folder to which you want to publish the service. The default folder is the root folder of the server. The folder will be created if it does not already exist.

String
serverType
(Lecture seule)

The server type as specified when the MapServiceDraft was created from the CreateSharingDraft function. The only possible value returned from serverType for a MapServiceDraft is STANDALONE_SERVER. A serverType of STANDALONE_SERVER indicates support for creating a map service for ArcGIS Server.

String
serviceName
(Lecture et écriture)

The name of the map service. This is the name people will see and use to identify the service. The name can only contain alphanumeric characters and underscores. No spaces or special characters are allowed. The name cannot be more than 120 characters.

String
summary
(Lecture et écriture)

The summary of the map service draft.

String
tags
(Lecture et écriture)

The tags of the map service draft. Tags can be separated by commas or semicolons.

String
targetServer
(Lecture et écriture)

The server to which the map will be published. The server can be specified using either of the following formats:

  • The full path to an ArcGIS Server connection file (.ags).
  • An ArcGIS Server URL. Use this option when you have a publisher or administrator connection to ArcGIS Server in the ArcGIS Pro project and you are opening the project in the script or running the script in ArcGIS Pro.

For more information, see Connect to a GIS server.

Conseil :

The targetServer can also be used in the in_server parameter in the Upload Service Definition tool. The code samples below demonstrate this.

String
useLimitations
(Lecture et écriture)

The use limitations of the map service draft.

String

Vue d’ensemble des méthodes

MéthodeExplication
exportToSDDraft (out_sddraft)

Converts a MapServiceDraft to a service definition draft (.sddraft) file.

Méthodes

exportToSDDraft (out_sddraft)
ParamètreExplicationType de données
out_sddraft

The path and file name for the output service definition draft (.sddraft) file.

String

Once the MapServiceDraft is configured, it can be saved as a service definition draft (.sddraft) file. It can then be staged and shared to ArcGIS Server using the Stage Service and Upload Service Definition tools.

Exemple de code

Publish a map service to a server folder

The following script creates a map service definition draft (.sddraft) file for a map and sets metadata properties. The map service is published to a folder in a stand-alone ArcGIS Server.

import arcpy
import os

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set metadata and server folder properties
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection
sddraft.credits = "These are credits"
sddraft.description = "This is description"
sddraft.summary = "This is summary"
sddraft.tags = "tag1, tag2"
sddraft.useLimitations = "These are use limitations"
sddraft.serverFolder = "MyServerFolder"

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

# Stage Service
print("Start Staging")
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

print("Finish Publishing")
Overwrite a map service

The following script overwrites a map service. If the service name already exists, the service will be overwritten. Otherwise, a new service will be created.

import arcpy
import os

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set overwrite property
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection
sddraft.overwriteExistingService = True

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

# Stage Service
print("Start Staging")
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

print("Finish Publishing")
Publish a map service with a feature service

The following script creates a map service definition draft (.sddraft) file that references registered data. The data store must be already registered on the server for the data to be referenced. It then enables the feature capability and sets map service and feature service properties by modifying the service definition draft file using the xml.dom.minidom standard Python library. The modified service definition draft file is then staged and published to ArcGIS Server.

import arcpy
import os
import xml.dom.minidom as DOM

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set copyDataToServer property to false to reference registered data
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection
sddraft.copyDataToServer = False

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

"""Modify the .sddraft file to enable the feature capability and set map service and feature service properties"""
# Read the file
doc = DOM.parse(sddraft_output_filename)

# Find all elements named TypeName
# This is where the extensions are defined
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
    # Get the TypeName to enable
    if typeName.firstChild.data == "FeatureServer":
        extension = typeName.parentNode
        for extElement in extension.childNodes:
            # Enable the feature capability
            if extElement.tagName == 'Enabled':
                extElement.firstChild.data = 'true'

# Set map service properties
configProps = doc.getElementsByTagName('Info')[0]
propArray = configProps.firstChild
propSets = propArray.childNodes
for propSet in propSets:
    keyValues = propSet.childNodes
    for keyValue in keyValues:
        if keyValue.tagName == 'Key':
            if keyValue.firstChild.data == "WebCapabilities":
                # Defaults are Map,Query,Data
                keyValue.nextSibling.firstChild.data = "Map,Data"

# Set feature service properties
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
    # Get the TypeName to enable
    if typeName.firstChild.data == "FeatureServer":
        extension = typeName.parentNode
        for extElement in extension.childNodes:
            if extElement.tagName == 'Info':
                for propSet in extElement.childNodes:
                    for prop in propSet.childNodes:
                        for prop1 in prop.childNodes:
                            if prop1.tagName == "Key":
                                if prop1.firstChild.data == 'WebCapabilities':
                                    # Defaults are Query,Create,Update,Delete,Uploads,Editing
                                    prop1.nextSibling.firstChild.data = "Create,Sync,Query"

# Write to a new .sddraft file
sddraft_mod_xml = service_name + '_mod_xml' + '.sddraft'
sddraft_mod_xml_file = os.path.join(outdir, sddraft_mod_xml)
f = open(sddraft_mod_xml_file, 'w')
doc.writexml(f)
f.close()

# Stage Service
print("Start Staging")
arcpy.StageService_server(sddraft_mod_xml_file, sd_output_filename)

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

print("Finish Publishing")
Publish a cached map service

The following script publishes a cached map service by calling the Manage Map Server Cache Tiles tool to create map service cache tiles.

import arcpy
import os
import xml.dom.minidom as DOM

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

"""Modify the .sddraft to enable caching"""
# Read the file
doc = DOM.parse(sddraft_output_filename)

configProps = doc.getElementsByTagName('ConfigurationProperties')[0]
propArray = configProps.firstChild
propSets = propArray.childNodes
for propSet in propSets:
    keyValues = propSet.childNodes
    for keyValue in keyValues:
        if keyValue.tagName == 'Key':
            if keyValue.firstChild.data == "isCached":
                keyValue.nextSibling.firstChild.data = "true"

# Write to a new .sddraft file
sddraft_mod_xml = service_name + '_mod_xml' + '.sddraft'
sddraft_mod_xml_file = os.path.join(outdir, sddraft_mod_xml)
f = open(sddraft_mod_xml_file, 'w')
doc.writexml(f)
f.close()

try:
    # Stage Service
    print("Start Staging")
    arcpy.StageService_server(sddraft_mod_xml_file, sd_output_filename)
    warnings = arcpy.GetMessages(1)
    print(warnings)

    # Publish to server
    print("Start Uploading")
    arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)
    print("Finish Publishing")

    # Manage Map server Cache Tiles
    # For cache, use multiple scales separated by semicolon (;)
    # For example, "591657527.591555;295828763.795777"
    arcpy.server.ManageMapServerCacheTiles(target_server_connection + "/" + service_name + ".MapServer", "591657527.591555", "RECREATE_ALL_TILES")
except Exception as stage_exception:
    print("Analyzer errors encountered - {}".format(str(stage_exception)))

except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))
Publish a map service that draws from existing cache

The following script creates a map service definition draft (.sddraft) file for a map. It then uses an existing cache to draw the service by modifying the service definition draft file using the xml.dom.minidom standard Python library. The modified service definition draft file is then staged and published to ArcGIS Server.

import arcpy
import os
import xml.dom.minidom as DOM

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

"""Modify the .sddraft file to keep existing cache"""
# Read the file
doc = DOM.parse(sddraft_output_filename)
# Turn off caching
configProps = doc.getElementsByTagName('ConfigurationProperties')[0]
propArray = configProps.firstChild
propSets = propArray.childNodes
for propSet in propSets:
    keyValues = propSet.childNodes
    for keyValue in keyValues:
        if keyValue.tagName == 'Key':
            if keyValue.firstChild.data == "isCached":
                keyValue.nextSibling.firstChild.data = "false"

# Use existing cache
configProps = doc.getElementsByTagName('KeepExistingMapCache')[0]
configProps.firstChild.data = "true"

# Write to a new .sddraft file
sddraft_mod_xml = service_name + '_mod_xml' + '.sddraft'
sddraft_mod_xml_file = os.path.join(outdir, sddraft_mod_xml)
f = open(sddraft_mod_xml_file, 'w')
doc.writexml(f)
f.close()

# Stage Service
print("Start Staging")
arcpy.StageService_server(sddraft_mod_xml_file, sd_output_filename)

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

print("Finish Publishing")
Analyze and register a data store

The following script creates a map service definition draft (.sddraft) file for a map. The service definition draft file is analyzed during staging. If analyzer 24011 is returned warning that the data source is not registered with the server, the data store is registered using the AddDataStoreItem function.

import arcpy
import os

arcpy.env.overwriteOutput = True

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set copyDataToServer property to False to reference registered data
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection
sddraft.copyDataToServer = False

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

# Stage the service and analyze the .sddraft file for registered data store
# Continue publishing only if data store is registered
print("Start Staging")
stage_service = True
while stage_service:
    arcpy.StageService_server(sddraft_output_filename, sd_output_filename)
    # Get analyzer warnings to check if data store is registered
    warnings = arcpy.GetMessages(1)
    print(warnings)
    # If data store is not registered
    if "24011" in warnings:
        # Register data store
        db_conn = r"C:\Project\db_conn.sde"
        register_msg = arcpy.AddDataStoreItem(target_server_connection, "DATABASE", "datastore_name", db_conn)
        print("Registered datastore: {0}".format(register_msg))
        # Stage the service again
        stage_service = True
    else:
        stage_service = False

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

print("Finish Publishing")
Set a time zone and configure pooling

The following script creates a map service definition draft (.sddraft) file for a map. The data store must be already registered on the server for the data to be referenced. It then sets a time zone for layers with date fields and configures service instance settings by modifying the service definition draft file using the xml.etree.ElementTree and xml.dom.minidom standard Python libraries. The modified service definition draft file is then staged and published to ArcGIS Server.

import arcpy
import os
import xml.dom.minidom as DOM
import codecs
import xml.etree.ElementTree as ET

def enable_extensions(sddraftPath, soe):
    """Function to enable extensions"""
    # Read the .sddraft file
    doc = DOM.parse(sddraftPath)

    # Find all elements named TypeName
    # This is where the additional layers and capabilities are defined
    typeNames = doc.getElementsByTagName('TypeName')
    for typeName in typeNames:
        # Get the TypeName to enable
        if typeName.firstChild.data == soe:
            extension = typeName.parentNode
            for extElement in extension.childNodes:
                # Enable the feature capability
                if extElement.tagName == 'Enabled':
                    extElement.firstChild.data = 'true'

    # Write to the .sddraft file
    f = open(sddraftPath, 'w')
    doc.writexml(f)
    f.close()

# soe = extension for which properties must be added
def enable_configproperties(sddraftPath, soe, property_set):
    """Function to configure extension properties"""
    # Read the file
    doc = DOM.parse(sddraftPath)

    # Find all elements named TypeName
    # This is where the extensions are defined
    typeNames = doc.getElementsByTagName('TypeName')
    for typeName in typeNames:
        # Get the TypeName to enable
        if typeName.firstChild.data == soe:
            extension = typeName.parentNode
            # prp = extension.childNodes.getElementsByTagNameNS('PropertyArray')
            for extElement in extension.childNodes:
                if extElement.tagName == 'Definition':
                    for definition in extElement.childNodes:
                        if definition.tagName == 'ConfigurationProperties':
                            for config_prop in definition.childNodes:
                                if config_prop.tagName == 'PropertyArray':
                                    for prop in property_set:
                                        prop_set = doc.createElement("PropertySetProperty")
                                        attr = doc.createAttribute("xsi:type")
                                        attr.value = "typens:PropertySetProperty"
                                        prop_set.setAttributeNode(attr)

                                        prop_key = doc.createElement("Key")
                                        txt = doc.createTextNode(prop["key"])
                                        prop_key.appendChild(txt)
                                        prop_set.appendChild(prop_key)

                                        prop_value = doc.createElement("Value")
                                        attr = doc.createAttribute("xsi:type")
                                        attr.value = "xs:string"
                                        prop_value.setAttributeNode(attr)
                                        txt = doc.createTextNode(prop["value"])
                                        prop_value.appendChild(txt)
                                        prop_set.appendChild(prop_value)

                                        config_prop.appendChild(prop_set)
    # Write to the .sddraft file
    f = open(sddraftPath, 'w')
    doc.writexml(f)
    f.close()

if __name__ == "__main__":

    # Set output file names
    outdir = r"C:\Project\Output"
    service_name = "MapServiceDraftExample"
    sddraft_filename = service_name + ".sddraft"
    sddraft_output_filename = os.path.join(outdir, sddraft_filename)
    sd_filename = service_name + ".sd"
    sd_output_filename = os.path.join(outdir, sd_filename)

    # Reference map to publish
    aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
    m = aprx.listMaps('World')[0]

    # Create MapServiceDraft and set copyDataToServer property to False to reference registered data
    target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
    sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
    sddraft.targetServer = target_server_connection
    sddraft.copyDataToServer = False
    sddraft.exportToSDDraft(sddraft_output_filename)

    # Set time zone to UTC
    property_set = [{
        "key": "dateFieldsRespectsDayLightSavingTime",
        "value": "true"
    },
        {
            "key": "dateFieldsTimezoneID",
            "value": "UTC"
        }]
    enable_configproperties(sddraft_output_filename, soe="MapServer", property_set=property_set)

    # Enable extensions on map server
    enable_extensions(sddraft_output_filename, "FeatureServer")
    # enable_extensions(sddraft_output_filename, "VersionManagementServer")
    # enable_extensions(sddraft_output_filename, "LRServer")

    # Configure pooling options
    doc = DOM.parse(sddraft_output_filename)
    def_childnodes = doc.getElementsByTagName("Definition")[0].childNodes
    for def_node in def_childnodes:
        if def_node.nodeName == "Props":
            for node in def_node.childNodes[0].childNodes:
                # Change the provider to modify instance type
                # provider='DMaps' for shared or 'ArcObjects11' for dedicated
                if node.firstChild.firstChild.data == 'provider':
                    node.lastChild.firstChild.data = 'ArcObjects11'
                elif node.firstChild.firstChild.data == 'MinInstances':
                    node.lastChild.firstChild.data = '0'
                elif node.firstChild.firstChild.data == 'MaxInstances':
                    node.lastChild.firstChild.data = '2'

    # Write to the .sddraft file
    f = open(sddraft_output_filename, 'w')
    doc.writexml(f)
    f.close()

    # Stage Service
    print("Start Staging")
    arcpy.StageService_server(sddraft_output_filename, sd_output_filename)

    # Publish to server
    print("Start Uploading")
    arcpy.UploadServiceDefinition_server(sd_output_filename, target_server_connection)

    print("Finish Publishing")
Create and publish an offline service definition

The following script creates an offline service definition and publishes it as a map service.

import arcpy
import os

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set offline property
# The targetServer property is not needed when the offline property is set to True
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.offline = True

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

# Stage Service
print("Start Staging")
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)

# Publish to server
print("Start Uploading")
arcpy.UploadServiceDefinition_server(sd_output_filename, r"C:\Project\gisserver.ags.esri.com (publisher).ags")

print("Finish Publishing")
Analyze to confirm map is set to allow assignment of unique numeric IDs

The following script creates a map service definition draft (.sddraft) file that enables the checkUniqueIDAssignment property. The service definition draft file is analyzed during staging. If the map is not set to allow assignment of unique numeric IDs for sharing web layers, analyzer error 00374 is returned and a message is printed. For more information, see Assign layer IDs.

import arcpy
import os

# Set output file names
outdir = r"C:\Project\Output"
service_name = "MapServiceDraftExample"
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)

# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"C:\Project\World.aprx")
m = aprx.listMaps('World')[0]

# Create MapServiceDraft and set the check unique ID assignment property
target_server_connection = r"C:\Project\gisserver.ags.esri.com (publisher).ags"
sddraft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service_name, m)
sddraft.targetServer = target_server_connection
sddraft.checkUniqueIDAssignment = True

# Create Service Definition Draft file
sddraft.exportToSDDraft(sddraft_output_filename)

try:
    # Stage Service
    print("Start Staging")
    arcpy.StageService_server(sddraft_output_filename, sd_output_filename)
    # Share to portal
    print("Start Uploading")
    arcpy.UploadServiceDefinition_server(sd_output_filename, server_type)

    print("Finish Publishing")
except Exception as stage_exception:
    if "00374" in str(stage_exception):
        print("The map is not set to allow assignment of unique IDs")
    print("Analyzer errors encountered - {}".format(str(stage_exception)))

except arcpy.ExecuteError:
    print(arcpy.GetMessages(2))

Rubriques connexes