CreateMapSDDraft (arcpy.mapping)

摘要

将地图文档 (.mxd) 文件转换为服务定义草稿 (.sddraft) 文件。

讨论

CreateMapSDDraft 是使用 ArcPy 将地图文档自动发布到 GIS Server 的第一步。通过 CreateMapSDDraft 创建的输出是服务定义草稿 (.sddraft) 文件。服务定义草稿由地图文档、服务器信息和一组服务属性组合而成。

服务器信息包括服务器连接或已发布的服务器类型,正在发布的服务的类型,服务的元数据(项目信息)和数据参考(是否向服务器复制数据)。

服务属性包括服务是否支持缓存以及缓存设置(如果支持)。还包括服务的其他附加功能(如要素访问或 OGC 功能)以及为所选功能设置的相应属性集。此方法最初使用一组默认的服务属性。用户可以使用标准的第三方 XML 编辑器编辑这些属性。此外,用户可以使用第三方 XML 库(如 xml.dom.minidom 标准 Python 库)自动实现属性修改。请参见以下修改 SDDraft 示例。

注注:

草稿服务定义不包含数据。草稿服务不能单独用于发布服务。

AnalyzeForSD 函数相似,CreateMapSDDraft 也会返回一份包含错误和其他潜在问题的 Python 字典,创建服务定义文件之前应解决这些错误和问题。有关错误、警告和信息性消息的类型,以及如何访问它们的详细信息,请参阅 AnalyzeForSD

可在特定服务器连接信息未知的情况下编写服务定义草稿。在这种情况下,可以省略 connection_file_path 参数;但是,必须提供 server_type。可在使用上载服务定义工具发布服务定义草稿后提供服务器连接。

随后,可使用过渡服务工具将服务定义草稿转换为完全合并的服务定义 (.sd) 文件。过渡过程会编译成功发布 GIS 资源所需的所有必要信息。如果未将数据注册到服务器,将在过渡服务定义草稿时添加这些数据。最后,可以使用上载服务定义工具上载服务定义文件并将其作为 GIS 服务发布到特定的 GIS 服务器。此步骤将获取服务定义文件、将其复制到服务器、提取所需信息并发布 GIS 资源。有关详细信息,请参阅发布工具集概述

.sddraft 文件过渡并上传到服务器后,可使用缓存工具集中的工具(如创建地图服务器缓存工具)为已启用缓存的服务创建切片方案。此外,缓存工具集中的工具也可用于修改已启用缓存的服务的缓存和切片属性。例如,可使用管理地图服务器缓存比例工具添加新比例或者从缓存中删除现有比例。修改 SDDraft 示例 6 演示了该过程。还可以使用第三方 XML 库(如 xml.dom.minidom 标准 Python 库)编辑 .sddraft 文件以修改切片方案。然而,由于切片方案 XML 结构比较复杂,建议尽量使用缓存工具集。

将托管服务发布到 ArcGIS OnlinePortal for ArcGIS 时,从 ArcGIS for Desktop 主菜单上的文件 > 登录对话框中获取登录信息。此外,还可使用登录门户工具为 Portal for ArcGIS 中的一些安全配置指定登录信息。有关托管服务以及登录 ArcGIS OnlinePortal for ArcGIS 的详细信息,请参阅以下主题:

注注:

ArcGIS for Server Administrator API 还可用于编写在服务器上执行常用操作的脚本。例如,启动和停止服务、编辑服务属性(如最大实例数)、授予和撤消用户对服务的权限等。

您还可以为地理处理、影像和地理编码服务创建服务定义草稿文件。请参阅以下相关函数:

语法

CreateMapSDDraft (map_document, out_sddraft, service_name, {server_type}, {connection_file_path}, {copy_data_to_server}, {folder_name}, {summary}, {tags})
参数说明数据类型
map_document

A variable that references a MapDocument object.

MapDocument
out_sddraft

A string that represents the path and file name for the output Service Definition Draft (.sddraft) file.

String
service_name

A string that represents the name of the 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 in length.

String
server_type

A string representing the server type. If a connection_file_path parameter is not supplied, then a server_type must be provided. If a connection_file_path parameter is supplied, then the server_type is taken from the connection file. In this case, you can choose FROM_CONNECTION_FILE or skip the parameter entirely.

  • ARCGIS_SERVERArcGIS for Server server type
  • FROM_CONNECTION_FILEGet the server_type as specified in the connection_file_path parameter
  • MY_HOSTED_SERVICESMy Hosted Services server type for ArcGIS Online or Portal for ArcGIS

法律声明法律声明:

Starting at ArcGIS 10.2.1 for Desktop, SPATIAL_DATA_SERVER is not a supported server_type. For more information, see What's new in ArcGIS 10.2.1 for Server.

(默认值为 ARCGIS_SERVER)

String
connection_file_path

A string that represents the path and file name to the ArcGIS for Server connection file (.ags).

When the server_type is set to MY_HOSTED_SERVICES, connection_file_path is not required.

String
copy_data_to_server

A Boolean that indicates whether the data referenced in the map document will be copied to the server or not. The copy_data_to_server parameter is only used if the server_type is ARCGIS_SERVER and the connection_file_path isn't specified. If the connection_file_path is specified, then the server's registered data stores are used. For example, if the data in the map_document is registered with the server, then copy_data_to_server will always be False. Conversely, if the data in the map_document is not registered with the server, then copy_data_to_server will always be True.

When the server_type is set to MY_HOSTED_SERVICES, copy_data_to_server will always be True. My Hosted Maps services always copy data to the server.

(默认值为 False)

Boolean
folder_name

A string that represents a folder name to which you want to publish the service definition. If the folder does not currently exist, it will be created. The default folder is the server root level.

(默认值为 None)

String
summary

A string that represents the Item Description Summary.

By default, the Summary from the ArcMap Map Properties dialog box or Catalog window Item Description dialog box for the map_document will be used. Use this parameter to override the user interface summary, or to provide a summary if one does not exist. The summary provided here will not be persisted in the map document.

(默认值为 None)

String
tags

A string that represents the Item Description Tags.

By default, the Tags from the ArcMap Map Properties dialog box or Catalog window Item Description dialog box for the map_document will be used. Use this parameter to override the user interface tags, or to provide tags if they do not exist. The tags provided here will not be persisted in the map document.

(默认值为 None)

String
返回值
数据类型说明
Dictionary

返回由信息性消息、警告和错误组成的 Python 字典。

代码实例

CreateMapSDDraft 示例 1

以下脚本演示使用 arcpy.mapping 工作流发布地图服务的完整过程。通过将 arcpy.mapping 函数与发布工具集中的地理处理工具加以组合,可实现地图服务的自动发布。工作流开始于要发布的地图文档。首先,使用 arcpy.mapping 函数 CreateMapSDDraft 创建服务定义草稿。请注意,使用 summarytags 参数会覆盖输入地图文档的“项目描述”、“摘要”和“标签”。接下来,应对服务定义草稿进行分析,以找出可能会阻止成功发布的问题。分析服务定义草稿并解决严重问题后,即可开始过渡服务定义。过渡操作获取服务定义草稿并将发布服务所需的所有信息合并到完整的服务定义中。使用过渡服务地理处理工具过渡服务定义。最后,使用上传服务定义地理处理工具将服务定义上传到服务器并发布地图服务。

import arcpy

# define local variables
wrkspc = 'C:/Project/'
mapDoc = arcpy.mapping.MapDocument(wrkspc + 'counties.mxd')
con = 'GIS Servers/arcgis on MyServer_6080 (publisher).ags' 
service = 'Counties'
sddraft = wrkspc + service + '.sddraft'
sd = wrkspc + service + '.sd'
summary = 'Population Density by County'
tags = 'county, counties, population, density, census'

# create service definition draft
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', 
                                          con, True, None, summary, tags)

# stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {}:
    # Execute StageService
    arcpy.StageService_server(sddraft, sd)
    # Execute UploadServiceDefinition
    arcpy.UploadServiceDefinition_server(sd, con)
else: 
    # if the sddraft analysis contained errors, display them
    print analysis['errors']
CreateMapSDDraft 示例 2

以下示例脚本通过地图文档 (.mxd) 创建服务定义草稿 (.sddraft) 文件。然后,打印包含由 CreateMapSDDraft 函数返回的错误、警告和信息的 Python 字典。Python 字典中包含的分析信息有助于识别可能需要在创建服务定义 (.sd) 文件之前解决的潜在性瓶颈和地图错误。此脚本还演示了如何在不指定服务器连接信息的情况下创建服务定义草稿。

import arcpy

mapDoc = arcpy.mapping.MapDocument('C:/Project/counties.mxd') 
service = 'Counties'
sddraft = 'C:/Project/' + service + '.sddraft'
        
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER')

for key in ('messages', 'warnings', 'errors'):
  print "----" + key.upper() + "---"
  vars = analysis[key]
  for ((message, code), layerlist) in vars.iteritems():
    print "    ", message, " (CODE %i)" % code
    print "       applies to:",
    for layer in layerlist:
        print layer.name,
    print
CreateMapSDDraft 示例 3

以下示例脚本通过地图文档 (.mxd) 为我的托管服务创建服务定义草稿 (.sddraft) 文件。如果服务定义草稿没有分析错误,则使用过渡服务地理处理工具过渡此草稿。然后,使用上传服务定义地理处理工具将服务定义上传到 ArcGIS OnlinePortal for ArcGISArcGIS Online 登录信息可从 ArcGIS for Desktop 主菜单上的文件 > 登录对话框中获取。

import arcpy

mapDoc = arcpy.mapping.MapDocument('C:/Project/counties.mxd') 
service = 'Counties'
sddraft = 'C:/Project/{}.sddraft'.format(service)
sd = 'C:/Project/{}.sd'.format(service)

# create service definition draft
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'MY_HOSTED_SERVICES')

# stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {}:
    # create service definition
    arcpy.StageService_server(sddraft, sd)
    # publish to My Hosted Services
    arcpy.UploadServiceDefinition_server(sd, 'My Hosted Services')
else: 
    # if the sddraft analysis contained errors, display them
    print analysis['errors']
修改 SDDraft 示例 1

下列脚本使用 xml.dom.minidom 标准 Python 库修改“项目信息描述”元素。修改后的服务定义草稿 (.sddraft) 文件随后被保存到新文件中。最后,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。

import arcpy
import xml.dom.minidom as DOM 
# the new description
newDesc = 'US Counties Map'
xml = r"C:\Project\Counties.sddraft"
doc = DOM.parse(xml)
# find the Item Information Description element 
descriptions = doc.getElementsByTagName('Description')
for desc in descriptions:
    if desc.parentNode.tagName == 'ItemInfo':
        # modify the Description
        if desc.hasChildNodes():
            desc.firstChild.data = newDesc
        else:
            txt = doc.createTextNode(newDesc)
            desc.appendChild(txt)
# output to a new sddraft
outXml = r"C:\Project\Output\CountiesForWeb.sddraft"     
f = open(outXml, 'w')     
doc.writexml( f )     
f.close() 

# analyze the new sddraft for errors
analysis = arcpy.mapping.AnalyzeForSD(outXml)
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print
修改 SDDraft 示例 2

下列脚本使用 xml.dom.minidom 标准 python 库修改过渡设置 TextAntialiasingMode 元素。修改后的服务定义草稿 (.sddraft) 文件随后被保存到新文件中。最后,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。

import arcpy
import xml.dom.minidom as DOM 
# the new TextAntiAliasingMode value
newTextAntialiasingMode = 'Normal'
xml = r"C:\Project\Counties.sddraft"
doc = DOM.parse(xml)
keys = doc.getElementsByTagName('Key')
for key in keys:
    if key.hasChildNodes():
        if key.firstChild.data == 'textAntialiasingMode':
	    # modify the TextAntiAliasingMode value
	    key.nextSibling.firstChild.data = newTextAntialiasingMode
			
# output to a new sddraft
outXml = r"C:\Project\Output\CountiesForWeb.sddraft"     
f = open(outXml, 'w')     
doc.writexml( f )     
f.close()

# analyze the new sddraft for errors
analysis = arcpy.mapping.AnalyzeForSD(outXml)
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print
修改 SDDraft 示例 3

以下示例脚本通过地图文档 (.mxd) 创建服务定义草稿 (.sddraft) 文件。然后,使用 xml.dom.minidom 标准 Python 库修改 .sddraft 文件以启用 WMSServer 功能并设置标题属性。随后,将修改后的 .sddraft 文件保存到新文件中。最后,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。

import arcpy
import xml.dom.minidom as DOM 

# Reference map document for CreateSDDraft function.
mapDoc = arcpy.mapping.MapDocument('C:/project/counties.mxd') 
# Create service and sddraft variables for CreateSDDraft function.
service = 'Counties'
sddraft = 'C:/Project/' + service + r'.sddraft'
  
# Create sddraft.
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER')

# These are the properties we will change in the sddraft xml.
soe = 'WMSServer'
soeProperty = 'title'
soePropertyValue = 'USACounties'

# Read the sddraft xml.
doc = DOM.parse(sddraft)
# Find all elements named TypeName. This is where the server object extension (SOE) names are defined.
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
    # Get the TypeName whose properties we want to modify.
    if typeName.firstChild.data == soe:
        extension = typeName.parentNode
        for extElement in extension.childNodes:
            # Enabled SOE.
            if extElement.tagName == 'Enabled':
                extElement.firstChild.data = 'true'
            # Modify SOE property. We have to drill down to the relevant property.
            if extElement.tagName == 'Props':
                for propArray in extElement.childNodes:
                    for propSet in propArray.childNodes:
                        for prop in propSet.childNodes:
                            if prop.tagName == "Key":
                                if prop.firstChild.data == soeProperty:
                                    if prop.nextSibling.hasChildNodes():
                                        prop.nextSibling.firstChild.data = soePropertyValue
                                    else:
                                        txt = doc.createTextNode(soePropertyValue)
                                        prop.nextSibling.appendChild(txt)
                                        
# Output to a new sddraft.
outXml = "C:/Project/Output/CountiesForWeb.sddraft"     
f = open(outXml, 'w')     
doc.writexml( f )     
f.close()       

# Analyze the new sddraft for errors.
analysis = arcpy.mapping.AnalyzeForSD(outXml)
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print
修改 SDDraft 示例 4

以下示例脚本通过地图文档 (.mxd) 创建服务定义草稿 (.sddraft) 文件。然后,使用 xml.dom.minidom 标准 Python 库修改 .sddraft 文件以禁用 KmlServer 功能。随后,将修改后的 .sddraft 文件保存到新文件中。最后,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。

import arcpy
import xml.dom.minidom as DOM 

# Reference map document for CreateSDDraft function.
mapDoc = arcpy.mapping.MapDocument('C:/project/counties.mxd')
# Create service and sddraft variables for CreateSDDraft function.
service = 'Counties'
sddraft = 'C:/Project/' + service + '.sddraft'
 
# Create sddraft.
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER')

# The Server Object Extension (SOE) to disable.
soe = 'KmlServer'

# Read the sddraft xml.
doc = DOM.parse(sddraft)
# Find all elements named TypeName. This is where the server object extension (SOE) names are defined.
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
    # Get the TypeName we want to disable.
    if typeName.firstChild.data == soe:
        extension = typeName.parentNode
        for extElement in extension.childNodes:
            # Disabled SOE.
            if extElement.tagName == 'Enabled':
                extElement.firstChild.data = 'false'
                                        
# Output to a new sddraft.
outXml = "C:/Project/Output/CountiesForWeb.sddraft"     
f = open(outXml, 'w')     
doc.writexml( f )     
f.close()       

# Analyze the new sddraft for errors.
analysis = arcpy.mapping.AnalyzeForSD(outXml)
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print
修改 SDDraft 示例 5

以下示例脚本通过地图文档 (.mxd) 为 ARCGIS_SERVER server_type 创建服务定义草稿 (.sddraft) 文件。然后,使用 xml.dom.minidom 标准 Python 库修改 .sddraft 文件以启用服务的缓存功能。随后,将修改后的 .sddraft 文件保存到新文件中。最后,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。

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

# define local variables
wrkspc = 'C:/Project/'
mapDoc = arcpy.mapping.MapDocument(wrkspc + 'counties.mxd')
con = 'GIS Servers\arcgis on MyServer_6080 (admin).ags' 
service = 'Counties'
sddraft = wrkspc + service + '.sddraft'
sd = os.path.join(wrkspc, "output", service + '.sd')

# create sddraft
if os.path.exists(sddraft): os.remove(sddraft)
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER')

# read sddraft xml
doc = DOM.parse(sddraft)

# turn on caching in the configuration properties
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":
                # turn on caching
                keyValue.nextSibling.firstChild.data = "true"
                
# output to a new sddraft
outXml = "C:\Project\Output\CountiesForWeb.sddraft"   
if os.path.exists(outXml): os.remove(outXml)
f = open(outXml, 'w')     
doc.writexml( f )     
f.close() 

# analyze new sddraft for errors
analysis = arcpy.mapping.AnalyzeForSD(outXml)

# print dictionary of messages, warnings and errors
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print

del f, doc, mapDoc
修改 SDDraft 示例 6

以下示例脚本通过地图文档 (.mxd) 为 ARCGIS_SERVER server_type 创建服务定义草稿 (.sddraft) 文件。然后,使用 xml.dom.minidom 标准 Python 库修改 .sddraft 文件以启用服务的缓存功能。随后,将修改后的 .sddraft 文件保存到新文件中。接下来,使用 AnalyzeForSD 函数分析新的 .sddraft 文件中是否包含错误。分析服务定义草稿后,即可开始过渡服务定义。使用过渡服务地理处理工具过渡服务定义。然后,使用上传服务定义地理处理工具将服务定义上传到服务器并发布地图服务。发布服务后,脚本随后调用管理地图服务器缓存比例地理处理工具,该工具在现有已缓存地图或影像服务中更新比例级别。使用此工具可添加新比例或从缓存中删除现有比例。最后,此脚本调用管理地图服务器缓存切片地理处理工具创建地图服务缓存切片。

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

# define local variables
wrkspc = 'C:/Project'
systemFolder = 'C:/Users/<username>/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog'
server = 'arcgis on MyServer_6080 (publisher)'
service = 'Counties'

# build paths to data
mapDoc = arcpy.mapping.MapDocument(os.path.join(wrkspc, 'counties.mxd'))
connection = os.path.join(systemFolder, server + '.ags')
mapServer = os.path.join(systemFolder, server, service + '.MapServer')
sddraft = os.path.join(wrkspc, service + '.sddraft')
sd = os.path.join(wrkspc, 'output', service + '.sd')

# create sddraft
if os.path.exists(sddraft): os.remove(sddraft)
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER')

# read sddraft xml
doc = DOM.parse(sddraft)

# turn on caching in the configuration properties
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":
                # turn on caching
                keyValue.nextSibling.firstChild.data = "true"
                
# output to a new sddraft
outXml = os.path.join(wrkspc, 'output', service + '.sddraft')   
if os.path.exists(outXml): os.remove(outXml)
f = open(outXml, 'w')     
doc.writexml( f )     
f.close() 

# analyze new sddraft for errors
analysis = arcpy.mapping.AnalyzeForSD(outXml)

# print dictionary of messages, warnings and errors
for key in ('messages', 'warnings', 'errors'):
    print "----" + key.upper() + "---"
    vars = analysis[key]
    for ((message, code), layerlist) in vars.iteritems():
        print "    ", message, " (CODE %i)" % code
        print "       applies to:",
        for layer in layerlist:
            print layer.name,
        print

# stage and upload the service if the sddraft analysis did not contain errors
if analysis['errors'] == {}:
    # Execute StageService
    if os.path.exists(sd): os.remove(sd)
    arcpy.StageService_server(outXml, sd)
    # Execute UploadServiceDefinition
    print "Uploading Service Definition..."
    arcpy.UploadServiceDefinition_server(sd, connection)
    # Print messaging from UploadServiceDefinition
    x = 0
    while x < arcpy.GetMessageCount():
        arcpy.AddReturnMessage(x)
        x = x + 1
else: 
    print "{} contained errors. StageService and UploadServiceDefinition aborted.".format(sddraft)
    exit()
    
print "Updating cache scales..."
scaleValues = "100000000;10000000;5000000;1000000;500000;250000;125000;64000;5250"
arcpy.ManageMapServerCacheScales_server(mapServer, scaleValues)

print "Creating tiles..."
arcpy.ManageMapServerCacheTiles_server(mapServer, "100000000", "RECREATE_ALL_TILES", "3")

print "Uploaded service and created tiles."
修改 SDDraft 示例 7

以下示例脚本显示如何更新托管在 ArcGIS Online 上的现有要素服务。例如,为了与组织中 ArcGIS for Desktop 用户所进行的每日更改保持同步,组织可能希望传送更新。本示例脚本将演示如何进行以下操作:

  • 将地图文档转换为 .sddraft 文件。
  • 通过相应的设置来修改内部 XML。
  • 分析 .sddraft 文件是否存在错误。
  • .sddraft 文件过渡为 .sd(服务定义)文件。
  • 服务上传到 ArcGIS Online。请注意,此代码与 ArcGIS Online 上的所有人共享要素服务。

使用 MXD 文件的路径更新变量。脚本将在其保存位置上创建临时草稿。ArcGIS Online 登录信息可从 ArcGIS for Desktop 主菜单上的文件 > 登录对话框中获取。

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

arcpy.env.overwriteOutput = True

# Update these variables
# The tempPath variable is a relative path which is the same directory
# this script is saved to. You can modify this value to a path on your
# system to hold the temporary files.
serviceName = "importantPoints"
tempPath = sys.path[0]
path2MXD = r"C:\path2MXD\pts.mxd"

# All paths are built by joining names to the tempPath
SDdraft = os.path.join(tempPath, "tempdraft.sddraft")
newSDdraft = os.path.join(tempPath, "updatedDraft.sddraft")
SD = os.path.join(tempPath, serviceName + ".sd")

mxd = arcpy.mapping.MapDocument(path2MXD)
arcpy.mapping.CreateMapSDDraft(mxd, SDdraft, serviceName, "MY_HOSTED_SERVICES")

# Read the contents of the original SDDraft into an xml parser
doc = DOM.parse(SDdraft)

# The follow 5 code pieces modify the SDDraft from a new MapService
# with caching capabilities to a FeatureService with Query,Create,
# Update,Delete,Uploads,Editing capabilities. The first two code
# pieces handle overwriting an existing service. The last three pieces
# change Map to Feature Service, disable caching and set appropriate
# capabilities. You can customize the capabilities by removing items.
# Note you cannot disable Query from a Feature Service.
tagsType = doc.getElementsByTagName('Type')
for tagType in tagsType:
    if tagType.parentNode.tagName == 'SVCManifest':
        if tagType.hasChildNodes():
            tagType.firstChild.data = "esriServiceDefinitionType_Replacement"

tagsState = doc.getElementsByTagName('State')
for tagState in tagsState:
    if tagState.parentNode.tagName == 'SVCManifest':
        if tagState.hasChildNodes():
            tagState.firstChild.data = "esriSDState_Published"

# Change service type from map service to feature service
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
    if typeName.firstChild.data == "MapServer":
        typeName.firstChild.data = "FeatureServer"

# 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"

# Turn on feature access capabilities
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":
                keyValue.nextSibling.firstChild.data = "Query,Create,Update,Delete,Uploads,Editing"

# Write the new draft to disk
f = open(newSDdraft, 'w')
doc.writexml( f )
f.close()

# Analyze the service
analysis = arcpy.mapping.AnalyzeForSD(newSDdraft)

if analysis['errors'] == {}:
    # Stage the service
    arcpy.StageService_server(newSDdraft, SD)

    # Upload the service. The OVERRIDE_DEFINITION parameter allows you to override the
    # sharing properties set in the service definition with new values. In this case,
    # the feature service will be shared to everyone on ArcGIS.com by specifying the
    # SHARE_ONLINE and PUBLIC parameters. Optionally you can share to specific groups
    # using the last parameter, in_groups.
    arcpy.UploadServiceDefinition_server(SD, "My Hosted Services", serviceName,
                                         "", "", "", "", "OVERRIDE_DEFINITION", "SHARE_ONLINE",
                                         "PUBLIC", "SHARE_ORGANIZATION", "")

    print "Uploaded and overwrote service"

else:
    # If the sddraft analysis contained errors, display them and quit.
    print analysis['errors']
5/10/2014