写在前面的话:
对于初学者来说,本文够用,只讲了最基本的实现逻辑与代码,实现了最简单的功能,对于实际工作中,本文中提到的代码并不足够严谨,没有考虑到如果已经存在同名sd文件时如何处理,修改实例数等情况,缺少基本的判断。本文的主要目的在于梳理逻辑。
接下来这篇讲如何利用ArcPy发布服务
一、用Python脚本发切片服务(ArcMap版)
为了提高效率,节约时间,同样也为了节省计算机内存,从本篇开始,所有的数据源全部来自数据库,并且注册到server,这样在发布服务的时候就不会提醒:数据将被复制到服务器。除了注册数据库之外,还可以注册文件夹,通过注册的方式,都可以避免数据复制到server,以此达到节省计算机内存,提高效率的目的。注册数据方法点我,本篇的主要目的不在此,故不赘述。
接下来进入正题。
准备工作:一个做好的mxd文档,包括数据、坐标系信息、配图等信息(本文中用到的数据源为在server中注册数据库中的数据,所以在发布时没有考虑复制数据到服务器的情况)
思路(part1):mxd文档----服务定义文件草稿文件(.sddraft)—服务定义文件(.sd)—用DOM读取以xml的形式读取sddraft文件—开启or关闭该文件中的相关功能—重新生成sddraft文件----重新生成sd文件—分析sd文件----发布服务
# -*- coding: utf-8 -*-
#!/usr/bin/python
import arcpy
from arcpy import env
import xml.dom.minidom as DOM
import os
env.workspace="E:/05email/zzshare"
wrkspc="E:/05email/zzshare/"
#前面的博客中的代码生成了GIS Server的连接信息,此处直接使用,并未重新生成,详细代码见
#https://blog.csdn.net/weixin_44616652/article/details/89454557
out_name='ajServer.ags'
#将mxd文档变为服务定义草稿(.sddraft)文件,服务定义草稿文件会在服务定义文件(sd)后自动删除
mapDoc=arcpy.mapping.MapDocument(wrkspc+'Beijingshi.mxd')
service_name='BeijingTileArcMap'
sddraft=wrkspc+service_name+'.sddraft'
sd=wrkspc+service_name+'.sd'
summary='blog use sd'
tags='beijing,map,tile'
con=wrkspc+out_name
print("准备生成服务定义……")
analysis=arcpy.mapping.CreateMapSDDraft(mapDoc,sddraft,service_name,'ARCGIS_SERVER',
con,True,'blog',summary,tags)
#用DOM读取以xml的形式读取sddraft文件
doc=DOM.parse(sddraft)
print("准备修改服务定义草稿文件内容……")
#打开配置属性中的缓存
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'
print("缓存已开启……")
#关闭KmlServer
typeNames=doc.getElementsByTagName('TypeName')
for typeName in typeNames:
if typeName.firstChild.data=='KmlServer':
extension=typeName.parentNode
for extElement in extension.childNodes:
if extElement.tagName=='Enabled':
extElement.firstChild.data='false'
print("KmlServer已关闭……")
#重新生成服务定义草稿文件
outXml=wrkspc+service_name+'.sddraft'
if os.path.exists(outXml):
os.remove(outXml)
newFile = open(outXml,'w')
doc.writexml(newFile)
newFile.close()
analysis=arcpy.mapping.AnalyzeForSD(outXml)
print ("重新分析……")
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
del newFile, doc, mapDoc
#分析完成,没有错误,准备发服务
if analysis['errors']=={}:
arcpy.StageService_server(outXml, sd)
arcpy.UploadServiceDefinition_server(sd, con)
arcpy.SignOutFromPortal_server()
else:
print analysis['errors']
思路(part2):用创建地图服务器缓存工具—管理地图服务器缓存切片
创建地图服务器缓存
# -*- coding: utf-8 -*-
#!/usr/bin/python
import arcpy
from arcpy import env
import os, sys, time, datetime, traceback, string
wrkspc="E:/05email/zzshare"
server = "ajServer"
floder="blog"
serviceName = "BeijingTileArcMap.MapServer"
inputService = wrkspc + "/" + server + "/" + floder+"/" + serviceName
print inputService
serviceCacheDirectory = "E:/Enterprise/server/directories/arcgiscache"
tilingSchemeType = "NEW"
scalesType = "STANDARD"
numOfScales = "3"
scales = ""
dotsPerInch = "96"
tileOrigin = ""
scales = ""
tileSize = "512 x 512"
cacheTileFormat = "PNG"
tileCompressionQuality = ""
storageFormat = "COMPACT"
predefinedTilingScheme = ""
print ("参数初始化成功……")
currentTime = datetime.datetime.now()
arg1 = currentTime.strftime("%H-%M")
arg2 = currentTime.strftime("%Y-%m-%d %H:%M")
file = "E:/05email/zzshare/report_%s.txt" % arg1
print currentTime
report = open(file, 'w')
try:
starttime = time.clock()
result = arcpy.CreateMapServerCache_server(inputService,
serviceCacheDirectory,
tilingSchemeType, scalesType,
numOfScales, dotsPerInch,
tileSize, predefinedTilingScheme,
tileOrigin, scales,
cacheTileFormat,
tileCompressionQuality,
storageFormat)
finishtime = time.clock()
elapsedtime = finishtime - starttime
#打印消息至文件
while result.status < 4:
time.sleep(0.2)
resultValue = result.getMessages()
report.write("completed " + str(resultValue))
print "创建了3级缓存" + \
serviceName + " in " + str(elapsedtime) + " sec \n on " + arg2
except Exception, e:
# 如果发生错误,打印行号和错误消息
tb = sys.exc_info()[2]
report.write("Failed at step 1 \n" "Line %i" % tb.tb_lineno)
report.write(e.message)
print "缓存架构创建成功"
report.close()
管理地图服务器缓存切片
# -*- coding: utf-8 -*-
#!/usr/bin/python
import arcpy
from arcpy import env
import os, sys, time, datetime, traceback, string
wrkspc="E:/05email/zzshare"
server = "ajServer"
floder="blog"
serviceName = "BeijingTileArcMap.MapServer"
inputService = wrkspc + "/" + server + "/" + floder+"/" + serviceName
scales=""
update_mode="RECREATE_EMPTY_TILES"
num_of_caching_service_instances="-1"
area_of_interest=""
update_extent=""
wait_for_job_completion="WAIT"
currentTime = datetime.datetime.now()
arg1 = currentTime.strftime("%H-%M")
arg2 = currentTime.strftime("%Y-%m-%d %H:%M")
file = "E:/05email/zzshare/report_%s.txt" % arg1
print file
report = open(file, 'w')
try:
starttime = time.clock()
result=arcpy.ManageMapServerCacheTiles_server (inputService,
scales,
update_mode,
num_of_caching_service_instances,
area_of_interest,
update_extent,
wait_for_job_completion)
finishtime = time.clock()
elapsedtime = finishtime - starttime
print result.status
#打印消息至文件
while result.status < 4:
time.sleep(0.2)
resultValue = result.getMessages()
report.write("completed " + str(resultValue))
print "创建了3级缓存" + \
serviceName + " in " + str(elapsedtime) + " sec \n on " + arg2
except Exception, e:
# 如果发生错误,打印行号和错误消息
tb = sys.exc_info()[2]
report.write("Failed at step 1 \n" "Line %i" % tb.tb_lineno)
report.write(e.message)
print "缓存创建成功"
report.close()
图片中显示的为用脚本发布且成功切图的服务
二、用Python脚本发切片服务(ArcGIS Pro版)
PS:ArcGIS的产品更新的实在是太快了,初开这个系列的时候,用的还是10.6+2.3,现在已经更新为10.7.1+2.4了,因为ArcGIS Pro的帮助文档没有历史版本,因此本篇的代码是基于2.4写的,还请知晓。
代码附上
# -*- coding: utf-8 -*-
#!/usr/bin/python
import arcpy
import os
# Set output file names
outdir = r"E:\05email\zzshare\pro"
service = "proShareTile4326"
sddraft_filename = service + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
print (sddraft_output_filename)
# Reference map to publish
aprx = arcpy.mp.ArcGISProject(r"D:\cache\arcgis\proProject\MyProject.aprx")
m = aprx.listMaps("Map5")[0]
# Create TileSharingDraft and set service properties
sharing_draft = m.getWebLayerSharingDraft("HOSTING_SERVER", "TILE", service)
sharing_draft.summary = "SouthAmericaCountries 4326"
sharing_draft.tags = "SouthAmericaCountries 4326"
sharing_draft.description = "SouthAmericaCountries 4326"
sharing_draft.credits = "SouthAmericaCountries 4326"
sharing_draft.useLimitations = "SouthAmericaCountries 4326"
print("description.")
# Create Service Definition Draft file
sharing_draft.exportToSDDraft(sddraft_output_filename)
print("to sd.")
# Stage Service
try:
sd_filename = service + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)
print(sd_output_filename)
print(sddraft_output_filename)
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)
warnings = arcpy.GetMessages(1)
print(warnings)
except Exception as stage_exception:
print("Sddraft not staged. Analyzer errors encountered - {}".format(str(stage_exception)))
# Share to portal
print("Uploading Service Definition...")
arcpy.UploadServiceDefinition_server(sd_output_filename, "https://aj.enterprise.cn/serverwa/manager")
print("Successfully Uploaded service.")
通过此方式发布服务与server有以下不同:
1、发布的服务在Hosted文件夹中,即为托管切片服务,在server中界面如下:
并且在点进去详情后,多一列关于缓存的设置
默认是不开始切片的,需要手动开启,可在server中查看缓存状态
打开portal页面,找到该项目,开启切片任务,如果遇到构建切片按钮是不可用的状态,只需要将离线模式下面的勾打上后保存即可。
2、从portal中开启切片任务,无需修改sddraft文件,开启切片功能。
3、代码量更少
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/108165.html