1

I am currently attempting to create a script to download shapefiles from ArcGIS Online to my local drive before adding it to an aprx project and thereafter uploading it to a ArcGIS portal/enterprise.

All the above I have managed by downloading them as shapefiles -> convert .shp to feature class (in gdb) and then uploading it to the aprx.

However, when I run the script the symbology do not tag along. I have tried finding methods of downloading lyrx files from AGOL without any luck.

Do any of you know of a way to download the symbology from AGOL and merge them with the shapefile or feature class?

Here's the most relevant functions in the code I've used:

def agol_login(AGOL_url,AGOL_user,AGOL_pw):
    # gis_q = AGOL_url + ', ' + AGOL_user + ', ' + AGOL_pw
    print('AGOL login')
    gis = GIS(AGOL_url,AGOL_user,AGOL_pw)
    return gis

def createGDB():
    if folder_exist(path to gdb):
        gdb = 'testpath'
    else:
        gdb = arcpy.CreateFileGDB_management(path to folder, gdb)

def folder_exist(path):
    if arcpy.Exists(path):
        print(path + " Exist")
        return True
    else:
        print(path + " does not exist")
        return False

def downloadUserItem2(item, export_location, downloadFormat):
    # type: (object, object) -> object
    try:
        #Download
        name = item.title.replace(" ", "_")
        result = item.export(name.format(item.type), downloadFormat)
        result.download(export_location)
        result.delete()


        #Unzip
        zip_path = export_location + "\\" + name + ".zip"
        zip_file = ZipFile(zip_path)
        zip_file.extractall(export_location)

    except Exception as e:
        print(e)

def SHPtoGDB():
    # Set the workspace for ListFeatureClasses
    arcpy.env.workspace = "path to folder"
    # Use the ListFeatureClasses function to return a list of shapefiles.
    featureclasses = arcpy.ListFeatureClasses()
    # Copy shapefiles to a file geodatabase
    for fc in featureclasses:
        arcpy.CopyFeatures_management(
            fc, os.path.join("path to gdb",
                             os.path.splitext(fc)[0]))

def AddFCtoAPRX():
    arcpy.env.workspace = "path to gdb"
    datasets = arcpy.ListDatasets(feature_type='feature')
    datasets = [''] + datasets if datasets is not None else []
    rootPath_aprx = 'path to aprx folder'
    aprx = arcpy.mp.ArcGISProject(rootPath_aprx + 'TestWMS.aprx')
    aprxMap = aprx.listMaps("Map")[0]
    for ds in datasets:
        for fc in arcpy.ListFeatureClasses(feature_dataset=ds):
            path = os.path.join(arcpy.env.workspace, ds, fc)
            print ("List of feature classes:")
            print(path)
            try:
                test = aprxMap.addDataFromPath(path)
                aprxMap.addLayer(test)
                print("Feature Classes added to Arcgis Pro..")
            except:
                print("gah.")
    aprx.save()
    print("APRX path is:")
    print(aprx.filePath)

def UploadtoPortal():
    rootPath_aprx = 'C:\\Users\\ESSE\\Documents\\ArcGIS\\Projects\\TestWMS\\'
    aprx = arcpy.mp.ArcGISProject(rootPath_aprx + 'TestWMS.aprx')
    m = aprx.listMaps('Map')[0]
    arcpy.mp.CreateWebLayerSDDraft(m, rootPath_aprx + 'TestWMS.sddraft', 'Map', 'MY_HOSTED_SERVICES', 'FEATURE_ACCESS')
    arcpy.StageService_server(rootPath_aprx + 'TestWMS.sddraft', rootPath_aprx + 'TestWMS.sd')
    print("Uploading Service Definition to Portal...")
    arcpy.UploadServiceDefinition_server(rootPath_aprx + 'TestWMS.sd', 'My Hosted Services')
5
  • What is the downloadFormat being used in this chunk: result = item.export(name.format(item.type), downloadFormat)
    – KHibma
    Jun 21, 2019 at 12:01
  • Shapefile, then added to gdb afterwards.
    – Sineik
    Jun 21, 2019 at 12:03
  • I can't add an answer as this is on-hold. But in short, you wont get the symbology via any sort of Extract on a feature service.. None of those formats include symbology. You'd need to ingest the service layers themselves into your map (they'd retain symbology). Or the real long way would be to look at the JSON making up the symbology of the layers in a webmap, and somehow convert that into symbols inside ArcGIS Pro.
    – KHibma
    Jun 21, 2019 at 12:17
  • SHP do not contain any symbology and depending on the case the symbols might only exist in the web map or layer item and not that the service level and you would need to extract the JSON there. Jun 21, 2019 at 14:31
  • Is there a specific reason you want to download and convert then re-upload to Portal instead of adding the items directly to the portal via the 'Add Item > From the Web' utility or as @KHibma mentions just adding them to a map and sharing them as a service from there? Jun 21, 2019 at 15:37

1 Answer 1

0

Below is a workflow for getting the symbology from AGOL and applying to downloaded feature classes. Create a template APRX with two maps, one names Symbology, and one named Publishing. Add the Feature Layers from the AGOL Feature Service to the Symbology map, export each layer from the APRX as a .lyrx with the name the same as the layer. Export the Feature Layer to a File Geodatabase using the layer url. Add the exported feature classes to the Publishing map in the APRX and apply the symbology.

The below does not reorder layers as required or iterate through one at a time and publish separately but t wouldnt take too much to revamp to cater for additional requirements. Youlc could run a cleanup to delete .lyrx files after publishing and remove layers from Symbology and Publishing maps to be ready for the next run.

import arcpy
from arcgis import GIS

################################################################################

lyrfile_fldr = r"C:\Path\To\symbology\folder"

output_gdb = r"C:\Path\To\Temp.gdb"

arcpy.env.maintainAttachments = False
arcpy.env.overwriteOutput = True

################################################################################
## AGOL

agol = GIS("home")

fs_id = "FEATURE_SERVICE_ITEM_ID"

item = agol.content.get(fs_id)

################################################################################
## APRX Template that has two maps with 0 layers
## 1. Symbology
## 2. Publishing

aprx_path = r"\Path\To\Processing.aprx"

aprx = arcpy.mp.ArcGISProject(aprx_path)

symb_map = aprx.listMaps("Symbology")[0]
pub_map = aprx.listMaps("Publishing")[0]

################################################################################
## add each layer to an APRX, export the lyrx for symbology, export data to gdb

fc_list = []

## for each layer in the feature service
for lyr in item.layers:
    lyr_url = lyr.url
    lyr_name = lyr.properties.name

    ## export lyrx file for symbology
    lyr_added = symb_map.addDataFromPath(lyr_url)
    lyr_added.saveACopy("{0}\{1}.lyrx".format(lyrfile_fldr, lyr_name))

    ## fc is a result object
    fc = arcpy.FeatureClassToFeatureClass_conversion(lyr_url, output_gdb, lyr_name)

    ## append the fc path from result object to fc_list
    fc_list.append(fc[0])

################################################################################
## add fc to aprx and apply symbology

## for each fc
for fc in fc_list:
    ## add to the Publishing Map
    lyr_added = pub_map.addDataFromPath(fc)

    ## apply sumbology
    fc_name = fc.split("\\")[-1]
    sym_file = "{0}\\{1}.lyrx".format(lyrfile_fldr, fc_name)
    arcpy.ApplySymbologyFromLayer_management(lyr_added, sym_file, update_symbology="UPDATE")

aprx.save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.