コード例 #1
0
ファイル: publisher.py プロジェクト: chadcooper/slap
    def publish_gp(self, config_entry, filename, sddraft):
        if "result" in config_entry:
            result = self.config_parser.get_full_path(config_entry["result"])
        else:
            raise Exception(
                "Result must be included in config for publishing a GP tool")

        self.message("Generating service definition draft for gp tool...")
        arcpy.CreateGPSDDraft(
            result=result,
            out_sddraft=sddraft,
            service_name=config_entry["serviceName"]
            if "serviceName" in config_entry else filename,
            server_type=config_entry["serverType"]
            if "serverType" in config_entry else 'ARCGIS_SERVER',
            connection_file_path=self.connection_file_path,
            copy_data_to_server=config_entry["copyDataToServer"]
            if "copyDataToServer" in config_entry else False,
            folder_name=config_entry["folderName"]
            if "folderName" in config_entry else None,
            summary=config_entry["summary"]
            if "summary" in config_entry else None,
            tags=config_entry["tags"] if "tags" in config_entry else None,
            executionType=config_entry["executionType"]
            if "executionType" in config_entry else 'Asynchronous',
            resultMapServer=False,
            showMessages="INFO",
            maximumRecords=5000,
            minInstances=2,
            maxInstances=3,
            maxUsageTime=100,
            maxWaitTime=10,
            maxIdleTime=180)
        return arcpy.mapping.AnalyzeForSD(sddraft)
コード例 #2
0
def convert_toolbox_to_service_draft(toolbox_path,
                                     sd_draft_path,
                                     get_result_fn,
                                     service_name,
                                     folder_name=None,
                                     summary=None):
    # import and run the package
    arcpy.ImportToolbox(toolbox_path)
    # optionally allow a list of results
    if not callable(get_result_fn):
        result = [fn() for fn in get_result_fn]
    else:
        result = get_result_fn()

    # create the sddraft
    analysis = arcpy.CreateGPSDDraft(result,
                                     sd_draft_path,
                                     service_name,
                                     server_type="ARCGIS_SERVER",
                                     copy_data_to_server=False,
                                     folder_name=folder_name,
                                     summary=summary)
    check_analysis(analysis)
    # and analyse it
    analysis = arcpy.mapping.AnalyzeForSD(sd_draft_path)
    check_analysis(analysis)

    return sd_draft_path
コード例 #3
0
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
コード例 #4
0
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
コード例 #5
0
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')
コード例 #6
0
    if arcpy.env.workspace not in [
            i[2] for i in arcpy.ListDataStoreItems(connPath, 'FOLDER')
    ]:
        # both the client and server paths are the same
        dsStatus = arcpy.AddDataStoreItem(connPath, "FOLDER", "CityData",
                                          arcpy.env.workspace,
                                          arcpy.env.workspace)
        print "Data store : " + str(dsStatus)

    # create service definition draft
    print "Creating sddraft file..."
    arcpy.CreateGPSDDraft(result,
                          sddraft,
                          serviceName,
                          server_type="ARCGIS_SERVER",
                          connection_file_path=connPath,
                          copy_data_to_server=False,
                          folder_name=None,
                          summary="Buffer",
                          tags="Buffer data")

    # analyze the service definition draft
    print "Analyzing..."
    analyzeMessages = arcpy.mapping.AnalyzeForSD(sddraft)

    # stage and upload the service if the sddraft analysis did not contain errors
    if analyzeMessages['errors'] == {}:
        # Execute StageService
        print "Creating sd file..."
        arcpy.StageService_server(sddraft, sd)
        # Execute UploadServiceDefinition
                           connection_name="HSRef",
                           server_path=config.uncpath,
                           client_path=ws)
    print("Add data store")
except:
    print("Adding data store error:", sys.exc_info()[0])

# Publish a gp service
try:
    # Create a service definition draft
    draft_file = os.path.join(sc, 'gpservice.sddraft')
    draft_file_return = arcpy.CreateGPSDDraft(
        result=history_item,
        out_sddraft=draft_file,
        service_name='hotspotgpservice2',
        server_type="ARCGIS_SERVER",
        connection_file_path=connectionFile,
        copy_data_to_server=False,
        showMessages="Info",
        constantValues=['hotspotscript.distancem'])
    print("Service Definition Draft is ready.")

    # Analyze the return from creating the service definition draft
    if (draft_file_return['errors']):
        print("error message = " + (draft_file_return['errors'] or 'None'))
    else:
        print("warning message = " + (draft_file_return['warnings'] or 'None'))

        # Stage the service
        definition_file = os.path.join(sc, 'gpservice1.sd')
        arcpy.StageService_server(draft_file, definition_file)
    distance_method = 'Manhattan'
    arcpy.ImportToolbox(intbx)
    result_item = arcpy.hotspotscript_hotspot(inputfc, inputRaster,
                                              distance_method)
    print("Tool runs successfully.")

except:
    print("Making layer or running tool error:", sys.exc_info()[0])

# Publish web tool
try:
    # Create a service definition draft
    draft_file = os.path.join(sc, 'webtools.sddraft')
    draft_file_return = arcpy.CreateGPSDDraft(
        result=result_item,
        out_sddraft=draft_file,
        service_name='hotspotwebtool1',
        server_type="MY_HOSTED_SERVICES",
        constantValues=['hotspotscript.distancem'])
    print("Service Definition Draft is ready.")

    # Analyze the return from creating the service definition draft
    if (draft_file_return['errors']):
        print(draft_file_return['errors'])
    else:
        print(draft_file_return['warnings'])

        # Stage the service
        definition_file = os.path.join(sc, 'webtools.sd')
        arcpy.StageService_server(draft_file, definition_file)
        print("Service staged.")
コード例 #9
0
# -*- coding: utf-8 -*-
__author__ = 'kikita'

import arcpy
import os

arcpy.env.workspace = r"\\192.168.220.162\TestData\My_data3DUIM_1.gdb"
OutFolder = r"\\192.168.220.162\TestData\MyProject1"
sddraftFile = os.path.join(OutFolder, "CopyFeature.sddraft")
sdFile = os.path.join(OutFolder, "CopyFeature.sd")

result = arcpy.CopyFeatures_management("NewBuilding2", "NewBuilding_Copy3")
print('Copy Feature Done !')

arcpy.CreateGPSDDraft(result, sddraftFile, "myGPservice")
print("GP Draft Done!")

arcpy.StageService_server(sddraftFile, sdFile)
print("GP SD Done!")

arcpy.UploadServiceDefinition_server(os.path.join(OutFolder, sdFile),
                                     'My Hosted Services')
print('Done!')
コード例 #10
0
def CreateSDFile(configFile):
    try:
        with open(configFile) as json_config:
            config = json.load(json_config)
    except Exception as e:
        arcpy.AddMessage("Failed to load config.")
        return

    try:
        toolbox = config["toolbox"]
        alias = config["alias"]
        toolName = config["toolName"]
        toolArgs = config["toolArgs"]
        sddraft = config["sdDraft"]
        sd = config["sd"]
        portalurl = config["portalURL"]
        portalusername = config["portalUsername"]
        portalpassword = config["portalPassword"]
        serverURL = config["serverURL"]
        serviceName = config["serviceName"]
        serverType = config["serverType"]
        connectionFilePath = config["connectionFilePath"]
        copyDataToServer = config["copyDataToServer"]
        folderName = config["folderName"]
        summary = config["summary"]
        tags = config["tags"]
        executionType = config["executionType"]
        resultMapServer = config["resultMapServer"]
        showMessages = config["showMessages"]
        maximumRecords = config["maximumRecords"]
        minInstances = config["minInstances"]
        maxInstances = config["maxInstances"]
        maxUsageTime = config["maxUsageTime"]
        maxWaitTime = config["maxWaitTime"]
        maxIdleTime = config["maxIdleTime"]
        constantValues = config["constantValues"]
    except KeyError as keyErr:
        arcpy.AddMessage(f"Config file missing value: {keyErr}")
        return
    except Exception as e:
        arcpy.AddMessage(f"Error occured in retreiving config values: {e}")
        return

    arcpy.AddMessage("Successfuly read all configuration values.")
    arcpy.ImportToolbox(toolbox, alias)
    arcpy.AddMessage(arcpy.GetMessages(0))
    customToolMethod = getattr(arcpy, f"{toolName}_{alias}")
    result = customToolMethod(*toolArgs)
    arcpy.AddMessage(arcpy.GetMessages(0))
    arcpy.SignInToPortal(portalurl, portalusername, portalpassword)
    arcpy.AddMessage(arcpy.GetMessages(0))

    analyzeMessages = arcpy.CreateGPSDDraft(
        result,
        sddraft,
        serviceName,
        server_type=serverType,
        connection_file_path=connectionFilePath,
        copy_data_to_server=copyDataToServer,
        folder_name=folderName,
        summary=summary,
        tags=tags,
        executionType=executionType,
        resultMapServer=resultMapServer,
        showMessages=showMessages,
        maximumRecords=maximumRecords,
        minInstances=minInstances,
        maxInstances=maxInstances,
        maxUsageTime=maxUsageTime,
        maxWaitTime=maxWaitTime,
        maxIdleTime=maxIdleTime,
        constantValues=constantValues)
    arcpy.AddMessage(arcpy.GetMessages(0))

    # Stage and upload the service if the sddraft analysis did not
    # contain errors
    if analyzeMessages['errors'] == {}:
        # Execute StageService
        arcpy.StageService_server(sddraft, sd)
        arcpy.AddMessage(arcpy.GetMessages(0))
        # Execute UploadServiceDefinition
        # Use URL to a federated server
        arcpy.UploadServiceDefinition_server(sd, serverURL)
        arcpy.AddMessage(arcpy.GetMessages(0))
    else:
        # If the sddraft analysis contained errors, display them
        print(analyzeMessages['errors'])
コード例 #11
0
       "WATERS_Services"
      ,".sddraft"
      ,None
      ,arcpy.env.scratchFolder
   );
   
   arcpy.CreateGPSDDraft(
       result=[navsrv_results,navdelin_results,updn_results,ptindx_results]
      ,out_sddraft=sddraft
      ,service_name=draft_service_name
      ,server_type="ARCGIS_SERVER"
      ,connection_file_path=ags_con
      ,copy_data_to_server=False
      ,folder_name=draft_folder_name
      ,summary=draft_summary
      ,tags=draft_tags
      ,executionType=draft_execution_type
      ,resultMapServer=False
      ,showMessages="INFO"
      ,maximumRecords=draft_max_records
      ,minInstances=draft_minInstances
      ,maxInstances=draft_maxInstances
      ,maxUsageTime=draft_maxUsageTime
      ,maxWaitTime=draft_maxWaitTime
      ,maxIdleTime=draft_maxIdleTime
   );
   
except arcpy.ExecuteError:
   print(arcpy.GetMessages(2));
   
#------------------------------------------------------------------------------
#- Step 90