I've been experimenting with the FeatureSharingDraft class. It works fine accessing map objects indiscriminately, and one at a time. However, I'm trying to access specific objects (layers) in an if statement. Then I want them to overwrite the corresponding feature services using the service_names list.
In my if statement I'm able to find the selected_layer and assign it. However, I'm looking for some help to plug it into the FeatureSharingDraft part of the code. And I also don't think my service_name variable is doing much outside the maps loop, as I'm not sure how to include it.
In a nutshell, I want to be able to iterate the service_names list and overwrite the service with the selected_layer from each of the maps in my Pro project.
#existing service names in my AGOL
service_names = ['Elementary Districts Vacc Rate Tot Pop','Elementary Districts Vacc Rate 12 to 18','Elementary Districts Vacc Rate 0 to 18',
'Elementary Districts Vacc Rate 11 to 14','Elementary Districts Vacc Rate 14 to 16','Elementary Districts Vacc Rate 16 to 18',
'Elementary Districts Vacc Rate 19 to 64','Elementary Districts Vacc Rate 65 Plus']
# Set output file names
outdir = r"C:/Users/jpilbeam"
for service_name in service_names:
sddraft_filename = service_name + ".sddraft"
sddraft_output_filename = os.path.join(outdir, sddraft_filename)
sd_filename = service_name + ".sd"
sd_output_filename = os.path.join(outdir, sd_filename)
'''For each map in the Pro project,
grab the selected_layer and overwrite the service from the service_name list'''
# Reference maps
maps = aprx.listMaps()
for m in maps:
for selected_layer in m.listLayers():
if selected_layer.name.endswith('Elementary'): #<--look for selected layer in map
print(f'layer: {selected_layer}')
#---------FeatureSharingDraft------------------
# Create FeatureSharingDraft and set overwrite property
server_type = "HOSTING_SERVER"
# returns a map class object based on service_type selected
sddraft = m.getWebLayerSharingDraft(server_type, "FEATURE", service_name) #<--map class function
sddraft.overwriteExistingService = True
# Create and save to service definition draft file
# returns location and name of sddraft
sddraft.exportToSDDraft(sddraft_output_filename)
# Convert to service definition (.sd) file. Staging compiles all necessary info needed to sucessfully publish
print("Start Staging")
arcpy.StageService_server(sddraft_output_filename, sd_output_filename)
# take .sd file, copy it onto server, extract required info and publish
print("Start Uploading")
arcpy.server.UploadServiceDefinition(sd_output_filename, server_type)
print("Finish Publishing")
I have tried putting selected_layer in the getWebLayerSharingDraft() function as a parameter, but it doesn't ultimately overwrite the feature service. Rather, it publishes a new one.
sddraft = prj.getWebLayerSharingDraft(server_type, "FEATURE", service_name, [selected_layer])
sddraft.overwriteExistingService = True