通過Arcpy發布地圖服務


1.發布地圖服務的流程

使用 ArcPy 將地圖文檔自動發布到 GIS 服務器的流程分為四步:

  • 第一步,運行 CreateMapSDDraft 函數。CreateMapSDDraft 的輸出是服務定義草稿 (.sddraft) 文件,服務定義草稿由地圖文檔、服務器信息和一組服務屬性組合而成。
  • 第二步,使用 AnalyzeForSD 函數分析輸出的服務定義草稿文件的適用性和潛在性能問題。
  • 第三步,使用 Stage Service 地理處理工具將服務定義草稿轉換為完全合並的服務定義 (.sd) 文件。過渡過程會編譯成功發布 GIS 資源所需的所有必要信息。如果選擇將數據復制到服務器,則將在服務定義草稿階段添加數據。
  • 最后,使用 上載服務定義地理處理工具上載服務定義文件並將其作為 GIS 服務發布到特定的 GIS 服務器。此步驟將獲取服務定義文件、將其復制到服務器、提取所需信息並發布 GIS 資源。

2.調用函數參數詳解

第一步:創建草圖文件

CreateMapSDDraft (map_document, out_sddraft, service_name, {server_type}, {connection_file_path}, {copy_data_to_server}, {folder_name}, {summary}, {tags})

參數 說明 類型
map_document Map Document 類型的對象,即一個mxd文檔。 Map Document
out_sddraft Service Definition Draft (.sddraft) 文件輸出路徑。 String
service_name 服務的名字,由字母和數字組成,不允許使用空格或特殊字符,長度不得超過120。 String
server_type 服務的類型,如果未提供「connection_file_path」參數,則必須提供「server_type」。如果提供了「connection_file_path」參數,則從連接文件中獲取「 server_type」。
• ARCGIS_SERVER — ArcGIS for Server 服務類型,默認值。
• FROM_CONNECTION_FILE — 從 connection_file_path 參數獲取服務類型。
• SPATIAL_DATA_SERVER — Spatial Data Server 服務類型,ArcGIS 10.2.1 版本之后就不再支持。
• MY_HOSTED_SERVICES — My Hosted Services 服務類型,應用與 ArcGIS Online 或者 Portal for ArcGIS 的托管服務。
String
connection_file_path ArcGIS for Server connection file (.ags) 文件的路徑。通常在ArcCatalog創建后的路徑為「C:\Users\Administrator\AppData\Roaming\ESRI\Desktop10.2\ArcCatalog」 String
copy_data_to_server mxd文檔的數據是否要拷貝到服務器中。當數據沒有在服務器內被注冊時,此參數應設為false,反之應設為true。
當「server_type」設置為SPATIAL_DATA_SERVER時,「copy_data_to_server」將始終為False。 Spatial Data Server 服務始終使用已注冊的數據,因此不會將數據復制到服務器。
當「server_type」設置為MY_HOSTED_SERVICES時,「copy_data_to_server」將始終為True。My Hosted Maps services 服務始終將數據復制到服務器。
Boolean
folder_name 服務發布的文件夾名,如果不存在則會新建,默認值None對應的是根文件夾。 String
summary 服務的摘要。 String
tags 服務的標簽。 String

第二、三、四步

可以直接在arcgis幫助文檔內查看,有中文的。

3.實現代碼

下面是一個發布服務的例子,實現的功能是遍歷一個文件夾,將文件夾內.mxd結尾的文件都發布上服務器。

# -*- coding: utf-8 -*-
import arcpy
import os
import xml.dom.minidom as DOM

def SetSddraftParam(sddraft_file_path):
    '''修改Sddraft文件的參數。(一般就修改開啟WMS、WFS功能)

    Args:
        sddraft_file_path: .sddraft文件的路徑。
    '''
    doc = DOM.parse(sddraft_file_path)
    ext = doc.getElementsByTagName('Extensions')[0]
    svcExts = ext.childNodes
    for svcExt in svcExts:
        typename_ele = svcExt.getElementsByTagName('TypeName')[0]
        if typename_ele.firstChild.data == 'WMSServer':
            enable_ele = svcExt.getElementsByTagName('Enabled')[0]
            enable_ele.firstChild.data = 'true'
            break
    if os.path.exists(sddraft_file_path):
        os.remove(sddraft_file_path)
    f = open(sddraft_file_path, 'w')
    doc.writexml(f)
    f.close()

def GetAGSConnectionFile(out_folder_path):
    '''在指定文件夾新建test.ags文件。

    Args:
        out_folder_path: .ags文件的輸出文件夾路徑。

    Returns:
        返回.ags文件的路徑。
    '''
    out_name = 'test.ags'
    server_url = 'http://localhost:6080/arcgis/admin'
    use_arcgis_desktop_staging_folder = False
    staging_folder_path = out_folder_path
    username = 'siteadmin'
    password = '123456'
    out_file_path = os.path.join(out_folder_path, out_name)
    if os.path.exists(out_file_path):
        os.remove(out_file_path)
    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,
                                                True)
    return out_file_path

def PublishMxd(mxd_file_path, mxd_folder_path, con_file_path):
    '''發布服務。

    Args:
        mxd_file_path:mxd文檔的路徑。
        mxd_folder_path:mxd文檔所在文件夾的路徑。
        con_file_path:服務器連接文件路徑
    '''
     #檢查mxd文件是否存在
    print "Checking mxd file path..."
    if os.path.exists(mxd_file_path) == False:
        print "mxd file is not exist!"
        return
    
    # 打開mxd文檔
    try:
        print "Opening mxd file..."
        mxd = arcpy.mapping.MapDocument(mxd_file_path)
    except Exception, e:
        print "open mxd error: ", e
        return

    # 獲取默認的數據框
    print "Loading mxd file default dataframes..."
    df = ""
    try:
        frames = arcpy.mapping.ListDataFrames(mxd, "圖層")
        if len(frames) == 0:
           frames = arcpy.mapping.ListDataFrames(mxd, "Layers") 
        df = frames[0]
    except Exception, e:
        print "load mxd file default dataframes failed:", e
        return
    # 組織參數發布服務
    mxdNameWithExt = os.path.basename(mxd_file_path)
    (serviceName, extension) = os.path.splitext(mxdNameWithExt)
    sddraft_file_path = os.path.join(mxd_folder_path, serviceName + '.sddraft')
    summary = 'Test'
    tags = 'Test'
    # 創建草圖文件
    print "CreateMapSDDraft..."
    if os.path.exists(sddraft_file_path):
        os.remove(sddraft_file_path)
    arcpy.mapping.CreateMapSDDraft(mxd, sddraft_file_path, serviceName, 'ARCGIS_SERVER', con_file_path, False, None, summary, tags)
    # 設置草圖文件內的參數(開啟WMS功能,WFS功能等)
    SetSddraftParam(sddraft_file_path)
    # 分析草圖文件
    analysis = arcpy.mapping.AnalyzeForSD(sddraft_file_path)
    if analysis['errors'] == {}:
        for message in analysis['messages']:
            print analysis['messages'][message]
            print message[0].encode("gb2312") + "(%s)" % message[1]
        for warning in analysis['warnings']:
            print analysis['warnings'][warning]
            print warning[0].encode("gb2312") + "(%s)" % warning[1]
        # 過渡服務
        print "StageService..."
        sdPath = os.path.join(mxd_folder_path1, serviceName + '.sd')
        arcpy.StageService_server(sddraft_file_path, sdPath)
        # 上傳服務定義
        print "UploadServiceDefinition_server..."
        arcpy.UploadServiceDefinition_server(sdPath, con_file_path)
    else:
        for error in analysis['errors']:
            print analysis['errors'][error]
            print error[0].encode("gb2312") + "(%s)" % error[1]

def PublishAll(mxd_folder_path):
    '''遍歷指定文件夾內的所有mxd文檔,並逐個發布服務。

    Args:
        mxd_folder_path:包含mxd文檔的文件夾路徑。
    '''
    print "Check folder path..."
    if os.path.isdir(mxd_folder_path) == False:
        print "folder path is not exist!"
        return
    print "Get .ags file..."
    con_file_path = GetAGSConnectionFile(mxd_folder_path)
    print "******************Traversing a folder******************"
    files = os.listdir(mxd_folder_path)
    mxdCount = 0
    for f in files:
        if f.endswith(".mxd"):
            mxdCount = mxdCount + 1
    mxdNo = 1
    for f in files:
        if f.endswith(".mxd"):
            mxd_file_path = os.path.join(mxd_folder_path, f)
            print "Publishing: " + f + "(%d/%d)" % (mxdNo, mxdCount)
            mxdNo = mxdNo + 1
            PublishMxd(mxd_file_path, mxd_folder_path, con_file_path)
        else:
            continue

mxd_folder_path = r'E:\MyCode\Mypy\py2\mxd'
publishServices.PublishAll(mxd_folder_path)

4.備注

針對上面的內容還有以下幾點需要說明:
1.如果對編碼不熟悉的話,建議過程中不要使用中文名。
2.通過arcmap界面發布服務時設置的參數可以在sddraft草圖文件內找到,並通過修改文件配置來設置CreateMapSDDraft函數沒囊括的參數。另外對沒有函數可以修改已發布的服務參數問題,設想可以通過重復發布服務覆蓋來實現需求,但是暫時還沒有嘗試。
3.切片緩存功能還沒添加。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM