import arcpy import xml.dom.minidom as DOM import os workspace = 'C:/Temp/hosted publishing/' # Reference map document for CreateSDDraft function. mapDoc = arcpy.mapping.MapDocument(r'C:\Temp\betty4.mxd') # Create service and sddraft variables for CreateSDDraft function. sddraft = workspace + 'HostedMS.sddraft' service = 'FeatureService' arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'MY_HOSTED_SERVICES', summary="test", tags='test') con = 'My Hosted Services' sd = workspace + service + '.sd' doc = DOM.parse(sddraft) # Read the sddraft xml. doc = DOM.parse(sddraft) # Change service from map service to feature service typeNames = doc.getElementsByTagName('TypeName') for typeName in typeNames: # Get the TypeName we want to disable. if typeName.firstChild.data == "MapServer": typeName.firstChild.data = "FeatureServer" #Turn off caching configProps = doc.getElementsByTagName('ConfigurationProperties')[0] propArray = configProps.firstChild propSets = propArray.childNodes for propSet in propSets: keyValues = propSet.childNodes for keyValue in keyValues: if keyValue.tagName == 'Key': if keyValue.firstChild.data == "isCached": # turn on caching keyValue.nextSibling.firstChild.data = "false" #Turn on feature access capabilities configProps = doc.getElementsByTagName('Info')[0] propArray = configProps.firstChild propSets = propArray.childNodes for propSet in propSets: keyValues = propSet.childNodes for keyValue in keyValues: if keyValue.tagName == 'Key': if keyValue.firstChild.data == "WebCapabilities": # turn on caching keyValue.nextSibling.firstChild.data = "Query,Create,Update,Delete,Uploads,Editing" outXml = workspace + 'HostedMSNew.sddraft' f = open(outXml, 'w') doc.writexml( f ) f.close() analysis = arcpy.mapping.AnalyzeForSD(outXml) #print analysis #arcpy.SignOutFromPortal_server() arcpy.SignInToPortal_server("username","password","http://www.arcgis.com/") arcpy.StageService_server(outXml, sd) arcpy.UploadServiceDefinition_server(sd, con)
typeReplace = 'esriServiceDefinitionType_Replacement' statePublished = 'esriSDState_Published' myTagsType = doc.getElementsByTagName('Type') for myTagType in myTagsType: if myTagType.parentNode.tagName == 'SVCManifest': if myTagType.hasChildNodes(): myTagType.firstChild.data = typeReplace myTagsState = doc.getElementsByTagName('State') for myTagState in myTagsState: if myTagState.parentNode.tagName == 'SVCManifest': if myTagState.hasChildNodes(): myTagState.firstChild.data = statePublished
ExecuteError: Failed to execute. Parameters are not valid. ERROR 000732: Server: Dataset My Hosted Services does not exist or is not supported Failed to execute (UploadServiceDefinition).
tribeiro:You've made a GP Service to perform this publishing routine?I'd strongly recommend against that. The Upload and Stage tools (which are required in this workflow) are not designed to be re-published in your own geoprocessing service. I'd suggest making it a scheduled task on one of your desktop machines.
ExecuteError: Failed to execute. Parameters are not valid.ERROR 000732: Server: Dataset My Hosted Services does not exist or is not supportedWARNING 001404: You are not signed in to ArcGIS Online.Failed to execute (UploadServiceDefinition).
I'm able to publish/overwrite the service with 10.2 only when I comment out the SignInToPortal line and sign in separately using ArcGIS Desktop. Is anyone else having this problem with ArcGIS 10.2? Are there any workarounds?Thanks,Erik
Executing: UploadServiceDefinition C:\Workspace\KYEM_Test\KYEM_TEST3.sd "My Hosted Services" KYEM_TEST3 # FROM_SERVICE_DEFINITION # STARTED OVERRIDE_DEFINITION SHARE_ONLINE PRIVATE NO_SHARE_ORGANIZATION # Start Time: Mon Sep 16 14:06:05 2013 Failed to execute. Parameters are not valid. ERROR 000732: Server: Dataset My Hosted Services does not exist or is not supported WARNING 001404: You are not signed in to ArcGIS Online. Failed to execute (UploadServiceDefinition). Failed at Mon Sep 16 14:06:05 2013 (Elapsed Time: 0.02 seconds)
import arcpy, os, sys from datetime import datetime import xml.dom.minidom as DOM arcpy.env.overwriteOutput = True # Define global variables from User Input mapDoc = 'KYEM.mxd' serviceName = 'KYEM' shareLevel = 'PRIVATE' # Options: PUBLIC or PRIVATE shareOrg = 'NO_SHARE_ORGANIZATION' # Options: SHARE_ORGANIZATION and NO_SHARE_ORGANIZATION shareGroups = '' # Options: Valid groups that user is member of tempPath = sys.path[0] #SignInToPortal function does not work in 10.2 #for 10.1: uncomment below line to enable sign in #for 10.2: (1): Sign in to arcgis desktop and check 'sign in automatically' # (2): Schedule task to run publishFS.py script, using same user as in step 1 ##arcpy.SignInToPortal_server('','','http://www.arcgis.com/') sdDraft = tempPath+'/{}.sddraft'.format(serviceName) newSDdraft = 'updatedDraft.sddraft' try: os.remove(serviceName+'.sd') print 'SD already exists, overwriting..' SD = os.path.join(tempPath, serviceName + '.sd') print 'File removed and overwritten' except OSError: print 'No SD exists, writing one now.' SD = os.path.join(tempPath, serviceName + '.sd') try: # create service definition draft analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sdDraft, serviceName, 'MY_HOSTED_SERVICES') # Read the contents of the original SDDraft into an xml parser doc = DOM.parse(sdDraft) # The follow 5 code pieces modify the SDDraft from a new MapService # with caching capabilities to a FeatureService with Query,Create, # Update,Delete,Uploads,Editing capabilities. The first two code # pieces handle overwriting an existing service. The last three pieces # change Map to Feature Service, disable caching and set appropriate # capabilities. You can customize the capabilities by removing items. # Note you cannot disable Query from a Feature Service. tagsType = doc.getElementsByTagName('Type') for tagType in tagsType: if tagType.parentNode.tagName == 'SVCManifest': if tagType.hasChildNodes(): tagType.firstChild.data = 'esriServiceDefinitionType_Replacement' tagsState = doc.getElementsByTagName('State') for tagState in tagsState: if tagState.parentNode.tagName == 'SVCManifest': if tagState.hasChildNodes(): tagState.firstChild.data = 'esriSDState_Published' # Change service type from map service to feature service typeNames = doc.getElementsByTagName('TypeName') for typeName in typeNames: if typeName.firstChild.data == 'MapServer': typeName.firstChild.data = 'FeatureServer' #Turn off caching configProps = doc.getElementsByTagName('ConfigurationProperties')[0] propArray = configProps.firstChild propSets = propArray.childNodes for propSet in propSets: keyValues = propSet.childNodes for keyValue in keyValues: if keyValue.tagName == 'Key': if keyValue.firstChild.data == 'isCached': keyValue.nextSibling.firstChild.data = 'false' #Turn on feature access capabilities configProps = doc.getElementsByTagName('Info')[0] propArray = configProps.firstChild propSets = propArray.childNodes for propSet in propSets: keyValues = propSet.childNodes for keyValue in keyValues: if keyValue.tagName == 'Key': if keyValue.firstChild.data == 'WebCapabilities': keyValue.nextSibling.firstChild.data = 'Query,Create,Update,Delete,Uploads,Editing' # Write the new draft to disk f = open(newSDdraft, 'w') doc.writexml( f ) f.close() # Analyze the service analysis = arcpy.mapping.AnalyzeForSD(newSDdraft) if analysis['errors'] == {}: # Stage the service arcpy.StageService_server(newSDdraft, SD) # Upload the service. The OVERRIDE_DEFINITION parameter allows you to override the # sharing properties set in the service definition with new values. arcpy.UploadServiceDefinition_server(SD, 'My Hosted Services', serviceName, '', '', '', '', 'OVERRIDE_DEFINITION','SHARE_ONLINE', shareLevel, shareOrg, shareGroups) print 'Uploaded and overwrote service' # Write messages to a Text File txtFile = open(tempPath+'/{}-log.txt'.format(serviceName),"a") txtFile.write (str(datetime.now()) + " | " + "Uploaded and overwrote service" + "\n") txtFile.close() else: # If the sddraft analysis contained errors, display them and quit. print analysis['errors'] # Write messages to a Text File txtFile = open(tempPath+'/{}-log.txt'.format(serviceName),"a") txtFile.write (str(datetime.now()) + " | " + analysis['errors'] + "\n") txtFile.close() except: print arcpy.GetMessages() # Write messages to a Text File txtFile = open(tempPath+'/{}-log.txt'.format(serviceName),"a") txtFile.write (str(datetime.now()) + " | Last Chance Message:" + arcpy.GetMessages() + "\n") txtFile.close()
Executing: UploadServiceDefinition C:\Workspace\KYEM_Test\KYEM_TEST3.sd "My Hosted Services" KYEM_TEST3 # FROM_SERVICE_DEFINITION # STARTED OVERRIDE_DEFINITION SHARE_ONLINE PRIVATE NO_SHARE_ORGANIZATION # Start Time: Thu Sep 19 08:41:03 2013 ERROR 001566: Service overwrite error: failed to delete the service. ERROR: code:400, Item 'e18aae36f2874deba39e380611c59745' does not exist or is inaccessible., Bad syntax in request. Failed to execute (UploadServiceDefinition).
from subprocess import Popen, PIPE import win32com.client import time import os proc = Popen(["C:\\Program Files (x86)\\ArcGIS\\Desktop10.2\\bin\\ArcMap.exe", "c:\\temp\\states.mxd"], stdout=PIPE) # put in a dummy mxd to get around the start dialog time.sleep(10) shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys("%f", 0) # sends ALT+F to the UI, which signs you in - just opening ArcMap doesnt sign you in. You have to click the file menu < code to overwrite a hosted feature service goes here > os.system("taskkill /im arcmap.exe /f")
import json, urllib, urllib2 def gentoken(username, password, referer, expiration=60): #Re-usable function to get a token required for Admin changes referer = "http://www.arcgis.com/" query_dict = {'username': username, 'password': password, 'expiration': str(expiration), 'client': 'referer', 'referer': referer, 'f': 'json'} query_string = urllib.urlencode(query_dict) tokenUrl = "https://www.arcgis.com/sharing/rest/generateToken" tokenResponse = urllib.urlopen(tokenUrl, urllib.urlencode(query_dict)) token = json.loads(tokenResponse.read()) if "token" not in token: print token['messages'] import sys sys.exit() else: # Return the token to the function which called for it return token['token'] def enableAttachment(token, fsURL): query_dict = {'updateDefinition': "{'hasAttachments':true}", #false 'f': 'json', 'token': token} query_string = urllib.urlencode(query_dict) attachResponse = urllib.urlopen(fsURL, urllib.urlencode(query_dict)) msg = json.loads(attachResponse.read()) print msg return USERNAME = " ______ " PASSWORD = " ______ " REFFER = "http://www.arcgis.com" fsURL = "http://services1.arcgis.com/<ORGANIZATION IDENTFIER/arcgis/admin/services/<SERVICE NAME>.FeatureServer/0/updateDefinition" # for example, a link may look like: #http://services1.arcgis.com/4safsf2dgg32daf3/arcgis/admin/services/MyService.FeatureServer/0/updateDefinition token = gentoken(USERNAME, PASSWORD, REFFER) enableAttachment(token, fsURL)
Besides the overwrite issue, has anyone been able to get this automated process to work in v10.2?Can you get this automated process to work on a brand new service where there is no overwrite to be done?
I'm attempting to implement the 10.2 version of this script and keep running into the error that Consolidating the data failed when attempting to stage the service from a SDDraft document.
Traceback (most recent call last):
File "C:\Python27\ArcGISx6410.2\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
exec codeObject in __main__.__dict__
File "\\AGOL\py\update.py", line 406, in <module>
updateSD()
File "\\AGOL\py\update.py", line 249, in updateSD
arcpy.StageService_server(newSDdraft, SD)
File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\server.py", line 1204, in StageService
raise e
ExecuteError: ERROR 001270: Consolidating the data failed.
Failed to execute (StageService).
Any ideas?
I realize that this post is over two years old now, but I'm trying to run this script using 10.3 - has this requirement to be logged in through ArcMap been corrected? I'm trying to set up exactly the situation you described - a nightly auto-update.
Any ideas are greatly appreciated..
Hey Jeff,
Could you please share the code in a little nicer way to look at it?
I am very new to python and I am trying to step my way through the code but I cant seem to separate it our very well since its all in a line.
Thanks
I know this is an old post, but that link seems to be dead. Is the blog post archived somewhere?
Is there a way get this code in actual lines of code rather than one enormously large single line of code? I'm guessing there is a browser SNAFU. But IE, FF and Chrome are all currently displaying your response as a single line of code.
Membros conectados podem postar, seguir atualizações e mais. Novo aqui? Registre uma conta gratuita.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.