Solved! Go to Solution.
import arcpy, os import xml.dom.minidom as DOM print "Establishing environment" workspace = r"C:\temp\enableNA" mxd = arcpy.mapping.MapDocument(os.path.join(workspace,"enablenatest.mxd")) svrconnection = os.path.join(workspace, "svrconnection.ags") outsddraft = os.path.join(workspace,"service.sddraft") draftfinal = os.path.join(workspace,"draftfinal.sddraft") outsd = os.path.join(workspace,"naservice.sd") print "Creating initial draft" arcpy.mapping.CreateMapSDDraft(mxd, outsddraft, "PythonNaTest","ARCGIS_SERVER",svrconnection) soe = 'NAServer' print "Enabling Network Analysis in the draft" # Read the sddraft xml. doc = DOM.parse(outsddraft) # Find all elements named TypeName. This is where the server object extension (SOE) names are defined. typeNames = doc.getElementsByTagName('TypeName') for typeName in typeNames: # Get the TypeName whose properties we want to modify. if typeName.firstChild.data == soe: extension = typeName.parentNode for extElement in extension.childNodes: # Enabled SOE. if extElement.tagName == 'Enabled': extElement.firstChild.data = 'true' # Output to a new sddraft. f = open(draftfinal, 'w') doc.writexml( f ) f.close() print "Staging Service" arcpy.StageService_server(draftfinal, outsd) print "Publishing to Server" arcpy.UploadServiceDefinition_server(outsd,svrconnection,"PythonNATest")
import arcpy, os import xml.dom.minidom as DOM print "Establishing environment" workspace = r"C:\temp\enableNA" mxd = arcpy.mapping.MapDocument(os.path.join(workspace,"enablenatest.mxd")) svrconnection = os.path.join(workspace, "svrconnection.ags") outsddraft = os.path.join(workspace,"service.sddraft") draftfinal = os.path.join(workspace,"draftfinal.sddraft") outsd = os.path.join(workspace,"naservice.sd") print "Creating initial draft" arcpy.mapping.CreateMapSDDraft(mxd, outsddraft, "PythonNaTest","ARCGIS_SERVER",svrconnection) soe = 'NAServer' print "Enabling Network Analysis in the draft" # Read the sddraft xml. doc = DOM.parse(outsddraft) # Find all elements named TypeName. This is where the server object extension (SOE) names are defined. typeNames = doc.getElementsByTagName('TypeName') for typeName in typeNames: # Get the TypeName whose properties we want to modify. if typeName.firstChild.data == soe: extension = typeName.parentNode for extElement in extension.childNodes: # Enabled SOE. if extElement.tagName == 'Enabled': extElement.firstChild.data = 'true' # Output to a new sddraft. f = open(draftfinal, 'w') doc.writexml( f ) f.close() print "Staging Service" arcpy.StageService_server(draftfinal, outsd) print "Publishing to Server" arcpy.UploadServiceDefinition_server(outsd,svrconnection,"PythonNATest")
I am trying to accomplish same thing like OP but I am getting an error after analyzing the modified sddraft file. I checked the modified sddraft and it is updated to "true". I can publish the mxd file using ArcMap with NA on. The error message is:
----ERRORS---
The Network Analyst extension needed for layer "Route" is not enabled (CODE 146)
applies to: Route
Dennis Jarrard, any help any help would be appreciated.
# https://enterprise.arcgis.com/en/server/10.4/administer/windows/example-publish-a-map-service-from-a-map-document-mxd-.htm
# https://community.esri.com/thread/179472
# http://desktop.arcgis.com/en/arcmap/10.4/analyze/arcpy-mapping/createmapsddraft.htm
# https://community.esri.com/thread/85441
# A connection to ArcGIS Server must be established in the
# Catalog window of ArcMap before running this script
import arcpy
import os
import urllib, urllib2
import httplib
import json
import sys
import xml.dom.minidom as DOM
# A function to generate a token given username, password and the adminURL.
def getToken():
# Token URL is typically http://server[:port]/arcgis/admin/generateToken
tokenURL = "/arcgis/admin/generateToken"
params = urllib.urlencode({
'username': portalAdminName,
'password': portalAdminPassword,
'client': 'requestip',
'f': 'json'
})
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
# Connect to URL and post parameters
httpConn = httplib.HTTPConnection(serverName, serverPort)
httpConn.request("POST", tokenURL, params, headers)
# Read response
response = httpConn.getresponse()
if response.status != 200:
httpConn.close()
print "Error while fetching tokens from admin URL. Please check the URL and try again."
return
else:
data = response.read()
httpConn.close()
# Extract the token from it
token = json.loads(data)
return token.get('token')
if len(sys.argv[1:]) != 9:
print len(sys.argv[1:])
print ("Parameters are missing or too many, check your parameters.")
sys.exit(2)
else:
mxd = sys.argv[1]
severadmurl = sys.argv[2]
portalAdminName = sys.argv[3]
portalAdminPassword = sys.argv[4]
serverName = sys.argv[5]
con = sys.argv[6]
severfolder = sys.argv[7]
maxRecordCount = sys.argv[8]
schemaLockingEnabled = sys.argv[9]
serverPort = 6080
# Define local variables
wrkspc = os.path.dirname(mxd)
arcpy.env.workspace = wrkspc
arcpy.env.overwriteOutput = True
# Generate Token
token = getToken()
print " \nProcessing {}".format(os.path.basename(mxd))
mapDoc = arcpy.mapping.MapDocument(mxd)
# Provide other service details
service = os.path.basename(mxd).split(".")[0] # service name
sddraft = wrkspc + "\\" + service + '.sddraft'
draftfinal = wrkspc + "\\" + service + 'draft.sddraft'
sd = wrkspc + "\\" + service + '.sd'
summary = mapDoc.description
tags = mapDoc.tags
# Create service definition draft
arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', con, True, severfolder, summary, tags)
naserver = 'NAServer'
print "Enabling Network Analysis in the draft"
doc = DOM.parse(sddraft)
# Find all elements named TypeName. This is where the server object extension (SOE) names are defined.
typeNames = doc.getElementsByTagName('TypeName')
for typeName in typeNames:
# Get the TypeName whose properties we want to modify.
if typeName.firstChild.data == naserver:
extension = typeName.parentNode
for extElement in extension.childNodes:
# Enabled SOE.
if extElement.tagName == 'Enabled':
extElement.firstChild.data = 'true'
# Output to a new sddraft.
f = open(draftfinal, 'w')
doc.writexml(f)
f.close()
# Analyze the service definition draft
analysis = arcpy.mapping.AnalyzeForSD(draftfinal)
# 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
print " "