Select to view content in your preferred language

script unable to locate AGO layer by title

289
3
3 weeks ago
KyleConboy
Occasional Contributor

Hello,

I don't really do any Python scripting but I found this script to backup a hosted feature layer on AGO to my computer.  I'm using the python window in ArcPro 3.53 and I'm getting Layer 'King George BMPs' not found.  When I run the script I have the right info for org URL, username, password, and backup directory in place.  Anyone have any ideas on why it can't find the layer title?

# coding: utf-8
from arcgis.gis import GIS
import os
import datetime

# --- Configuration ---
AGOL_ORG_URL = "https://place-name.maps.arcgis.com"
USERNAME = "username"
PASSWORD = "password" # Storing credentials in a script is less secure; consider alternative authentication methods for production environments
BACKUP_DIR = r"BMPBackup" # Local directory for backups
LAYER_TITLE = "King George BMPs" # Title of the layer to backup

# Ensure backup directory exists
if not os.path.exists(BACKUP_DIR):
os.makedirs(BACKUP_DIR)

# Authenticate to ArcGIS Online
gis = GIS(AGOL_ORG_URL, USERNAME, PASSWORD)

# Search for the hosted feature layer
# Note: You may need to refine the search query if the title isn't unique
search_result = gis.content.search(query=f"title:{LAYER_TITLE} AND type:Feature Layer", max_items=1)
if not search_result:
print(f"Layer '{LAYER_TITLE}' not found.")
exit()

item = search_result[0]
print(f"Found item: {item.title}")

# Export data to a File Geodatabase (FGDB) format
# This creates a new item in AGOL content, which will be deleted later
export_title = f"{item.title}_Backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"
export_item = item.export(export_title, "File Geodatabase", wait=True)

# Download the exported file
download_path = export_item.download(BACKUP_DIR)
print(f"Downloaded backup to: {download_path}")

# Delete the temporary export item from AGOL content
export_item.delete()
print("Temporary export item deleted from ArcGIS Online.")
print("Backup process complete.")
Layer 'King George BMPs' not found.

0 Kudos
3 Replies
Clubdebambos
MVP Regular Contributor

Hi @KyleConboy,

If you know which Feature Service you are backing up I would not use search() instead I would use get() and supply in the item id.

search_result = gis.content.get("FS_ITEM_ID")

 

You can get the Item id from the URL of the Feature Service page and paste it in.

Let me know how you get on.

All the best,

Glen

~ learn.finaldraftmapping.com
KyleConboy
Occasional Contributor

Hi Glen,

Thanks for the response.  i now get this error:

# coding: utf-8

# coding: utf-8

from arcgis.gis import GIS

import os

import datetime

 

# --- Configuration ---

AGOL_ORG_URL = "https://Org-name.maps.arcgis.com"

USERNAME = "Username"

PASSWORD = "Password" 

BACKUP_DIR = r"directory" # Local directory for backups

LAYER_TITLE = "LayerTitle" # Title of the layer to backup

 

# Ensure backup directory exists

if not os.path.exists(BACKUP_DIR):

    os.makedirs(BACKUP_DIR)

 

# Authenticate to ArcGIS Online

gis = GIS(AGOL_ORG_URL, USERNAME, PASSWORD)

 

# Search for the hosted feature layer

# Note: You may need to refine the search query if the title isn't unique

search_result = gis.content.get("6b945b44045f4012853adbda211e81f8")

if not search_result:

    print(f"Layer '{LAYER_TITLE}' not found.")

    exit()

 

item = search_result[0]

print(f"Found item: {item.title}")

 

# Export data to a File Geodatabase (FGDB) format

# This creates a new item in AGOL content, which will be deleted later

export_title = f"{item.title}_Backup_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}"

export_item = item.export(export_title, "File Geodatabase", wait=True)

 

# Download the exported file

download_path = export_item.download(BACKUP_DIR)

print(f"Downloaded backup to: {download_path}")

 

# Delete the temporary export item from AGOL content

export_item.delete()

print("Temporary export item deleted from ArcGIS Online.")

print("Backup process complete.")

Traceback (most recent call last):

  File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\arcgis\gis\__init__.py", line 14050, in __getitem__

    return dict.__getitem__(self, k)

           ^^^^^^^^^^^^^^^^^^^^^^^^^

KeyError: 0

 

During handling of the above exception, another exception occurred:

 

Traceback (most recent call last):

  File "<string>", line 28, in <module>

  File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\Lib\site-packages\arcgis\gis\__init__.py", line 14052, in __getitem__

    if not self._hydrated and not k.startswith("_"):

                                  ^^^^^^^^^^^^

AttributeError: 'int' object has no attribute 'startswith'

0 Kudos
Clubdebambos
MVP Regular Contributor

Hi @KyleConboy,

The get() method does not return a list like search() does, so remove the [0] for item = search_result[0], you can just set the item variable as per below...

item = gis.content.get("6b945b44045f4012853adbda211e81f8")

 

No need for... 

if not search_result:
    print(f"Layer '{LAYER_TITLE}' not found.")
    exit()

 

You could replace for something like...

if not item:
    print("Item not found") # this would only happen if the item id belonged to a different AGOL/Portal or was entered incorrectly

else:
    # continue with the workflow

 

All the best,

Glen

~ learn.finaldraftmapping.com
0 Kudos