def publishServices(self, mxdLists, con, clusterName='default', copy_data_to_server=True, folder=None): for file in self.checkfileValidation(mxdLists): serviceName = os.path.splitext(os.path.split(file)[1])[0] print "++++++++INFO:服务_" + serviceName.encode( 'utf-8') + "开始创建服务定义文件++++++++" clsCreateSddraft = CreateSddraft() sddraft = clsCreateSddraft.CreateSddraft(file, con, serviceName, copy_data_to_server, folder) print "++++++++INFO:开始分析服务:" + serviceName.encode( 'utf-8') + "++++++++" analysis = arcpy.mapping.AnalyzeForSD(sddraft) dirName = os.path.split(file)[0] if analysis['errors'] == {}: print "++++++++WARNING:不存在错误,但是有如下提示信息。这些内容可能会影响服务性能+++++++" print analysis['warnings'] if (not self.checkWarnings(analysis['warnings'])): try: sd = dirName + "\\" + serviceName + ".sd" if (os.path.exists(sd)): os.remove(sd) arcpy.StageService_server(sddraft, sd) print "++++++++INFO:服务:" + serviceName.encode( 'utf-8') + "打包成功+++++++" arcpy.UploadServiceDefinition_server( sd, con, in_cluster=clusterName) print "++++++++INFO:服务:" + str( serviceName) + "发布成功++++++" os.remove(sd) ####停止服务 except Exception, msg: print msg else: print "++++++++WARNING:强烈建议,退出当前程序,去注册数据源。如不退出,6s后发布服务继续+++" try: sd = dirName + "\\" + serviceName + ".sd" if (os.path.exists(sd)): os.remove(sd) arcpy.StageService_server(sddraft, sd) print "++++++++INFO:打包成功++++++++" print "正在执行发布函数" arcpy.UploadServiceDefinition_server( sd, con, in_cluster=clusterName) print "++++++++INFO:" + serviceName.encode( 'utf-8') + "发布成功+++++++" os.remove(sd) except Exception, msg: print msg
def rebuild_locator(self, locator): self.logger.logMsg('rebuilding {}'.format(locator)) arcpy.env.workspace = settings.LOCATORS_FGDB arcpy.RebuildAddressLocator_geocoding(locator) sdFile = '{}\{}.sd'.format(sddraftsFolder, locator) # clear out any old .sd files if arcpy.Exists(sdFile): arcpy.Delete_management(sdFile) sddraftFile = '{}\{}.sddraft'.format(sddraftsFolder, locator) if arcpy.Exists(sddraftFile): arcpy.Delete_management(sddraftFile) # delete existing locator service service = r'Geolocators/' + locator serviceType = 'GeocodeServer' self.logger.logMsg('deleting existing service') self.agsAdmin.deleteService(service, serviceType) # need to make a copy of the .sddraft file # since StateService deletes it self.logger.logMsg('publishing new service') arcpy.Copy_management( '{}\{}\{}.sddraft'.format(sddraftsFolder, settings.ORIGINALS_FOLDER, locator), sddraftFile) arcpy.StageService_server(sddraftFile, sdFile) arcpy.UploadServiceDefinition_server(sdFile, settings.GIS_SERVER_CONNECTION) self.logger.logMsg('validating service status') if (not self.agsAdmin.getStatus(service, serviceType)['realTimeState'] == 'STARTED'): raise '{} was not restarted successfully!'.format(service)
def __upload_service_definition_server(self, ags_file, sd_file): """ upload and publish GIS services to a specific GIS server according to the transition service definition .sd file. :param ags_file: the .ags.file origin private create_server_connfile method :param sd_file: the .sd file origin private stage_service_server method :return: True such as: ags_file = "E:\connectToSDE\conFile.ags" sd_file = "E:\connectToSDE\ty_region.sd" """ if not os.path.exists(ags_file): emsg = "__upload_service_definition_server ags_file is not exist" raise Exception(emsg) if not os.path.exists(sd_file): emsg = "__upload_service_definition_server sd_file is not exist" raise Exception(emsg) try: arcpy.UploadServiceDefinition_server(sd_file, ags_file) except Exception as e: emsg = "__upload_service_definition_server is error: %s" % e.message raise Exception(emsg) else: return True
def PublishService(mapDocPath, con): '''' mxd文档路径,服务名称和连接字符串路径''' mapDoc = arcpy.mapping.MapDocument(mapDocPath) # check the sd file exits or not for i in range(502, 551): serviceName = 'myMapServer' + str(i) sddraft = r"d:\workspace\test.sddraft" result = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, 'ARCGIS_SERVER', con, True, None) newSddaft = setTheClusterName(sddraft, 'ClusterC', serviceName) print newSddaft # analyze the service definition draft analysis = arcpy.mapping.AnalyzeForSD(newSddaft) if analysis['errors'] == {}: # Execute StageService sd = "d:\\workspace\\" + serviceName + ".sd" if (os.path.exists(sd)): os.remove(sd) arcpy.StageService_server(sddraft, sd) # Execute UploadServiceDefinition arcpy.UploadServiceDefinition_server(sd, con) print "publish successufully" + str(i) # createCache(con+"\\"+serviceName,i) else: print "Publish failed"
def run_process(self, *args): root_directory = args[0] self.log(f"Root directory is:{root_directory}") for (dirpath, dirs, files) in os.walk(root_directory): for filename in files: if not filename.endswith(".aprx"): continue try: full_file = os.path.join(root_directory, dirpath, filename) self.log(f"ArcGIS pro Project:{full_file}") head, tail = os.path.splitext(filename) self.log(f"Filename:{filename},head:{head},tail:{tail}") folder = os.path.basename(dirpath) self.log(dirpath) self.log(f"Publish folder is :{folder}") self.log(str(files)) enable_fa = self._config.enable_feature_access == 1 self.log(f"Enable feature access?:{str(enable_fa)}") temp_dir = TempFileName.make_temp_dir( ) # need to create this here as it will delete as soon as var goes out of scope sdfile = CreateSDFiles().create_sd_files_from_map( pro_prjx=full_file, service_name=head, folder=folder, working_dir=temp_dir, enable_feature_access=enable_fa) self.log(f"Uploading service definition file: {sdfile}") arcpy.UploadServiceDefinition_server( sdfile, self._config.fed_server) self.log("Upload done.") except Exception as e: self.errorlog(str(e))
def publishSDs(agsConnectionFile, SDList, started, folder): '''Function to publish SDs. Takes an AGS connection file and a list of SDs. If you only have 1 SD, you can send it in a list ['c:\foo\mySd.sd'] ''' if folder != "": folderType = 'EXISTING' else: folderType = "FROM_SERVICE_DEFINITION" folder = "" if started: startUp = "STARTED" else: startUp = "STOPPED" for sd in SDList: try: arcpy.UploadServiceDefinition_server(sd, agsConnectionFile, '', '', in_folder_type=folderType, in_folder=folder, in_startupType=startUp) arcpy.AddMessage("Published : " + str(sd[:-3])) except: arcpy.AddWarning("FAILED to publish " + str(sd[:-3])) arcpy.GetMessages(2) return
def PublishService(mapDocPath, serviceName, con, testWidget): '''' mxd文档路径,服务名称和连接字符串路径''' mapDoc = arcpy.mapping.MapDocument(mapDocPath) sd = os.path.splitext(mapDocPath)[0] + ".sd" sddraft = os.path.splitext(mapDocPath)[0] + ".sddraft" # check the sd file exits or not if os.path.exists(sd): os.remove(sd) result = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, 'ARCGIS_SERVER', con, True, None) if not result['errors'] == {}: print result['errors'] # analyze the service definition draft analysis = arcpy.mapping.AnalyzeForSD(sddraft) # stage and upload the service if the sddraft analysis did not contain errors if analysis['errors'] == {}: # Execute StageService arcpy.StageService_server(sddraft, sd) testWidget.insert("end", serviceName + "创建服务定义文件成功\n") # Execute UploadServiceDefinition arcpy.UploadServiceDefinition_server(sd, con) testWidget.insert("end", serviceName + "发布服务成功\n") else: # if the sddraft analysis contained errors, display them testWidget.insert("end", serviceName + "发布失败,失败原因为:%s\n" % analysis['errors'])
def PublishService(mapDocPath, serviceName, con): '''' mxd文档路径,服务名称和连接字符串路径''' mapDoc = arcpy.mapping.MapDocument(mapDocPath) sd = os.path.splitext(mapDocPath)[0] + ".sd" sddraft = os.path.splitext(mapDocPath)[0] + ".sddraft" # check the sd file exits or not if os.path.exists(sd): os.remove(sd) result = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, 'ARCGIS_SERVER', con, True, None) if not result['errors'] == {}: print result['errors'] # analyze the service definition draft analysis = arcpy.mapping.AnalyzeForSD(sddraft) # stage and upload the service if the sddraft analysis did not contain errors if analysis['errors'] == {}: # Execute StageService arcpy.StageService_server(sddraft, sd) # Execute UploadServiceDefinition arcpy.UploadServiceDefinition_server(sd, con) else: print "Publish failed"
def publishingMapService(workSpace, mxdFile, outAGSName): # define local variables mapDoc = arcpy.mapping.MapDocument(os.path.join(workSpace, mxdFile)) print('Map Document: {0}'.format(mapDoc.filePath)) service = mxdFile.split(".")[0] sddraft = os.path.join(workSpace, service + '.sddraft') sd = os.path.join(workSpace, service + '.sd') summary = 'Publishing Map Service Using Python' tags = 'python' # create service definition draft analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', outAGSName, True, None, summary, tags) print('Service definition draft file created: {0}'.format(sddraft)) # stage and upload the service if the sddraft analysis did not contain errors if analysis['errors'] == {}: if os.path.exists(sd): os.remove(sd) print("Existing service defination file deleted ... ") # Execute StageService arcpy.StageService_server(sddraft, sd) print('Service definition file created: {0}'.format(sd)) # Execute UploadServiceDefinition print('Uploading service...') arcpy.UploadServiceDefinition_server(sd, outAGSName) print("Success!") else: # if the sddraft analysis contained errors, display them print analysis['errors']
def run(): # Delete any existing sd and sddraft files if os.path.exists(SD_DRAFT_FN): os.remove(SD_DRAFT_FN) if os.path.exists(SD_FN): os.remove(SD_FN) logger.info("Running tool %s" % (GP_TOOL_TITLE)) arcpy.ImportToolbox( os.path.join(CODE_BASE, r'pp\pub_toolbox\PublishedTools.pyt')) results = [arcpy.publishedtools.FindPlantSites(COMMUNITY)] logger.info("Creating SDDraft %s" % (SD_DRAFT_FN)) arcpy.CreateGPSDDraft(results, SD_DRAFT_FN, GP_TOOL_TITLE, server_type='FROM_CONNECTION_FILE', connection_file_path=AGS_CONNECTION_FN, copy_data_to_server=False, folder_name=REST_FOLDER, summary='test', tags='test', executionType='Asynchronous', showMessages='Info', minInstances=1, maxInstances=2, maxUsageTime=10 * 60, resultMapServer=True) logger.info("Creating SD %s" % (SD_FN)) arcpy.server.StageService(SD_DRAFT_FN, SD_FN) logger.info("Uploading SD %s" % (SD_FN)) arcpy.UploadServiceDefinition_server(SD_FN, AGS_CONNECTION_FN) return
def create_service_definition(map_proj, sname, mpname, proj_dir, weblyrname): agol_serv_con = 'My Hosted Services' aprx = arcpy.mp.ArcGISProject(map_proj) outServiceDefinition = os.path.join(proj_dir, "{}.sd".format(sname)) sddraft_output_filename = os.path.join(proj_dir, "{}.sddraft".format(sname)) mplyrs = aprx.listMaps(mpname)[0] print(mplyrs) arcpy.mp.CreateWebLayerSDDraft(mplyrs, sddraft_output_filename, weblyrname, 'MY_HOSTED_SERVICES', 'FEATURE_ACCESS', overwrite_existing_service=1) arcpy.StageService_server(sddraft_output_filename, outServiceDefinition) print("Uploading {} Services to AGOL".format(sname)) arcpy.UploadServiceDefinition_server( outServiceDefinition, agol_serv_con, in_override=1, in_public=0, in_organization=1, in_groups=["Town of Apex Authoritative GIS Data"]) print("-------Web Service Succesfully Published--------")
def publish_draft(self, sddraft, sd, config): self.message("Staging service definition...") arcpy.StageService_server(sddraft, sd) self.delete_service(config) self.message("Uploading service definition...") arcpy.UploadServiceDefinition_server(sd, self.connection_file_path) self.update_service(config)
def publish_images(draft_workspace, input_raster, con_path, service_name): import arcpy try: start_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S', time.localtime(time.time())) start = time.time() s = start print("Publishing Services,Start time:" + start_timeStampName) arcpy.env.overwriteOutput = True # Set output file names sddraft_filename = os.path.join(draft_workspace, service_name + '.sddraft') arcpy.CreateImageSDDraft(input_raster, sddraft_filename, service_name, 'ARCGIS_SERVER', con_path, False, None, "Publish image service for smart show", "lands,image service") end_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S', time.localtime(time.time())) end = time.time() elapse_time = end - start print("Create image sddraft finished, at time:" + end_timeStampName, "Elapsed time:", elapse_time, "s") # Stage Service start = time.time() sd_filename = service_name + ".sd" sd_output_filename = os.path.join(draft_workspace, sd_filename) arcpy.StageService_server(sddraft_filename, sd_output_filename) end_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S', time.localtime(time.time())) end = time.time() elapse_time = end - start print("Stage Service finished, at time:" + end_timeStampName, "Elapsed time:", elapse_time, "s") # Share to portal start = time.time() arcpy.UploadServiceDefinition_server(sd_output_filename, con_path) end_timeStampName = time.strftime('%Y_%m_%d %H:%M:%S', time.localtime(time.time())) end = time.time() elapse_time = end - start print( "Uploading service definition finished, at time:" + end_timeStampName, "Elapsed time:", elapse_time, "s") elapse_time = end - s print( "Completed publishing images service,ending time:" + end_timeStampName, "Total Elapsed time:", elapse_time, "s") except: print("Publish images failed.") print() arcpy.GetMessages()
def publishServices(self,mxdLists,con,clusterName='default',copy_data_to_server=True,folder=None): for file in self.checkfileValidation(mxdLists): ###tmp: serviceslist=[] serviceName=os.path.splitext(os.path.split(file)[1])[0] arcpy.AddMessage( "++++++++INFO: Service_"+serviceName +" Start to create SD++++++++") clsCreateSddraft=CreateSddraft() sddraft=clsCreateSddraft.CreateSddraft(file,con,serviceName,copy_data_to_server,folder) arcpy.AddMessage( "++++++++INFO: Start to analyse :"+serviceName+"++++++++") analysis = arcpy.mapping.AnalyzeForSD(sddraft) dirName=os.path.split(file)[0] if analysis['errors'] == {}: arcpy.AddMessage( "++++++++WARNING:No error, but following warnings exist:+++++++") arcpy.AddMessage( analysis['warnings']) if(not self.checkWarnings(analysis['warnings'])): try: sd=dirName+"\\"+serviceName+".sd" if(os.path.exists(sd)): os.remove(sd) arcpy.StageService_server(sddraft, sd) arcpy.AddMessage( "++++++++INFO:Service:"+ str(serviceName) +" Packed+++++++") arcpy.UploadServiceDefinition_server(sd, con,in_cluster=clusterName) arcpy.AddMessage( "++++++++INFO:Service:"+str(serviceName)+" Published++++++") os.remove(sd) ####Stop service except Exception,msg: arcpy.AddMessage( msg) else: arcpy.AddMessage( "++++++++WARNING:SUGGEST: END THIS AND REGISTER YOUR DATA SOURCE. Continue publishing in 6s +++") # time.sleep(10) try: sd=dirName+"\\"+serviceName+".sd" if(os.path.exists(sd)): os.remove(sd) arcpy.StageService_server(sddraft, sd) arcpy.AddMessage( "++++++++INFO: " + serviceName + " Packed++++++++") arcpy.UploadServiceDefinition_server(sd, con,in_cluster=clusterName) arcpy.AddMessage( "++++++++INFO: " + serviceName + " Published+++++++") os.remove(sd) except Exception,msg: arcpy.AddMessage( msg)
def UploadtoAGOL(sd): result = False log('Uploading and provisioning services') try: uploadSDresult = arcpy.UploadServiceDefinition_server( sd, 'My Hosted Services') result = uploadSDresult.getOutput(3) except arcgisscripting.ExecuteError as e: log('ERROR: ' + e.message) return result
def PublishService(mxdpath, agspath, sddraftpath, sdpath, serviceName="idwRes"): # Define local variables mapDoc = arcpy.mapping.MapDocument(mxdpath) # Provide path to connection file # To create this file, right-click a folder in the Catalog window and # click New > ArcGIS Server Connection con = agspath # Provide other service details service = serviceName sddraft = sddraftpath sd = sdpath if os.path.exists(sddraft): os.remove(sddraft) if os.path.exists(sd): os.remove(sd) summary = 'General reference map of the ' + serviceName tags = serviceName # Create service definition draft arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, service, 'ARCGIS_SERVER', con, True, None, 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() return agspath.replace(".ags", "/" + service + ".MapServer")
def publish_hosted_feature_service(map_doc, service_name, initial_sd_draft, share_level, share_org, share_groups, sd, updated_sd_draft, summary, tags): see_if_service_def_exists(sd) try: arcpy.mapping.CreateMapSDDraft(map_doc, initial_sd_draft, service_name, 'MY_HOSTED_SERVICES', summary=summary, tags=tags) # Read the contents of the original SDDraft into an xml parser sd_draft_xml = dom.parse(initial_sd_draft) change_types(sd_draft_xml.getElementsByTagName('Type')) change_states(sd_draft_xml.getElementsByTagName('State')) change_service_type(sd_draft_xml.getElementsByTagName('TypeName')) turn_off_caching( sd_draft_xml.getElementsByTagName('ConfigurationProperties')[0]) turn_on_feature_access(sd_draft_xml.getElementsByTagName('Info'[0])) write_new_draft(updated_sd_draft, sd_draft_xml) analysis = arcpy.mapping.AnalyzeForSD(updated_sd_draft) if analysis['errors'] == {}: # Stage the service arcpy.StageService_server(updated_sd_draft, 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( in_sd_file=sd, in_server='My Hosted Services', in_service_name=service_name, in_override='OVERRIDE_DEFINITION', in_my_contents='SHARE_ONLINE', in_public=share_level, in_organization=share_org, in_groups=share_groups) print 'Uploaded and overwrote service.' else: # If the sd draft analysis contained errors, display them and quit. print analysis['errors'] except: print arcpy.GetMessages()
def publish_service(service_name, results): """Publishes the results list to an ArcGIS Server specified in the config module""" # Create Service draft. sddraft = arcpy.CreateUniqueName(service_name + '.sddraft') info = arcpy.CreateGPSDDraft(results, sddraft, service_name, folder_name=ARC_SERVER['serviceFolder'], showMessages='INFO') sd = arcpy.CreateUniqueName(service_name + '.sd') info = arcpy.StageService_server(sddraft, sd) info = arcpy.UploadServiceDefinition_server(sd, ARC_SERVER['uri']) return sd
def publish_service(ags_folder, map_document): map_document_file_name = ntpath.basename(map_document) # build up a name for the service, the sddraft file name, and the sd file name sd_draft_path = map_document.replace('.mxd', '.sddraft') sd = map_document.replace('.mxd', '.sd') service_name = os.path.splitext(map_document_file_name)[0] # create the SDDraft file arcpy.mapping.CreateMapSDDraft(map_document, sd_draft_path, service_name, 'ARCGIS_SERVER', cfg.AGS_CONN, True, None, '', '') # alter some of the settings in the SDDraft sddraft = SDDraft.load(sd_draft_path) sddraft.set_property('antialiasingMode', 'Fast') sddraft.set_property('textAntialiasingMode', 'Force') sddraft.set_manifest_type('esriServiceDefinitionType_Replacement') sddraft.save() del sddraft # analyse the service analysis = arcpy.mapping.AnalyzeForSD(sd_draft_path) # check for analysis errors, if there are none publish the service if analysis['errors'] == {}: arcpy.StageService_server(sd_draft_path, sd) arcpy.UploadServiceDefinition_server(sd, cfg.AGS_CONN, service_name, "default", "EXISTING", ags_folder, "STARTED") print "Service successfully published" sys.exit(0) else: 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 print "Service could not be published because errors were found during analysis" sys.exit(1)
def new_service(sname, mpname, weblyrname): # upload service definition, sharing set to everyone print("Uploading {} Services to AGOL.".format(sname)) arcpy.UploadServiceDefinition_server(outServiceDefinition, agol_serv_con, in_override=1, in_public=True, in_organization=True) print("-------Web Service Successfully Published--------", "Adding new services to Open Data Group.\n") # use GIS module to add new services to Open Data folder new_data = gis.content.search(query="tags:{}".format(mpname), item_type='Feature Layer') l = len(new_data) for x in range(0, 1): data = new_data[x] data.share(groups=group.groupid) print("{} Services added to Open Data Group".format(weblyrname))
def create_service_definition(map_proj, sname, mpname, proj_dir, weblyrname): agol_serv_con = 'My Hosted Services' aprx = arcpy.mp.ArcGISProject(map_proj) outServiceDefinition = os.path.join(proj_dir, "{}.sd".format(sname)) sddraft_output_filename = os.path.join(proj_dir, "{}.sddraft".format(sname)) try: mplyrs = aprx.listMaps(mpname)[0] #print (mplyrs) arcpy.mp.CreateWebLayerSDDraft(mplyrs, sddraft_output_filename, weblyrname, 'MY_HOSTED_SERVICES', 'FEATURE_ACCESS', overwrite_existing_service=1) except: tb = traceback.format_exc() email(tb) raise sys.exit() try: arcpy.StageService_server(sddraft_output_filename, outServiceDefinition) except: tb = traceback.format_exc() email(tb) raise sys.exit() try: print("Uploading {} Services to AGOL".format(sname)) arcpy.UploadServiceDefinition_server( outServiceDefinition, agol_serv_con, in_override="OVERRIDE_DEFINITION", in_public="PUBLIC", in_organization="SHARE_ORGANIZATION", in_groups=["Apex Recollect Data and Applications"], in_my_contents="SHARE_ONLINE") except: tb = traceback.format_exc() email(tb) raise sys.exit() print("-------Web Service Succesfully Published--------")
def uploadServiceDefinition(sdFilePath, agsPubConnectionFile, startService=True): success = True pymsg = "" try: if startService: startService = "STARTED" else: startService = "STOPPED" arcpy.UploadServiceDefinition_server(sdFilePath, agsPubConnectionFile, in_startupType=startService, in_cluster='default') except: success = False pymsg = "\tError Info:\n\t" + str(sys.exc_info()[1]) finally: return [success, pymsg]
def create_service(temp_folder, map_document, server_path, service_name, folder_name=''): """Creates a map service on an ArcGIS Server machine or in an ArcGIS Online account. :param temp_folder: folder path where temporary files are created :param map_document: map document object :param server_path: the ArcGIS server path or connection file path (.ags) :param service_name: the name of the service to be created :param folder_name: the folder where the service is created """ # Create a temporary definition file. draft_file = '{0}.sddraft'.format(os.path.join(temp_folder, service_name)) status_writer.send_status(_('Creating map sd draft...')) arcpy.mapping.CreateMapSDDraft(map_document, draft_file, service_name, 'ARCGIS_SERVER', folder_name=folder_name, copy_data_to_server=True, summary=map_document.description, tags=map_document.tags) # Analyze the draft file for any errors before staging. status_writer.send_status(_('Analyzing the map sd draft...')) analysis = arcpy.mapping.AnalyzeForSD(draft_file) if analysis['errors'] == {}: # Stage the service. stage_file = draft_file.replace('sddraft', 'sd') status_writer.send_status(_('Staging the map service...')) arcpy.StageService_server(draft_file, stage_file) else: # If the sddraft analysis contained errors, display them and quit. if (u'Data frame does not have a spatial reference', 2) in analysis['errors']: errors = 'Cannot publish results. One or more inputs is missing a spatial reference.' else: errors = analysis['errors'] raise task_utils.AnalyzeServiceException(errors) # Upload/publish the service. status_writer.send_status(_('Publishing the map service to: {0}...').format(server_path)) result = arcpy.UploadServiceDefinition_server(stage_file, server_path, service_name) status_writer.send_status(_('Successfully created: {0}').format(result.getOutput(0))) return
def rebuild_locator(self, locator): sddraftsFolder = path.join(path.dirname(__file__), 'sddrafts') self.log.info('rebuilding {}'.format(locator)) arcpy.RebuildAddressLocator_geocoding(path.join( self.locators, locator)) sdFile = '{}\\{}.sd'.format(sddraftsFolder, locator) #: clear out any old .sd files if arcpy.Exists(sdFile): arcpy.Delete_management(sdFile) sddraftFile = '{}\\{}.sddraft'.format(sddraftsFolder, locator) if arcpy.Exists(sddraftFile): arcpy.Delete_management(sddraftFile) #: delete existing locator service service = 'Geolocators/' + locator serviceType = 'GeocodeServer' self.log.info('deleting existing service') try: self.agsAdmin.deleteService(service, serviceType) except Exception: pass #: need to make a copy of the .sddraft file #: since StageService deletes it copy_location = '{}\\{}\\{}.sddraft'.format(sddraftsFolder, 'originals', locator) self.log.info('publishing new service') arcpy.Copy_management(copy_location, sddraftFile) self.log.info('copy done') arcpy.StageService_server(sddraftFile, sdFile) self.log.info('stage done') gis_server_connection = path.join(path.dirname(__file__), 'server') arcpy.UploadServiceDefinition_server(sdFile, gis_server_connection) self.log.info('upload done') self.log.info('validating service status') if (not self.agsAdmin.getStatus(service, serviceType)['realTimeState'] == 'STARTED'): raise '{} was not restarted successfully!'.format(service)
def publishMXD(self, mxdPath, definitionType=None, maxRecordCount=None, maxInstances=None): ''' :param mxdPath: 地图文档路径 :param definitionType: esriServiceDefinitionType_Replacement 覆盖更新 :param maxRecordCount: 最大返回数 :param maxInstances: 最大实例数 :return: ''' try: new_mxd = arcpy.mapping.MapDocument(mxdPath) mxdName = os.path.basename(mxdPath) dotIndex = mxdName.index('.') serviceName = mxdName[0:dotIndex] sddraft = os.path.abspath(serviceName + '.sddraft') sd = os.path.abspath(serviceName + '.sd') if os.path.exists(sd): os.remove(sd) # 创建服务定义草稿draft analysis = arcpy.mapping.CreateMapSDDraft(new_mxd, sddraft, serviceName, 'ARCGIS_SERVER', self.agspath, False, self.type, None, None) if analysis['errors'] == {}: self.editSddraft(sddraft, definitionType, maxRecordCount, maxInstances) # Execute StageService arcpy.StageService_server(sddraft, sd) # Execute UploadServiceDefinition arcpy.UploadServiceDefinition_server(sd, self.agspath) else: # if the sddraft analysis contained errors, display them print analysis['errors'] except: self.logger.warning(traceback.format_exc())
def PublishService(connection_file_path, wrkspc, mapDoc): #get the serviceName serviceName = os.path.basename(mapDoc).replace(".mxd", "") #create the .sddraft path sddraftname = os.path.basename(mapDoc).replace(".mxd", ".sddraft") sddraft = str(wrkspc) + "/" + str(sddraftname) #create the .sd file path sdname = os.path.basename(mapDoc).replace(".mxd", ".sd") sd = str(wrkspc) + "/" + str(sdname) #check the file exists or not if (os.path.exists(sd)): os.remove(sd) analysis = arcpy.mapping.CreateMapSDDraft(mapDoc, sddraft, serviceName, 'ARCGIS_SERVER', connection_file_path, True, None, None, None) arcpy.StageService_server(sddraft, sd) arcpy.UploadServiceDefinition_server(sd, connection_file_path)
def createService(): global serviceNameEntry print("starting Operation...") serviceName = serviceNameEntry.get() #mapName = mapNameEntry.get() mapName = dataFrameName #print (mapName) #outdir = r"C:\Project\Output" outdir = pathFile service = serviceName #print(service) sddraft_filename = service + ".sddraft" sddraft_output_filename = os.path.join(outdir, sddraft_filename) # Reference map to publisht #aprx = arcpy.mp.ArcGISProject(r"C:\Users\emil9669\Desktop\portland.aprx") aprx = aprxFile #print (aprxFile) m = aprx.listMaps(mapName)[0] # Create MapServiceDraft and set service properties service_draft = arcpy.sharing.CreateSharingDraft("STANDALONE_SERVER", "MAP_SERVICE", service, m) #service_draft.targetServer = r"C:\Users\emil9669\Documents\ArcGIS\Projects\MyProject21\arcgis on mashupdev.esri.com (1).ags" service_draft.targetServer = serverFile # Create Service Definition Draft file service_draft.exportToSDDraft(sddraft_output_filename) # Stage Service sd_filename = service + ".sd" sd_output_filename = os.path.join(outdir, sd_filename) arcpy.StageService_server(sddraft_output_filename, sd_output_filename) # Share to portal print("Uploading Service Definition...") #arcpy.UploadServiceDefinition_server(sd_output_filename, r"C:\Users\emil9669\Documents\ArcGIS\Projects\MyProject21\arcgis on mashupdev.esri.com (1).ags") arcpy.UploadServiceDefinition_server(sd_output_filename, serverFile) print("Successfully Uploaded service.")
def multiPatch2ServerDefinition(dsFolder,mpName): # Change scene and layer as yours ... SceneName = 'MyScene' LayerName = '3dlayer' # Find the Scene aprx = arcpy.mp.ArcGISProject(projectFile) m = aprx.listMaps(SceneName)[0] print(m.name) print(m.mapType) # Change data source of the existing layer for lyr in m.listLayers(LayerName): print(lyr.connectionProperties) conProp = lyr.connectionProperties print(conProp['connection_info']['database']) conProp['connection_info']['database'] = dsFolder print(conProp['dataset']) conProp['dataset'] = mpName lyr.connectionProperties = conProp aprx.save() print('add layer to Project : ' + mpName) sddraftFile = os.path.join(sdFolder, mpName.__str__() + '_ArcPy162' + '.sddraft') sdFile = os.path.join(sdFolder, mpName.__str__() + '_ArcPy162' + '.sd') #### Publish Feature Service arcpy.mp.CreateWebLayerSDDraft(m, sddraftFile, mpName, 'MY_HOSTED_SERVICES', 'FEATURE_ACCESS') print('make SDDraft file : ' + sddraftFile) result = arcpy.StageService_server(sddraftFile, sdFile) print('make SD file : ' + sdFile) #### GP Service arcpy.CreateGPSDDraft(result, os.path.join(sdFolder, "GPoutput2.sddraft"), "myGPservice22") print("GP Draft Done!") arcpy.StageService_server(os.path.join(sdFolder, "GPoutput2.sddraft"), os.path.join(sdFolder, "GPoutput22.sd") ) print("GP SD Done!") # Fialed arcpy.UploadServiceDefinition_server(os.path.join(sdFolder, "GPoutput22.sd"), 'My Hosted Services') print('aaa')
def addServices(serviceDict, serverName, serverPort, token, agsConnection): for serviceToAdd in serviceDict: # Check to see that SD is present and that it is reachable. if not os.path.isfile(serviceDict[serviceToAdd]['in_sd_file']): print("Unable to access '" + serviceDict[serviceToAdd]['in_sd_file'] + "'. Skipping to publish.") else: # Delete the service first (if it exists) and then re-publish it if serviceDict[serviceToAdd].has_key("in_service_name"): if serviceDict[serviceToAdd].has_key("in_folder"): deleteServiceIfPresent( serverName, serverPort, token, serviceDict[serviceToAdd]["in_service_name"], serviceDict[serviceToAdd]["in_folder"]) else: deleteServiceIfPresent( serverName, serverPort, token, serviceDict[serviceToAdd]["in_service_name"]) serviceDict[serviceToAdd]["in_server"] = agsConnection print "Publishing the service: " + serviceDict[serviceToAdd][ 'in_sd_file'] try: arcpy.UploadServiceDefinition_server( **serviceDict[serviceToAdd]) print "Successfully published the service: " + serviceDict[ serviceToAdd]['in_sd_file'] except Exception, e: print "Publishing of " + serviceDict[serviceToAdd][ 'in_sd_file'] + " failed." print e.message
def publish_results(): # Sign in to portal arcpy.SignInToPortal("https://esriau.maps.arcgis.com/","","") # Set output file names outdir = os.path.join(os.path.dirname(__file__), 'sd') service = "FS_WazeEllipses_KL" sddraft_filename = service + ".sddraft" sddraft_output_filename = os.path.join(outdir, sddraft_filename) # Reference map to publish aprx = arcpy.mp.ArcGISProject(os.path.join(os.path.dirname(__file__), 'WazeForPublishing.aprx')) m = aprx.listMaps("Waze For Publishing")[0] # Create FeatureSharingDraft and set service properties sharing_draft = m.getWebLayerSharingDraft("HOSTING_SERVER", "FEATURE", service) sharing_draft.overwriteExistingService = "True" sharing_draft.portalFolder = "Waze" sharing_draft.summary = "Waze Ellipses created from a python script that pulls latest Waze data for Kuala Lumpur" sharing_draft.tags = "Waze, BGT, Kuala Lumpur" sharing_draft.description = "Latest Waze Jam incidents downloaded and a density clustering performed. Ellipses generated around the main clusters" sharing_draft.credits = "Waze CCP" sharing_draft.useLimitations = "Demo Purposes Only" # Create Service Definition Draft file sharing_draft.exportToSDDraft(sddraft_output_filename) # Stage Service sd_filename = service + ".sd" sd_output_filename = os.path.join(outdir, sd_filename) arcpy.StageService_server(sddraft_output_filename, sd_output_filename) # Share to portal print("Uploading Service Definition for publishing") arcpy.UploadServiceDefinition_server(sd_output_filename, "My Hosted Services", in_override="OVERRIDE_DEFINITION", in_public="PUBLIC") print("Successfully Uploaded & Published.")