def convert_service_draft_to_staged_service(sd_draft, sd_path): if os.path.exists(sd_path): os.remove(sd_path) if isinstance(sd_draft, basestring): arcpy.StageService_server(sd_draft, sd_path) else: arcpy.StageService_server(sd_draft.file_path, sd_path)
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 create_service(temp_folder, map_document, portal_url, username, password, 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 portal_url: the ArcGIS Online or Portal for ArcGIS URL :param username: username for ArcGIS Online :param password: password for ArcGIS Online :param service_name: the name of the service to be created :param folder_name: the name of the folder where the service is created (optional) """ # 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, 'MY_HOSTED_SERVICES', folder_name=folder_name, copy_data_to_server=True, summary=map_document.description, tags=map_document.tags) feature_draft_file = update_sddraft(draft_file) # Analyze the draft file for any errors before staging. status_writer.send_status(_('Analyzing the map sd draft...')) analysis = arcpy.mapping.AnalyzeForSD(feature_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(feature_draft_file, stage_file) else: # Analyze the draft file for any errors before staging. 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) # If the sddraft analysis contained errors, display them and quit. else: errors = analysis['errors'] raise task_utils.AnalyzeServiceException(errors) # Upload/publish the service. status_writer.send_status(_('Publishing the map service to: {0}...').format(portal_url)) agol_handler = AGOLHandler(portal_url, username, password, service_name) map_service_url = agol_handler.publish(stage_file, map_document.description, map_document.tags) status_writer.send_status(_('Successfully created: {0}').format(map_service_url))
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 __stage_service_server(self, sddraft, service_name): """ the staging .sd file of service defination contains the all informations of GIS services this tool is the .sddraft file transfer to the .sd file :param sddraft: the .sddraft file of map services origin private create_map_sddraft method :param service_name: the service name :return: the .sd file of service such as: sddraft = "D:\Py_file\config\ty_region.sd" service_name = "ty_region" """ sd_file = os.path.abspath( os.path.join(_SERVICE_FOLDER, service_name + ".sd")) if os.path.exists(sd_file): try: os.unlink(sd_file) except Exception as e: emsg = "__stage_service_server sd file is exist and delete error" raise Exception(emsg) if not os.path.exists(sddraft): emsg = "__stage_service_server sddraft is exist" raise Exception(emsg) try: arcpy.StageService_server(sddraft, sd_file) except Exception as e: emsg = "__stage_service_server is error: %s" % e.message raise Exception(emsg) else: return sd_file
def main(): """Create and upload service definition""" mxd = os.path.join(WORKSPACE, PROTOCOL + ".mxd") map_doc = arcpy.mapping.MapDocument(mxd) # connectionfile = 'GIS Servers/ArcGIS on MyServer_6080 (publisher).ags' sddraft = os.path.join(WORKSPACE, PROTOCOL + ".sddraft") sd_file = os.path.join(WORKSPACE, PROTOCOL + ".sd") summary = "Survey Protocol " + PROTOCOL tags = "Survey, Protocol, Park Observer, " + PROTOCOL # create service definition draft analysis = arcpy.mapping.CreateMapSDDraft( map_doc, sddraft, PROTOCOL, "ARCGIS_SERVER", None, False, "ParkObserver", summary, tags, ) # stage and upload the service if the sddraft analysis did not contain errors if analysis["errors"] == {}: # Execute StageService arcpy.StageService_server(sddraft, sd_file) # Execute UploadServiceDefinition # arcpy.UploadServiceDefinition_server(sd_file, connectionfile) else: # if the sddraft analysis contained errors, display them print(analysis["errors"])
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 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 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 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 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 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 publish_to_agol(self, mxd_path, service_name, tags="None", description="None"): """ publishes a service to AGOL """ mxd = mapping.MapDocument(mxd_path) sddraftFolder = env.scratchFolder + os.sep + "draft" sdFolder = env.scratchFolder + os.sep + "sd" sddraft = sddraftFolder + os.sep + service_name + ".sddraft" sd = sdFolder + os.sep + "%s.sd" % service_name mxd = self._prep_mxd(mxd) if os.path.isdir(sddraftFolder) == False: os.makedirs(sddraftFolder) else: shutil.rmtree(sddraftFolder, ignore_errors=True) os.makedirs(sddraftFolder) if os.path.isfile(sddraft): os.remove(sddraft) analysis = mapping.CreateMapSDDraft(mxd, sddraft, service_name, "MY_HOSTED_SERVICES") sddraft = self._modify_sddraft(sddraft) analysis = mapping.AnalyzeForSD(sddraft) if os.path.isdir(sdFolder): shutil.rmtree(sdFolder, ignore_errors=True) os.makedirs(sdFolder) else: os.makedirs(sdFolder) if analysis['errors'] == {}: # Stage the service arcpy.StageService_server(sddraft, sd) print "Created {}".format(sd) else: # If the sddraft analysis contained errors, display them and quit. print analysis['errors'] sys.exit() # POST data to site content = self.getUserContent() #Title, item for item in content['items']: if item['title'] == service_name and \ item['item'] == os.path.basename(sd): print self.deleteItem(item['id']) elif item['title'] == service_name: print self.deleteItem(item['id']) self._agol_id = self._upload_sd_file(sd, service_name=service_name, tags=tags, description=description) if self._agol_id != "Error Uploadings": p_vals = self._publish(self._agol_id) for service in p_vals['services']: print self.enableSharing(service['serviceItemId']) del service del p_vals del mxd
def create_sd(table): # Create a new SDDraft and stage to SD sddraft = str(table) + '.sddraft' sd = str(table) + '.sd' arcpy.mp.CreateWebLayerSDDraft(prj_mp, sddraft, prj_mp.name, "MY_HOSTED_SERVICES", "FEATURE_ACCESS") arcpy.StageService_server(sddraft, sd) os.remove(sddraft)
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 update_feature_services(project_path, sd_fs_name): # Get handle to logger LOGGER = logging.getLogger(__name__) start = datetime.datetime.now() LOGGER.info( "\n\n--------------------------------------------------------------\n") LOGGER.info("update_feature_services started at {0}.".format(start)) # Local paths to create temporary content relPath = sys.path[0] sddraft = os.path.join(settings.repo, "temp\WebUpdate.sddraft") sd = os.path.join(settings.repo, "temp\WebUpdate.sd") # Create a new SDDraft and stage to SD LOGGER.info("Creating SD file") arcpy.env.overwriteOutput = True prj = arcpy.mp.ArcGISProject(project_path) mp = None map_list = prj.listMaps() for a_map in map_list: if a_map.name == sd_fs_name: mp = a_map break if mp is not None: arcpy.mp.CreateWebLayerSDDraft(mp, sddraft, sd_fs_name, "MY_HOSTED_SERVICES", "FEATURE_ACCESS", "", True, True) arcpy.StageService_server(sddraft, sd) LOGGER.debug("Connecting to {}".format(settings.AGO_PORTAL)) gis = GIS(settings.AGO_PORTAL, settings.AGO_USER, settings.AGO_PASSWORD) # Find the SD, update it, publish /w overwrite and set sharing and metadata LOGGER.debug("Search for original SD on portal...") sdItem = gis.content.search("{} AND owner:{}".format( sd_fs_name, settings.AGO_USER), item_type="Service Definition")[0] LOGGER.debug( "Found SD: {}, ID: {} n Uploading and overwriting…".format( sdItem.title, sdItem.id)) sdItem.update(data=sd) LOGGER.info("Overwriting existing feature service...") fs = sdItem.publish(overwrite=True) if shrOrg or shrEveryone or shrGroups: LOGGER.debug("Setting sharing options...") fs.share(org=shrOrg, everyone=shrEveryone, groups=shrGroups) LOGGER.info("Finished updating: {} – ID: {}".format(fs.title, fs.id)) else: LOGGER.info("Could not find map!") end = datetime.datetime.now() LOGGER.info("update_feature_services time finished: {0}.".format(end)) LOGGER.info("Time elapsed: {0}.".format(end - start))
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 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 publishLayer(map_name, layer_name, shr_everyone=True, prj_path= default_proj_path): portal = "http://www.arcgis.com" user = "******" password = "******" # Set sharing options shr_org = True shr_groups = "" # Local paths to create temporary content loc_path = r'O:\01 Land & Property Info\Updating Parcel & Property Layers' sd_draft = os.path.join(loc_path, layer_name + '.sddraft') sd = os.path.join(loc_path, layer_name + '.sd') # Create a new SDDraft and stage to SD print("Creating SD draft") arcpy.env.overwriteOutput = True prj = arcpy.mp.ArcGISProject(prj_path) mp = prj.listMaps(map_name)[0] arcpy.mp.CreateWebLayerSDDraft(mp, sd_draft, layer_name, 'MY_HOSTED_SERVICES', 'FEATURE_ACCESS', '', True, True) print("SD draft created") print("Creating SD") arcpy.StageService_server(sd_draft, sd) print("SD created") print("Connecting to {}".format(portal)) gis = GIS(portal, user, password) # Find the SD, update it, publish w/ overwrite and set sharing and metadata print("Search for original SD on portal…") # Check that the correct layer has been found match = 0 layer_number = 0 while match == 0: sd_item = gis.content.search("title:{} AND owner:{}".format(layer_name, user), item_type="Service Definition")[layer_number] found_layer = sd_item.title if found_layer == layer_name: match = 1 else: layer_number = layer_number + 1 print("Found SD: {}, ID: {} - Uploading and overwriting…".format(sd_item.title, sd_item.id)) # Update the service definition and overwrite the hosted layer sd_item.update(data=sd) print("Overwriting existing feature service…") fs = sd_item.publish(overwrite=True) if shr_org or shr_everyone or shr_groups: print("Setting sharing options…") fs.share(org=shr_org, everyone=shr_everyone, groups=shr_groups) print("Finished updating: {} – ID: {}".format(fs.title, fs.id))
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 _stage_service_sd(self,map_document): #tick temp_sddraft = TempFileName.generate_temporary_file_name("HostedMS.sddraft", split=False) path, file = TempFileName.generate_temporary_file_name("", split=True) service_definition = os.path.join(path, self._config.itemname + ".sd") if os.path.exists(service_definition): os.remove(service_definition) service = self._config.itemname arcpy.mapping.CreateMapSDDraft(map_document, temp_sddraft, service, 'MY_HOSTED_SERVICES', summary="FWP", tags='FWP') updated_draft = self._prep_sddraft(temp_sddraft) analysis = arcpy.mapping.AnalyzeForSD(updated_draft) arcpy.StageService_server(updated_draft, service_definition) self.log("Draft analysis:"+str(analysis)) self._cleanups += [service_definition, temp_sddraft, updated_draft] return service_definition
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 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 create_service_definition(sname, mpname, weblyrname): global outServiceDefinition outServiceDefinition = os.path.join(direct, "{}.sd".format(sname)) sddraft_output_filename = os.path.join(direct, "{}.sddraft".format(sname)) mplyrs = aprx.listMaps(mpname)[0] print("Service definition for {} created.".format(weblyrname)) # Create FeatureSharingDraft and set service properties sharing_draft = mplyrs.getWebLayerSharingDraft("HOSTING_SERVER", "FEATURE", weblyrname) sharing_draft.tags = mpname sharing_draft.allowExporting = True sharing_draft.portalFolder = 'HubContent' # Create Service Definition Draft file sharing_draft.exportToSDDraft(sddraft_output_filename) arcpy.StageService_server(sddraft_output_filename, outServiceDefinition)
def analyze_SD_draft(self, sd_draft, sd): _analysis = arcpy.mapping.AnalyzeForSD(sd_draft) logger.debug("Service Definition analysis") for key in ('messages', 'warnings', 'errors'): logger.debug('---- {0} ---'.format(key.upper())) _vars = _analysis[key] for ((message, code), layer_list) in _vars.iteritems(): logger.debug(" {0} (CODE {1})".format(message, code)) logger.debug(" applies to:") for layer in layer_list: logger.debug(layer.name) if _analysis['errors'] == {}: # Execute StageService arcpy.StageService_server(sd_draft, sd) # Execute UploadServiceDefinition else: # if the sddraft analysis contained errors, display them logger.debug(_analysis['errors']) return None
def stage_features(project, prj_map, service, draft, definition): prj = arcpy.mp.ArcGISProject(project) for m in prj.listMaps(): if m.name == prj_map: arcpy.mp.CreateWebLayerSDDraft( map_or_layers=m, out_sddraft=draft, service_name=service, server_type="HOSTING_SERVER", service_type="FEATURE_ACCESS", folder_name="", overwrite_existing_service=True, copy_data_to_server=True, enable_editing=True, ) arcpy.StageService_server( in_service_definition_draft=draft, out_service_definition=definition, )
def create_sd_files_from_map(self, map_name=None, pro_prjx=None, service_id=""): sds = {} try: the_prj = pro_prjx if pro_prjx else self._config.baseprjx aprx = arcpy.mp.ArcGISProject(the_prj) if map_name in [m.name for m in aprx.listMaps()]: service_object = getattr(self._config, map_name.lower()) service_name = service_object["servicename"] try: service_name = service_name % service_id except Exception as e: self.errorlog(str(e)) self.log("This is an expected error. ;-)") self.log(f"Service name:{service_name}") sddraft_file = TempFileName.generate_temporary_file_name( suffix=".sddraft") sdfile = TempFileName.generate_temporary_file_name( suffix=".sd") self.log(f"Creating:{sddraft_file},{sdfile}") m = aprx.listMaps(map_name)[0] arcpy.SignInToPortal(self._config.portal, self._config.user, self._config.password) #sharing_draft = m.getWebLayerSharingDraft("HOSTING_SERVER", "FEATURE", service_name) # change for JXT sharing_draft = m.getWebLayerSharingDraft( "FEDERATED_SERVER", "MAP_IMAGE", service_name) sharing_draft.federatedServerUrl = self._config.fed_server sharing_draft.copyDataToServer = True # change to Map Image server sharing_draft.summary = service_object["summary"] sharing_draft.tags = service_object["tags"] sharing_draft.description = service_object[ "description"] + f'<br/>Item updated on {datetime.datetime.now().strftime("%d %B %Y %H:%M:%S")} by automated script.' sharing_draft.credits = "" sharing_draft.exportToSDDraft(sddraft_file) arcpy.StageService_server(sddraft_file, sdfile) sds[service_name] = sdfile except Exception as e: self.errorlog(e) return sds
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)