示例#1
0
def CreateTiles(inputService):
    scales = [
        12800000000, 6400000000, 3200000000, 1600000000, 800000000, 420263243
    ]
    numOfCachingServiceInstances = -1
    updateMode = "RECREATE_ALL_TILES"
    areaOfInterest = "#"
    waitForJobCompletion = "WAIT"
    updateExtents = "#"

    try:
        result = arcpy.ManageMapServerCacheTiles_server(
            inputService, scales, updateMode, numOfCachingServiceInstances,
            areaOfInterest, updateExtents, waitForJobCompletion)
        #print messages to a file
        while result.status < 4:
            time.sleep(0.2)
        resultValue = result.getMessages()
        print "completed " + str(resultValue)
        print "Created cache tiles for given schema successfully"
    except Exception, e:
        # If an error occurred, print line number and error message
        tb = sys.exc_info()[2]
        print "Failed at step 1 \n" "Line %i" % tb.tb_lineno
        print e.message
示例#2
0
def updateWMTScache(inputService, projectPath, flightMission):
    ## set the inputs to variables
    service = inputService
    projectPath = projectPath
    flightMission = flightMission

    ## split the project path string into an array to grab necessary info
    pathArr = projectPath.split('\\')

    ## handle for 2018 or 2019 naming convention differences
    if pathArr[3].find('2018') != -1:
        emd = 'EsriMosaicDataset'
    else:
        emd = 'esri-mosaic-dataset'

    ## get the aoi and extent
    if path.exists(projectPath):
        aoi = pathArr[len(pathArr) - 1]
        shp = os.path.join(projectPath, emd, flightMission,
                           flightMission + ".shp")
    else:
        print('projectPath does not exist. check your path.')
        sys.exit()

    ## create and format the extent and handle for invalid shp names
    if path.exists(shp):
        desc = arcpy.Describe(shp)
        extent = '{} {} {} {}'.format(desc.extent.XMin, desc.extent.YMin,
                                      desc.extent.XMax, desc.extent.YMax)
    else:
        print(
            'shapefile does not exist. check your flight mission directory and shapefile name.'
        )
        sys.exit()

    ## scales, mode, instances, and wait variables. these won't change.
    allScales = "591657527.591555;295828763.795777;147914381.897889;73957190.948944;36978595.474472;18489297.737236;9244648.868618;4622324.434309;2311162.217155;1155581.108577;577790.554289;288895.277144;144447.638572;72223.819286;36111.909643;18055.954822;9027.977411;4513.988705;2256.994353;1128.497176;564.248588;282.124294;141.062147;70.5310735"

    mode = "DELETE_TILES"
    instances = "3"
    wait = "WAIT"

    ## running the tool
    print(" -=-=- running the manage map server cache tiles tool -=-=- ")
    arcpy.ManageMapServerCacheTiles_server(
        input_service=service,
        scales=allScales,
        update_mode=mode,
        num_of_caching_service_instances=instances,
        area_of_interest=aoi,
        update_extent=extent,
        wait_for_job_completion=wait)
示例#3
0
def CreateTiles(inputService):
    # List of input variables for map service properties
    input_service = inputService
    # scales = [591657527.591555,295828763.795777,147914381.897889,73957190.948944]
    scales = [
        591657527.591555, 295828763.795777, 147914381.897889, 73957190.948944,
        36978595.474472, 18489297.737236, 9244648.868618, 4622324.434309,
        2311162.217155
    ]
    numOfCachingServiceInstances = 2
    updateMode = "RECREATE_ALL_TILES"
    areaOfInterest = ""
    waitForJobCompletion = "WAIT"
    updateExtents = ""

    currentTime = datetime.datetime.now()
    arg1 = currentTime.strftime("%H-%M")
    arg2 = currentTime.strftime("%Y-%m-%d %H:%M")
    file = r'C:/data/report_%s.txt' % arg1

    # print results of the script to a report
    report = open(file, 'w')

    try:
        starttime = time.clock()
        result = arcpy.ManageMapServerCacheTiles_server(
            input_service, scales, updateMode, numOfCachingServiceInstances,
            areaOfInterest, updateExtents, waitForJobCompletion)
        finishtime = time.clock()
        elapsedtime = finishtime - starttime

        #print messages to a file
        while result.status < 4:
            time.sleep(0.2)
        resultValue = result.getMessages()
        report.write("completed " + str(resultValue))

        print "Created cache tiles for given schema successfully for "
        + "serviceName" + " in " + str(elapsedtime) + " sec \n on " + arg2

    except Exception, e:
        # If an error occurred, print line number and error message
        tb = sys.exc_info()[2]
        report.write("Failed at step 1 \n" "Line %i" % tb.tb_lineno)
        report.write(e.message)
示例#4
0
def cache_test_extent():
    logger.logMsg('caching test extent')
    try:
        arcpy.ManageMapServerCacheTiles_server(service, all_scales,
                                               'RECREATE_ALL_TILES',
                                               num_instances, test_extent)
        emailer.sendEmail(
            'Cache Test Extent Complete ({})'.format(service_name),
            preview_url)
        if raw_input(
                'Recache test extent (T) or continue with full cache (F): '
        ) == 'T':
            cache_test_extent()
    except arcpy.ExecuteError:
        logger.logMsg('arcpy.ExecuteError')
        logger.logError()
        logger.logGPMsg()
        emailer.sendEmail(
            'Cache Test Extent Error ({}) - arcpy.ExecuteError'.format(
                service_name), logger.log)
        raise arcpy.ExecuteError
示例#5
0
def cache_extent(scales, aoi, name):
    today = datetime.datetime.today()
    if pauseAtNight and (today.hour > 22 or today.hour < 6):
        # don't cache at night, it slows down the update scripts
        if today.hour > 22:
            sleep_hours = 24 - today.hour + 6
        else:
            sleep_hours = 6 - today.hour
        logger.logMsg('sleeping for {} hours'.format(sleep_hours))
        time.sleep(sleep_hours * 60 * 60)
    logger.logMsg('caching {} at {}'.format(name, scales))

    try:
        arcpy.ManageMapServerCacheTiles_server(service, scales, update_mode,
                                               num_instances, aoi)
    except arcpy.ExecuteError:
        errors.append([scales, aoi, name])
        logger.logMsg('arcpy.ExecuteError')
        logger.logError()
        logger.logGPMsg()
        emailer.sendEmail(
            'Cache Update ({}) - arcpy.ExecuteError'.format(service_name),
            logger.log)
    def execute(self, parameters, messages):
        """The source code of the tool."""
        agspath = "C:/Users/Mr.HL/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (admin).ags"
        mxdpath = parameters[0].valueAsText
        new_mxd = arcpy.mapping.MapDocument(mxdpath)
        dirname = os.path.dirname(mxdpath)
        mxdname = os.path.basename(mxdpath)
        dotindex = mxdname.index('.')
        servicename = mxdname[0:dotindex]

        messages.addMessage('service_name {0}'.format(servicename))

        sddratf = os.path.abspath(servicename + ".sddraft")
        sd = os.path.abspath(servicename + ".sd")
        if os.path.exists(sd):
            os.remove(sd)

        arcpy.CreateImageSDDraft(new_mxd, sddratf, servicename,
                                 "ARCGIS_SERVER", agspath, False, None,
                                 "Ortho Images", "dddkk")
        analysis = arcpy.mapping.AnalyzeForSD(sddratf)

        # 打印分析结果
        messages.addMessage(
            "the following information wa returned during analysis of the MXD")
        for key in ('messages', 'warnings', 'errors'):
            messages.addMessage('---- {0} ----'.format(key.upper()))
            vars = analysis[key]
            for ((message, code), layerlist) in vars.iteritems():
                messages.addMessage(
                    ' message (CODE {0})    applies to:'.format(code))
                for layer in layerlist:
                    messages.addMessage(layer.name)

        if analysis['errors'] == {}:
            try:
                arcpy.StageService_server(sddratf, sd)
                arcpy.UploadServiceDefinition_server(sd, agspath)
                messages.addMessage('service successfully published')

                # 定义服务器缓存
                messages.addMessage("开始定义服务器缓存")
                # list of input variable for map service properties
                tiling_scheme_type = "NEW"
                scale_type = "CUSTOM"
                num_of_scales = 9
                scales = [7688, 7200, 6600, 6000, 5400, 4800, 4200, 3600, 3000]
                dot_per_inch = 96
                tile_origin = "-20037700 30198300"  # <X>-20037700</X> <Y>30198300</Y>
                tile_size = "256 x 256"
                cache_tile_format = "PNG8"
                tile_compression_quality = ""
                storage_format = "EXPLODED"
                predefined_tile_scheme = ""
                input_service = 'GIS Servers/arcgis on localhost_6080 (admin)/{0}.MapServer'.format(
                    servicename)
                cache_path = "D:/arcgisserver/directories-new/arcgiscache"

                try:
                    start_time = time.clock()
                    result = arcpy.CreateMapServerCache_server(
                        input_service, cache_path, tiling_scheme_type,
                        scale_type, num_of_scales, dot_per_inch, tile_size,
                        predefined_tile_scheme, tile_origin, scales,
                        cache_tile_format, tile_compression_quality,
                        storage_format)
                    # message to a file
                    while result.status < 4:
                        time.sleep(0.2)
                    # result_value = result.getMessage()
                    # messages.addMessage('completed {0}'.format(str(result_value)))
                except Exception, e:
                    tb = sys.exc_info()[2]
                    messages.addMessage('Failed to stop 1 \n Line {0}'.format(
                        tb.tb_lineno))
                    messages.addMessage(e.message)

                # 生成切片
                messages.addMessage("开始切片")
                scales = [7688, 7200, 6600, 6000, 5400, 4800, 4200, 3600, 3000]
                num_of_caching_service_instance = 2
                update_mode = "RECREATE_ALL_TILES"
                area_of_interest = ""
                wait_for_job_completion = "WAIT"
                update_extents = ""
                input_service = 'C:/Users/Mr.HL/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on localhost_6080 (' \
                                'admin)/{0}.MapServer'.format(servicename)

                try:
                    result = arcpy.ManageMapServerCacheTiles_server(
                        input_service, scales, update_mode,
                        num_of_caching_service_instance, area_of_interest,
                        update_extents, wait_for_job_completion)
                    while result.status < 4:
                        time.sleep(0.2)
                    # result_value = result.getMessage()
                    # messages.addMessage('completed {0}'.format(str(result_value)))
                    messages.addMessage(
                        'Created cache tiles for given schema successfully')
                except Exception, e:
                    tb = sys.exc_info()[2]
                    messages.addMessage('Failed at step 1 \n Line {0}'.format(
                        tb.tb_lineno))
                    messages.addMessage(e.message)
                messages.addMessage("Created Map Service Cache Tiles")
示例#7
0
def processJob(ProjectJob, project, ProjectUID, serverConnectionFile):
    cache_path = ContourConfig.CACHE_FOLDER

    projectID = ProjectJob.getProjectID(project)
    ProjectFolder = ProjectFolders.getProjectFolderFromDBRow(
        ProjectJob, project)
    derived_filegdb_path = ProjectFolder.derived.fgdb_path
    contour_folder = ProjectFolder.derived.contour_path
    #     PublishFolder = ProjectFolder.published.path
    #     contour_file_gdb_path = os.path.join(contour_folder, CONTOUR_GDB_NAME)
    #     contourMerged_file_gdb_path = os.path.join(PublishFolder, CONTOUR_NAME_WM)
    # @TODO: move all the derived contour stuff to a published location
    # P:\OK_SugarCreekElaine_2006\DERIVED\CONTOUR\SCRATCH\RESULTS\Results.mxd
    contourMxd_Name = "Results.mxd"  # ContourConfig.CONTOUR_MXD_NAME
    contourMxd_path = os.path.join(contour_folder, "C02Scratch", "RESULTS",
                                   contourMxd_Name)
    #     ContourBoundFC = os.path.join(contourMerged_file_gdb_path, ContourConfig.CONTOUR_BOUND_FC_WEBMERC)
    ContourBoundFC = A05_C_ConsolidateRasterInfo.getRasterBoundaryPath(
        derived_filegdb_path, DTM)

    temp = os.path.join(contour_folder, "temp")
    if os.path.exists(temp):
        shutil.rmtree(temp)
    os.mkdir(temp)

    # Get input parameters
    mxd = contourMxd_path  #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN  # arcpy.GetParameterAsText(0)
    ## 2018051 EI: Switched to using envelope here to create all cache tiles. Use AOI for import in C04
    #areaOfInterest = ContourBoundFC  # arcpy.GetParameterAsText(1)
    areaOfInterest = ""
    updateExtents = ContourBoundFC  #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN  # arcpy.GetParameterAsText(1)

    localServer = serverConnectionFile  # arcpy.GetParameterAsText(2)

    serviceName = "{}_{}".format(
        projectID,
        ContourConfig.CONTOUR_2FT_SERVICE_NAME)  # arcpy.GetParameterAsText(3)
    folder = ProjectJob.getState(project)  # arcpy.GetParameterAsText(4)

    # Using the temp folder to create service definition files
    sddraft = os.path.join(
        temp, "{}.sddraft".format(serviceName)
    )  #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN
    sd = os.path.join(
        temp, "{}.sd".format(serviceName)
    )  #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN

    tilingScheme = ContourConfig.TILING_SCHEME  #.replace('aiotxftw6na01data', 'aiotxftw6na01') #Added replace method 22 Mar 2019 BJN  # cwd + "\\NRCS_tilingScheme.xml" #Cache template file

    #-------------------------------------------------------------------------------
    #-------------------------------------------------------------------------------
    # The following paths and values can be modified if needed

    # Path to the local cache folder where project tiles will be created
    #     cacheFolder = cache_path  # r"C:\arcgisserver\directories\arcgiscache"
    #     cacheDir = os.path.join(cache_path, serviceName)
    #     if folder is not None and len(folder) > 0:
    #         cacheDir = os.path.join(cache_path, "{}_{}".format(folder, serviceName))
    #     if os.path.exists(cacheDir):
    #         now = datetime.datetime.now()
    #         updatedCacheDir = "{}_{}{}{}_{}{}{}".format(cacheDir,
    #                                                     ("0000{}".format(now.year))[-4:],
    #                                                     ("00{}".format(now.month))[-2:],
    #                                                     ("00{}".format(now.day))[-2:],
    #                                                     ("00{}".format(now.hour))[-2:],
    #                                                     ("00{}".format(now.minute))[-2:],
    #                                                     ("00{}".format(now.second))[-2:])
    #         arcpy.AddMessage("The existing cache folder will be moved to: {0}".format(updatedCacheDir))
    #         shutil.move(cacheDir, updatedCacheDir)

    # Other map service properties
    cachingInstances = ContourConfig.CACHE_INSTANCES  # This should be increased based on server resources
    #-------------------------------------------------------------------------------
    #-------------------------------------------------------------------------------
    Utility.printArguments([
        "mxd", "areaOfInterest", "updateExtents", "serviceName", "folder",
        "sddraft", "sd", "tilingScheme", "cache_path"
    ], [
        mxd, areaOfInterest, updateExtents, serviceName, folder, sddraft, sd,
        tilingScheme, cache_path
    ], "C03 CreateContourCache")
    # List of scales to create tiles at. If additional scales are needed, the tiling
    # scheme file needs to be updated as well as this list
    scales = ContourConfig.CONTOUR_SCALES_STRING

    # Other map service properties that should not be modified
    updateMode = "RECREATE_ALL_TILES"  # @TODO: Can we change this to recreate missing?
    waitForJobCompletion = "WAIT"  # @TODO: What if we don't wait??
    cache_dir_path = os.path.join(cache_path,
                                  "{}_{}".format(folder, serviceName))
    if os.path.exists(cache_dir_path):
        arcpy.AddMessage(
            "Cache directory already exists, only recreating empty tiles: {0}".
            format(cache_dir_path))
        updateMode = "RECREATE_EMPTY_TILES"
        waitForJobCompletion = "DO_NOT_WAIT"

    # Construct path for local cached service
    inputService = os.path.join(localServer, folder,
                                serviceName + ".MapServer")
    if localServer.endswith(".ags"):
        inputService = os.path.join(localServer[:-4], folder,
                                    serviceName + ".MapServer")
    arcpy.AddMessage(
        "Location of new service will be: {0}".format(inputService))

    # Create a MapDocument object from the input MXD
    mapDoc = arcpy.mapping.MapDocument(mxd)

    # Create the SDDraft file for the local cached service
    arcpy.AddMessage("Creating draft service definition: {0}".format(sddraft))
    arcpy.mapping.CreateMapSDDraft(mapDoc,
                                   sddraft,
                                   serviceName,
                                   "ARCGIS_SERVER",
                                   localServer,
                                   folder_name=folder)

    #     # Parse the SDDraft file in order to modify service properties before publishing
    #     doc = DOM.parse(sddraft)
    #     # Set the antialiasing mode to 'Fast'
    #     newAntialiasingMode = "Fast"
    #     keys = doc.getElementsByTagName('Key')
    #     for key in keys:
    #         if key.hasChildNodes():
    #             if key.firstChild.data == 'antialiasingMode':
    #                 # Modify the antialiasing mode
    #                 arcpy.AddMessage("Updating anti-aliasing to: {}".format(newAntialiasingMode))
    #                 key.nextSibling.firstChild.data = newAntialiasingMode
    #
    #     # Save a new SDDraft file
    outsddraft = os.path.join(temp + "\\" + serviceName + "_aa.sddraft")
    #     f = open(outsddraft, 'w')
    #     doc.writexml(f)
    #     f.close()
    updateSDDraft(sddraft, outsddraft)

    # Analyze the SDDraft file
    arcpy.AddMessage(
        "Analyzing draft service definition: {}".format(outsddraft))
    analysis = arcpy.mapping.AnalyzeForSD(outsddraft)

    # Check for analyzer errors
    if analysis['errors'] == {}:

        RunUtil.runTool(r'ngce\pmdm\c\C03_B_StageSD.py',
                        [outsddraft, sd, localServer],
                        bit32=True,
                        log_path=ProjectFolder.derived.path)


# #        arcpy.AddMessage("Staging service definition {}".format(sd))
# #        arcpy.StageService_server(outsddraft, sd)
# #        arcpy.AddMessage("Uploading service definition {} to server {}".format(sd, localServer))
# #        arcpy.UploadServiceDefinition_server(sd, localServer)
# #        arcpy.AddMessage("Service publishing completed")
    else:
        # If the SDDraft analysis contained errors, display them
        arcpy.AddError(
            "\nERROR\nErrors encountered during analysis of the MXD: " +
            str(analysis['errors']))
        os.remove(sddraft)
        os.remove(outsddraft)
        raise Exception(
            "\nERROR\nErrors encountered during analysis of the MXD: " +
            str(analysis['errors']))

    try:
        # Create the cache schema for the local project service
        arcpy.AddMessage("Creating cache schema for service {} in: {}".format(
            inputService, cache_path))
        arcpy.CreateMapServerCache_server(
            inputService,
            cache_path,
            "PREDEFINED",
            predefined_tiling_scheme=tilingScheme,
            scales=scales
        )  # , scales_type="STANDARD", num_of_scales=len(scales))
        arcpy.AddMessage("Cache schema created for local project service")
    except arcpy.ExecuteError:
        arcpy.AddWarning(arcpy.GetMessages(2))

    # Create the cache tiles for the local project service
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    arcpy.AddMessage("Cache creation started at: {0}".format(st))
    Utility.printArguments([
        "inputService", "scales", "updateMode", "cachingInstances",
        "areaOfInterest", "updateExtents", "waitForJobCompletion"
    ], [
        inputService, scales, updateMode, cachingInstances, areaOfInterest,
        updateExtents, waitForJobCompletion
    ], 'arcpy.ManageMapServerCasheTiles_server')  #Added 16 April 2016 BJN
    arcpy.ManageMapServerCacheTiles_server(inputService, scales, updateMode,
                                           cachingInstances, areaOfInterest,
                                           updateExtents, waitForJobCompletion)
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    arcpy.AddMessage("Cache creation completed at: {0}".format(st))

    # Clean up the Service Definition file from the temp folder
    os.remove(sd)
示例#8
0
    Syntax = StageService_server (in_service_definition_draft, out_service_definition, staging_version)
'''
arcpy.StageService_server(sddraftPath, sdPath)
print("Created SD")

'''  Finally, the Service Definition file can be uploaded and published as a GIS service to a specified online organization using the Upload Service Definition tool.
    This step takes the Service Definition file, copies it onto the server, extracts required information, and publishes the GIS resource.
    Syntax = UploadServiceDefinition_server (in_sd_file, in_server, {in_service_name}, {in_cluster}, {in_folder_type},
                                                                        {in_folder}, {in_startupType}, {in_override}, {in_my_contents}, {in_public}, {in_organization}, {in_groups})
'''
arcpy.UploadServiceDefinition_server(sdPath, 'My Hosted Services', in_override = "OVERRIDE_DEFINITION", in_public = "PUBLIC", in_organization = "SHARE_ORGANIZATION")
print("Uploaded and Shared SD")

# Creates and updates tiles in an existing web tile layer cache. 
input_service = r'https://tiles.arcgis.com/tiles/<orgID>/arcgis/rest/services/' + serviceName + r'/MapServer'
arcpy.ManageMapServerCacheTiles_server(input_service, [295828763.79577702], "RECREATE_ALL_TILES")
print("Created Tiles")

''' Getting the token
'''
token_url = 'https://www.arcgis.com/sharing/generateToken'
referer = "http://services.arcgis.com"
query_dict1 = {  'username':   username,
                 'password':   password,
                 'expiration': str(1440),
                 'client':     'referer',
                 'referer': referer}
query_string = urlencode(query_dict1)
tokenStr = json.loads(urlopen(token_url + "?f=json", str.encode(query_string)).read().decode('utf-8'))['token']

'''  Validation - Save the tile image to local disk
示例#9
0
areaOfInterest = ""
waitForJobCompletion = "DO_NOT_WAIT"  # use "WAIT" if full report wanted (script runs until job finishes)
updateExtents = ""

currentTime = datetime.datetime.now()
arg1 = currentTime.strftime("%H-%M")
arg2 = currentTime.strftime("%Y-%m-%d %H:%M")
file = env.workspace + '/report_%s.txt' % arg1

# print results of the script to a report
report = open(file, 'w')

try:
    starttime = time.clock()
    result = arcpy.ManageMapServerCacheTiles_server(
        inputService, scales, updateMode, numOfCachingServiceInstances,
        areaOfInterest, updateExtents, waitForJobCompletion)
    finishtime = time.clock()
    elapsedtime = finishtime - starttime

    print "Started recreating cache tiles..."
    #print messages to a file
    while result.status < 4:
        time.sleep(0.2)
    resultValue = result.getMessages()
    report.write("completed " + str(resultValue))

    print "Created cache tiles for given schema successfully for "
    serviceName + " in " + str(elapsedtime) + " sec \n on " + arg2

except Exception, e:
示例#10
0
                                     'My Hosted Services',
                                     in_public="PUBLIC",
                                     in_organization="SHARE_ORGANIZATION")
''' Creates and updates tiles in an existing map or image service cache. This tool is used to create new tiles, replace missing tiles, overwrite outdated tiles, and delete tiles.
    Syntax  = ManageMapServerCacheTiles_server (input_service, scales, update_mode, {num_of_caching_service_instances},
                                                                                 {area_of_interest}, {update_extent}, {wait_for_job_completion})
'''
starttime = time.clock()
input_service = r'https://tiles.arcgis.com/tiles/EguFTd9xPXEoDtC7/arcgis/rest/services/' + serviceName + r'/MapServer'
scales = [73957191, 36978595]
updateMode = "RECREATE_ALL_TILES"  # param has to be a member of RECREATE_ALL_TILES | DELETE_TILES
numOfCachingServiceInstances = 2
#
# the cache generation process is being timed
#
arcpy.ManageMapServerCacheTiles_server(input_service, scales, updateMode,
                                       numOfCachingServiceInstances)
#
finishtime = time.clock()
elapsedtime = finishtime - starttime
print("Created tiles in " + str(elapsedtime) + " sec(s)")
''' Getting the token
'''
token_url = 'https://www.arcgis.com/sharing/generateToken'
referer = "http://services.arcgis.com"
cred_detail = []
with open("secure/AGO_pass.txt") as f:
    for line in f:
        cred_detail.append(line.splitlines())
query_dict1 = {
    'username': cred_detail[0][0],
    'password': cred_detail[1][0],
示例#11
0
'''
arcpy.StageService_server(sddraftPath, sdPath)
'''  Finally, the Service Definition file can be uploaded and published as a GIS service to a specified online organization using the Upload Service Definition tool.
    This step takes the Service Definition file, copies it onto the server, extracts required information, and publishes the GIS resource.
    Syntax = UploadServiceDefinition_server (in_sd_file, in_server, {in_service_name}, {in_cluster}, {in_folder_type},
                                                                        {in_folder}, {in_startupType}, {in_override}, {in_my_contents}, {in_public}, {in_organization}, {in_groups})
'''
arcpy.UploadServiceDefinition_server(sdPath,
                                     'My Hosted Services',
                                     in_public="PUBLIC",
                                     in_organization="SHARE_ORGANIZATION")

# Creates and updates tiles in an existing web tile layer cache.
input_service = r'https://tiles.arcgis.com/tiles/<Your Org Id>/arcgis/rest/services/' + serviceName + r'/MapServer'
arcpy.ManageMapServerCacheTiles_server(input_service,
                                       [73957191, 36978595, 18489298],
                                       "RECREATE_ALL_TILES")
''' Getting the token
'''
token_url = 'https://www.arcgis.com/sharing/generateToken'
referer = "http://services.arcgis.com"
query_dict1 = {
    'username': username,
    'password': password,
    'expiration': str(1440),
    'client': 'referer',
    'referer': referer
}
query_string = urlencode(query_dict1)
tokenStr = json.loads(
    urlopen(token_url + "?f=json",
示例#12
0
    s.sendmail(sender, recipients, msg.as_string())
    s.quit()

#print results of the script to a report
report = open(reportfile,'w')

try:
    #Start the main timer
    startTime = time.time()

    #Create the _alllayers folder in the c drive for arcServer to generate the new cache into
    os.makedirs(stagingServerLevelFoldersLocation)

    #Run the higher level cache layers at the full extent of all SDE data (time this process)
    startFirstCache = time.time()
    arcpy.ManageMapServerCacheTiles_server(inputService, firstCacheScales, "RECREATE_ALL_TILES", "2", "", firstAOI, "WAIT")
    finishFirstCache = time.time()

    ##Uncomment the lines below to run the ManageMapServerCacheTiles_server a second time if you want to run certain scale levels at a different extent
##    startSecondCache = time.time()
##    arcpy.ManageMapServerCacheTiles_server(inputService, secondCacheScales, "RECREATE_ALL_TILES", "2", "", secondAOI, "WAIT")
##    finishSecondCache = time.time()

    #create a reference to a temporary _alllayers directory then rename the populated _alllayers to _alllayers_old
    temporaryStagingFolderRename = "C:\\arcgisserver\\directories\\arcgiscache\\maps_parcel_road_labels\\Layers\\_alllayers_temp"
    os.rename(stagingServerLevelFoldersLocation, stagingServerLevelFoldersLocation + "_temp")

    #Use shutil.rmtree to remove the _alllayers_old folder on the destination server
    shutil.rmtree(productionServerLayersFoldersLocation + "\\_alllayers_old")

    #Move the renamed and current cache folder (_alllayers_temp) over to the production server
'''
Created on 29. jan. 2014

@author: ermias
'''

import arcpy, time

serviceConn = "C:/Users/ermias/AppData/Roaming/ESRI/Desktop10.2/ArcCatalog/arcgis on willem3 (admin)"
serviceFolder = "Basisdata_Intern"
serviceName = "NP_Nordomraadene_WMTS_25833"
serviceType = "MapServer"
service = serviceConn + "/" + serviceFolder + "/" + serviceName + "." + serviceType
scales = "10240000;5120000;2560000;1280000;640000;320000;160000;80000;40000;20000;10000;5000;2500;1250;625"
arcpy.ManageMapServerCacheScales_server(service, scales)
result = arcpy.ManageMapServerCacheTiles_server(service, scales,
                                                "RECREATE_EMPTY_TILES", "3",
                                                "", "", "DO_NOT_WAIT")
while result.status < 4:
    print result.status, result.getMessages()
    time.sleep(0.2)
示例#14
0
def mainFunction(
    mapService, updateMode, tileScheme
):  # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
    try:
        # Log start
        if logInfo == "true":
            loggingFunction(logFile, "start", "")

        # --------------------------------------- Start of code --------------------------------------- #

        # If new cache
        if updateMode == "New":
            # If tile scheme file provided
            if (len(str(tileScheme)) > 0):
                arcpy.AddMessage("Creating new cache...")
                # Create cache folders
                arcpy.CreateMapServerCache_server(mapService, tileScheme,
                                                  "PREDEFINED", "", "", "", "",
                                                  "", "0 0", "", "", "0",
                                                  "COMPACT")
                # Start caching process
                arcpy.ManageMapServerCacheTiles_server(mapService, "",
                                                       "RECREATE_ALL_TILES",
                                                       "", "", "", "WAIT")
            else:
                arcpy.AddError(
                    "Please provide a tiling scheme file for the cache...")

        # If existing cache to create all tiles
        if updateMode == "Existing - Recreate All Tiles":
            # Rebuild the map cache
            arcpy.AddMessage("Rebuilding cache...")
            # Start caching process
            arcpy.ManageMapServerCacheTiles_server(mapService, "",
                                                   "RECREATE_ALL_TILES", "",
                                                   "", "", "WAIT")

        # If existing cache to create empty tiles
        if updateMode == "Existing - Recreate Empty Tiles":
            # Rebuild the map cache
            arcpy.AddMessage("Rebuilding cache...")
            # Start caching process
            arcpy.ManageMapServerCacheTiles_server(mapService, "",
                                                   "RECREATE_EMPTY_TILES", "",
                                                   "", "", "WAIT")

        # --------------------------------------- End of code --------------------------------------- #

        # If called from gp tool return the arcpy parameter
        if __name__ == '__main__':
            # Return the output if there is any
            if output:
                arcpy.SetParameterAsText(1, output)
        # Otherwise return the result
        else:
            # Return the output if there is any
            if output:
                return output
        # Log start
        if logInfo == "true":
            loggingFunction(logFile, "end", "")
        pass
    # If arcpy error
    except arcpy.ExecuteError:
        # Show the message
        arcpy.AddError(arcpy.GetMessages(2))
        # Log error
        if logInfo == "true":
            loggingFunction(logFile, "error", arcpy.GetMessages(2))
    # If python error
    except Exception as e:
        # Show the message
        arcpy.AddError(e.args[0])
        # Log error
        if logInfo == "true":
            loggingFunction(logFile, "error", e.args[0])