ArcGIS中python实现地图服务的自动发布

项目的具体需求是,每天下载几张tiff图片,放在mxd文件里,然后将其发布到ArcGISServer,后来 参照网上有一篇文章,可以自动发布地图服务,但是,后来发现,现在使用的ArcGIS版本10.2.2已经放弃了原来的方式发布服务,根据ArcMap里的帮助文档,发现里面的例子还是挺多的,自己又修改了实现的代码,遇到的问题是,

 con = 'C:/Users/IBM_ADMIN/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (publisher).ags'
这个参数是ags文件的地址,默认这个文件是存在c盘的隐藏文件夹里,这个文件,是ArcCatolog里创建ArcGISServer连接的时候创建的。

实现方式是创建一个模板的mxd文件,每次,修改其数据源,这样图层的渲染方式不会改变,曾经想着将模板文件里的图层删掉,再添加新的图层,但,发现默认添加的tiff图层的渲染方式竟然不是ArcMap里自动添加tiff图层的渲染方式(rgb),添加出来的图层是灰色图,python的symbol控制又比较弱,所以,改成修改数据源的方式,实现了最终的效果

下载tiff文件的代码downLoadTiff.py:

import urllib 
import urllib2
import os,time
ftime=time.strftime("%Y_%m_%d", time.localtime())#2015_12_01 tiffFonderName
ftime1=time.strftime("%Y-%m-%d", time.localtime())#2015-12-01 tiffNametime
ftime='2015_12_07'
ftime1='2015-12-07'
tiffFolder='..\\..\\'+ftime
tiffNameStart='nasa-worldview-'
os.mkdir(tiffFolder)
url = 'http://9.186.62.26/weather/satellite/'#nasa-worldview-2015-11-30.tiff'  
print "downloading start from http://9.186.62.26/weather/satellite/"
tiffName=tiffNameStart+ftime1+'-2.tiff'
urllib.urlretrieve(url+tiffName, tiffFolder+'\\'+tiffName)
print "downloading with urllib from "+url+tiffName
tiffName=tiffNameStart+ftime1+'-3.tiff'
urllib.urlretrieve(url+tiffName, tiffFolder+'\\'+tiffName)
print "downloading with urllib from "+url+tiffName
tiffName=tiffNameStart+ftime1+'-4.tiff'
urllib.urlretrieve(url+tiffName, tiffFolder+'\\'+tiffName)
print "downloading with urllib from "+url+tiffName
tiffName=tiffNameStart+ftime1+'.tiff'
urllib.urlretrieve(url+tiffName, tiffFolder+'\\'+tiffName)
print "downloading with urllib from "+url+tiffName

构造mxd文件,并发布服务的代码publishHelper.py:

# -*- coding: utf-8 -*-
import arcpy, os,time

__name__ = 'publishHelper'

# 将指定目录下所有的.mxd文档发布为地图服务
# folder:包含mxd文档的文件夹路径
# serviceDir:服务目录URL,例如http://localhost/arcgis/rest/services
# serviceFolder:服务所在文件夹,如果为空,则表示根目录
def PublishAll(folder,serviceDir,serviceFolder):
    print "检查文件夹路径……"
    if os.path.isdir(folder) == False:
        print "输入的文件夹路径无效!"
        return
    print "遍历文件夹……"
    files = os.listdir(folder)
    for f in files:
        if f.endswith(".mxd"):
            mxdPath = os.path.join(folder, f)
            print "publishing: " + f
            PublishMxd(f,mxdPath, serviceDir, serviceFolder)
        else:
            continue
#将mxd文档发布为服务:1.将mxd转为msd;2.分析msd;3.发布msd
def PublishMxd(mxdName,mxdPath, serviceDir, serviceFolder):
    #检查mxd文件是否存在
    print "检查文件路径……"
    if os.path.exists(mxdPath) == False:
        print "指定路径的mxd文档不存在!"
        return
    
    # 打开mxd文档
    try:
        print "正在打开mxd文档……"
        mxd = arcpy.mapping.MapDocument(mxdPath)
    except Exception, e:
        print "open mxd error: ", e
        return
    else:
        print "mxd文档打开成功……"

    # 获取默认的数据框
 

    # 构造sddraft文档名称   
    sddraft = mxdPath.replace(".mxd", ".sddraft")
    service=mxdName.replace(".mxd", "")
    sd=mxdPath.replace(".mxd", ".sd")
    con = 'C:/Users/IBM_ADMIN/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (publisher).ags'
    copy_data_to_server=True
    #正在将mxd文档转换为sddraft文档……"
    # Create service definition draft
    arcpy.mapping.CreateMapSDDraft(mxd, sddraft, service,'ARCGIS_SERVER',con,copy_data_to_server, serviceFolder)
    # Analyze the service definition draft
    analysis = arcpy.mapping.AnalyzeForSD(sddraft)
    
    # Print errors, warnings, and messages returned from the analysis
    print "The following information was returned during analysis of the MXD:"
    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. This creates the service definition.
        arcpy.StageService_server(sddraft, sd)
    #Execute UploadServiceDefinition. This uploads the service definition and publishes the service.
        arcpy.UploadServiceDefinition_server(sd, con)
        print "Service successfully published"
    else: 
        print "Service could not be published because errors were found during analysis."

    print arcpy.GetMessages()

# demoMXDPath:包含mxd文档名称
# folder:包含新建的mxd文档以及tiff文件的文件夹路径
def createMxdDocument(demoMXDPath,folder):
     if os.path.exists(demoMXDPath) == False:
        print "mxd document it's not exist!"
     else:
        try:
            print "opening mxd document……"
            mxd = arcpy.mapping.MapDocument(demoMXDPath)
            print "repair layer source"
            if os.path.isdir(folder) == False:
                print "invalid document path!"
                return
            print "reading layer document one by one......"
            files = os.listdir(folder)
            i=0
            layerName=""
            for f in files:
                if f.endswith(".tiff"):
                    if layerName="":
                        name1=f.replace("nasa-worldview-", "")
                        layerName=name1[0:9]
                    if i>3:
                        continue
                    if f.index(layerName)>=0:
                        print layerName+";"+f
                        df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
                        print arcpy.mapping.ListLayers(mxd, "", df)[i].name
                        lyr = arcpy.mapping.ListLayers(mxd, "", df)[i]
                        lyr.replaceDataSource(folder,"RASTER_WORKSPACE",f)
                        lyr.name=f.replace(".tiff", "")
                        i=i+1
                else:
                    continue
            mxdName=time.strftime("%Y_%m_%d", time.localtime())+".mxd" #2015_11_24样式文件名
            newMXD=folder+"\\"+mxdName
            mxd.saveACopy(newMXD)
            del mxd
        except Exception, e:
            print "open mxd error: ", e
            return

执行过程的代码 doPublishHelper.py :

import sys,time
sys.path.append(r"D:\ly\hb\script\v2") # python文件路径
from publishHelper import PublishAll # 必须要有正确的许可,否则导入失败
from publishHelper import createMxdDocument # 必须要有正确的许可,否则导入失败
tiffFolder=time.strftime("%Y_%m_%d", time.localtime())
tiffFolder="nasadata"
folderPath=r"D:\ly"+"\\"+tiffFolder
createMxdDocument(r"D:\ly\hb\20151124demo.mxd",folderPath)
PublishAll(folderPath, "http://localhost/ArcGIS/rest/services", "ly")


你可能感兴趣的:(GIS综合)