03-利用python arcpy批量自动发布服务以及自动做服务切片

本文介绍了如何使用Python的ArcPy模块批量自动化发布地理信息系统(GIS)服务,并进行服务切片操作。通过这段代码,可以极大地提高GIS服务管理和维护的效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

所有代码如下:

# -*- coding: cp936 -*-
# Publishes a service to machine myserver using USA.mxd
# A connection to ArcGIS Server must be established in the
#  Catalog window of ArcMap before running this script
import arcpy
import os


def publishOneMxd(con, wrkspc, mxdname, servicename, serverFolder, inputS,serviceCacheDirectory, summary, tags):
    # Define local variables
    wrkspc = wrkspc
    mapDoc = arcpy.mapping.MapDocument(wrkspc + '/' + mxdname)

    # Provide path to connection file
    # To create this file, right-click a folder in the Catalog window and
    #  click New > ArcGIS Server Connection
    # con = wrkspc + '/servercon.ags'

    # Provide other service details
    service = servicename

    sddraft = wrkspc + "/" + service + '.sddraft'
    sd = wrkspc + "/" + service + '.sd'
    summary = summary
    tags = tags

    # Create service definition draft
    arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', con, True, serverFolder, summary, tags)

    # 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()

    # # inputService = 'C:/Users/Administrator/AppData/Roaming/ESRI/Desktop10.5/ArcCatalog//arcgis on localhost_6080 (admin)' + '/' + foldername + '//' + servicename + '.MapServer'
    inputService = inputS
    # serviceCacheDirectory = arcpy.GetParameterAsText(2)
    # serviceCacheDirectory = 'D:/arcgisserver/directories/arcgiscache'  # 指定缓存切片地址
    tilingSchemeType = "NEW"
    scalesType = "CUSTOM"
    numOfScales = "22"
    dotsPerInch = "96"
    tileSize = "256 x 256"
    predefinedTilingScheme = ""
    tileOrigin = "-20037508.342787001 20037508.342787001"
    # scales = "3000;1500;750;375;150"
    scales = "591657527.591555;295828763.79577702;147914381.89788899;73957190.948944002;36978595.474472001;18489297.737236001;9244648.8686180003;4622324.4343090001;2311162.2171550002;1155581.108577;577790.55428899999;288895.27714399999;144447.638572;72223.819286;36111.909643;18055.954822;9027.977411;4513.988705;2256.994353;1128.497176;564.248588;282.124294;141.062147"
    cacheTileFormat = "PNG"
    tileCompressionQuality = "75"
    storageFormat = "EXPLODED"
    print "start create cache ....."
    arcpy.CreateMapServerCache_server(inputService, serviceCacheDirectory,
                                      tilingSchemeType, scalesType, numOfScales,
                                      dotsPerInch, tileSize, predefinedTilingScheme,
                                      tileOrigin, scales, cacheTileFormat,
                                      tileCompressionQuality, storageFormat)
    print "end create cache ....."
    print "start create tiles ....."
    arcpy.ManageMapServerCacheTiles_server(inputService, scales, 'RECREATE_EMPTY_TILES')
    # arcpy.ConvertMapServerCacheStorageFormat_server(inputService)
    print "end create tiles ....."
    """
    删除临时文件
    """

    delete1 = servicename + '.sd'
    arcpy.Delete_management(delete1)

def create_con(username,password,out_folder_path):

    out_name = 'servercon.ags'
    server_url = 'http://localhost:6080/arcgis/admin'
    use_arcgis_desktop_staging_folder = False
    staging_folder_path = out_folder_path
    # crate arcgis server connection file ags extension
    arcpy.mapping.CreateGISServerConnectionFile("ADMINISTER_GIS_SERVICES",
                                                            out_folder_path,
                                                            out_name,
                                                            server_url,
                                                            "ARCGIS_SERVER",
                                                            use_arcgis_desktop_staging_folder,
                                                            staging_folder_path,
                                                            username,
                                                            password,
                                                            "SAVE_USERNAME")
    return out_folder_path + "/"+out_name

def publis_many_mxd(wrksp,username,password,serverFolder,serviceCacheDirectory):
    con = create_con(username, password, wrksp)
    arcpy.env.workspace = wrksp
    mxds = arcpy.ListFiles()
    for mxd in mxds:
        if mxd.endswith(".mxd"):
            servername = mxd.split(".")[0]
            inputS = con.split('.')[0] + '/' + serverFolder + '//' + servername + '.MapServer'
            publishOneMxd(con, wrksp, mxd, servername, serverFolder, inputS, serviceCacheDirectory, "summery", "tages")

if __name__ == "__main__":
    wrksp = "I:/test/mxd"
    username = "siteadmin"
    password = "123456"
    serverFolder = "tw"
    serviceCacheDirectory = 'D:/arcgisserver/directories/arcgiscache'

    # wrksp = raw_input("mxd_folder:")
    # username = raw_input("arcgis server username:")
    # password = raw_input("arcgis server password::")
    # serverFolder = raw_input("arcgis server folder:")
    # serviceCacheDirectory = raw_input("arcgis server cache folder:")

    publis_many_mxd(wrksp,username,password,serverFolder,serviceCacheDirectory)
    print'Publishing and Caching succeeded'
# raw_input()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

limeng19

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值