Select to view content in your preferred language

Arcpy: Automate Creation and Publishing of Map Service

2802
3
08-19-2016 07:38 AM
JacobSnyder2
Deactivated User

Hello,

I have written a script that should take a 'Table View' from an SDE Geodatabase, and export it to Shapefile format for use as source data for a layer in a specific MXD file. The script should then take this MXD file and upload it to ArcGIS Server as a map service. This map service must overwrite an existing service (this is a weekly process). I was wondering if anyone could take a look at my code, before I actually run it, to see if there is anything in there that could be a potential issue. I really appreciate any help whatsoever. Code is posted below. Thanks so much.

-Jacob

---------------------------------------------------------------------------------------------------------------------------------------------------------------

import arcpy
import xml.dom.minidom as DOM
import os
import sys
import traceback

arcpy.AddMessage("Setting the workspace to your Vector.sde connection...")

arcpy.env.workspace = arcpy.GetParameterAsText(0) # User must enter connection to 'Vector' SDE geodatabase ##"C:\Users\jsnyder\AppData\Roaming\ESRI\Desktop10.3\ArcCatalog\Vector.sde"

try:
    # Specify the folder in which the shapefiles that are necessary will be created, set other variables
    wrkspc = arcpy.GetParameterAsText(1) # Navigate to the workspace that contains or should contain parcels shapefile ##r"F:\ETL\04_Exports\Output\CRW"
    parcel_shp = str(wrkspc) + "\parcels.shp" ##"F:\ETL\04_Exports\Output\CRW\parcels.shp"
    parcel_view = "vector.dbo.PARCEL_VIEW"
    tags = 'Spotsylvania, Virginia, VA, CRW'
    summary = "Map Service is to be used within Spotsylvania County's CRW application"
    service = 'CRW'
    server = r"GIS Servers\arcgis on gis.spotsylvania.va.us (publisher)"
    mapDoc = arcpy.GetParameterAsText(2) # Navigate to the location of the CRW MXD file that will be used to publish the map service ##arcpy.mapping.MapDocument(r"F:\MXDs\CRW_MapService\CRW_MapService.mxd")
    sddraft = str(wrkspc) + "\CRW_MapService.sddraft" ##r"X:\ETL\04_Exports\Output\CRW\CRW_MapService.sddraft"
    sd = str(wrkspc) + "\CRW_MapService.sd" ##r"X:\ETL\04_Exports\Output\CRW\CRW_MapService.sd"

    # If any shapefiles exist in the folder currently, delete them.
    if os.path.exists(parcel_shp):
        arcpy.AddMessage("Renaming the old 'parcels' shapefile to 'parcels_old'")
        arcpy.Rename_management(parcel_shp, str(wrkspc) + "\parcels_old")
        arcpy.AddMessage("Creating new 'parcels' shapefile...")
        arcpy.FeatureClassToFeatureClass_conversion(parcel_view, wrkspc, "parcels")
    else:
        arcpy.FeatureClassToFeatureClass_conversion(parcel_view, wrkspc, "parcels")

    arcpy.AddMessage("Dropping 'OID' field from new shapefile...")

    # Delete 'ESRI_OID' field from new shapefile
    dropField = ["ESRI_OID"]
    arcpy.DeleteField_management(parcel_shp, dropField)

    arcpy.AddMessage("Setting parameters for the CRW Map Service. During this process, the script will specify the the service definition type as a replacement...")

    # Create the service definition draft for the CRW Map Service
    analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, 'CRW', 'ARCGIS_SERVER', server, True, None, summary, tags)

    # Set service type to be 'esriServiceDefinitionType_Replacement' to serve as a replacement for the existing service
    newType = 'esriServiceDefinitionType_Replacement'
    xml = sddraft
    doc = DOM.parse(xml)
    descriptions = doc.getElementsByTagName('Type')
    for desc in descriptions:
        if desc.parentNode.tagName == 'SVCManifest':
            if desc.hasChildNodes():
                desc.firstChild.data = newType
    outXml = xml
    f = open(outXml, 'w')
    doc.writexml( f )
    f.close()

    # After analyzing the service definition draft, if there are no errors, stage and upload the service
    if analysis['errors'] == {}:
        arcpy.AddMessage("There were noe errors...the service should now publish.")
        # Execute Stage Service
        arcpy.StageService_server(sddraft, sd)
        # Upload the service
        arcpy.UploadServiceDefinition_server(sd, server)
    else:
        arcpy.AddError("There seem to have been some errors with some of the parameters that have been specified. Please see the messages below.")
        arcpy.AddError(str(analysis['errors']))

    arcpy.AddWarning("The tool ran successfully. Please make sure that the CRW Map Service has successfully been uploaded.")

except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS: \nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_type) + ":" +str(sys.exc_value) + "\n"
    arcpy.AddError(pymsg)
    msgs = "ArcPy ERRORS: \n" +arcpy.GetMessages(2) + "\n"
    arcpy.AddError(msgs)
    print pymsg + "\n"
    print msgs
0 Kudos
3 Replies
DanPatterson_Retired
MVP Emeritus

could your format your code using the syntax highlighting capabilities here.  There appears to be some indentation issues in a few places and I don't know if they are artifacts of font/copying issues or potential sources of code issues.  See /blogs/dan_patterson/2016/08/14/script-formatting 

JacobSnyder2
Deactivated User

Dan,

I apologize for the earlier post. I had actually been wondering how to format the code properly for this thread...so thank you. The code seems to be in the proper format now. Thanks so much for your time.

-Jacob

0 Kudos
JacobSnyder2
Deactivated User

To provide a more specific question about the code, in the 'CreateSDDraft' tool parameters, can the connection file path parameter be specified with the following variable if this connection to the server has already been established in the 'GIS Servers' node in ArcCatalog prior to running the script tool?:

server = r"GIS Servers\arcgis on gis.spotsylvania.va.us (publisher)"

Thanks again,

Jacob

0 Kudos