python发布要素服务

官方示例中:http://desktop.arcgis.com/zh-cn/arcmap/10.3/analyze/arcpy-mapping/createmapsddraft.htm 
有通过python发布普通的地图服务的方法,非常的简单。
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']

    在此基础上,帮助文档中还提到了通过python发布要素服务,不过这是用于向ArcGIS Online上发布托管要素服务的方法。不能用于向server上发布传统的要素服务。通过与@kikita交流。我尝试写出了发布要素服务的python代码。依然是用arcpy, 与帮助文档中的示例类似, 没有使用arcgis for python api 。
import arcpy, os, sys 
from datetime import datetime
import xml.dom.minidom as DOM

arcpy.env.overwriteOutput = True

# Define global variables from User Input
wrkspc = 'D:\pytest'
mapDoc = arcpy.mapping.MapDocument(wrkspc + '\\' + 'fire.mxd')
con = 'GIS Servers/dans6443(admin).ags'
serviceName = 'KYEM'
#shareLevel = 'PRIVATE' # Options: PUBLIC or PRIVATE
#shareOrg = 'NO_SHARE_ORGANIZATION' # Options: SHARE_ORGANIZATION and NO_SHARE_ORGANIZATION
#shareGroups = '' # Options: Valid groups that user is member of


tempPath = sys.path[0]

#SignInToPortal function does not work in 10.2
#for 10.1: uncomment below line to enable sign in
#for 10.2: (1): Sign in to arcgis desktop and check 'sign in automatically'
# (2): Schedule task to run publishFS.py script, using same user as in step 1
##arcpy.SignInToPortal_server('','','http://www.arcgis.com/')

sdDraft = wrkspc+'\\' + serviceName + '.sddraft'
newSDdraft = 'updatedDraft.sddraft'
SD = wrkspc + '\\' + serviceName + '.sd'
summary = 'fire point by County'
tags = 'county, counties, population, density, census'
print "SD=="+SD +",,sdDraft=="+sdDraft

try:
print'create service definition draft'
# create service definition draft
analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sdDraft, serviceName, 'ARCGIS_SERVER', con, False, None, summary, tags)
print'create draft success'

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

# Change service type from map service to feature service
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
if typeName.firstChild.data == 'FeatureServer':
typeName.parentNode.getElementsByTagName('Enabled')[0].firstChild.data = 'true'


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

# Analyze the service
analysis = arcpy.mapping.AnalyzeForSD(newSDdraft)
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

if analysis['errors'] == {}:
print 'analysis true'
# 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.
arcpy.UploadServiceDefinition_server(SD, con)

print 'Service successfully published'

# Write messages to a Text File
txtFile = open(wrkspc+'/{}-log.txt'.format(serviceName),"a")
txtFile.write (str(datetime.now()) + " | " + "Uploaded and publish service" + "\n")
txtFile.close()

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

# Write messages to a Text File
txtFile = open(wrkspc+'/{}-log.txt'.format(serviceName),"a")
txtFile.write (str(datetime.now()) + " | " + analysis['errors'] + "\n")
txtFile.close()

except:

print arcpy.GetMessages()
# Write messages to a Text File
txtFile = open(wrkspc+'/{}-log.txt'.format(serviceName),"a")
txtFile.write (str(datetime.now()) + " | Last Chance Message:" + arcpy.GetMessages() + "\n")
txtFile.close()
    主要添加的内容有,将服务定义草稿文件(.sddraft)利用xml.dom.minidom读取到python中,读取<TypeName>里值为FeatureServer的节点,将FeatureServer的功能开启即可。
    通过记事本打开服务定义草稿文件SDdraft可以看到里面除了默认选择的MapServer外 含有另外七个类型的功能<TypeName>,而<Enabled>标签也是七个,来控制这七个功能的开启。在这里我们只需要开启FeatureServer的功能就可以发布要素服务了。
    此外,Analyze the service部分,添加了分析结果格式化输出代码,非常的好看。此工具还具有输出日志,可以查看日志记录。
    感谢@kikita对此事的研究与推进。

1 个评论

代码发出来,比较长的地方排版乱了。。请copy的时候注意python的缩进问题

要回复文章请先登录注册