<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Unknown error when appending feature layer in arcpy in Python Questions</title>
    <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256844#M66824</link>
    <description>&lt;P&gt;Wrap your processes up in try/ excepts and try to catch the error.&amp;nbsp; For example:&lt;/P&gt;&lt;LI-CODE lang="c"&gt;def AppendWebLayer(lyr, lID):
    try:
        svc = source.content.get(lID)
        serviceLayer = FeatureLayerCollection.fromitem(svc)
        flyr = serviceLayer.layers[0]
        updateTime = datetime.datetime.fromtimestamp(svc.modified / 1000)
        new_field = {"name": "Owner", "type": "esriFieldTypeString", "alias": "Owner", "length": 50, "nullable": True,
                     "editable": True, "visible": True, "domain": None}
        update_dict = {"fields": [new_field]}
        if updateTime != datetime.date.today():
            flyr.manager.add_to_definition(update_dict)
            flyr.manager.truncate()
            flyr.append(item_id=nID, upload_format='filegdb', source_table_name=lyr, upsert=True, skip_updates=False,
                        update_geometry=True, skip_inserts=False, upsert_matching_field='OBJECTID', return_messages=True)
            return lyr, 'yes'
        else:
            return lyr, 'no'
    except Exception as ex:
        arcpy.AddMessage(ex)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;This might sound odd, but for two of my scripts that involve the arcgis module, I have to run them in debug mode for them to work and they run without exceptions. When I run them as production, exceptions are thrown. Might try running it in debug mode.&lt;/P&gt;</description>
    <pubDate>Fri, 10 Feb 2023 02:13:08 GMT</pubDate>
    <dc:creator>Anonymous User</dc:creator>
    <dc:date>2023-02-10T02:13:08Z</dc:date>
    <item>
      <title>Unknown error when appending feature layer in arcpy</title>
      <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256769#M66823</link>
      <description>&lt;P&gt;After failing to manage this in Model Builder, I have been teaching myself python for almost a month so that I can automate updates to my organization's web layers. (There are about 50, so its a real drag to do this by hand whenever I make edits.)&lt;/P&gt;&lt;P&gt;I have code that I think should work, and PyCharm detects no errors, but when I run it, it gets right to the append part and throws Exception: Unknown Error.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;import arcpy
import os
import uuid
from arcgis.gis import GIS
from arcgis.features import FeatureLayerCollection
from zipfile import ZipFile
import datetime

# Overwrite Output
arcpy.env.overwriteOutput = True

# Create UUID variable for GDB
gdbId = str(uuid.uuid1())

print("Connecting to AGOL....")

sourceURL = 'https://someorg.maps.arcgis.com/'
sourceAdmin = "somebody"
sourcePassword = "apassword"
source = GIS(sourceURL, sourceAdmin, sourcePassword)
me = source.users.me
workspace = r'D:\Master_GIS_Files\Data\somedata\data.gdb'
fgdb = r'D:\Master_GIS_Files\Data\somedata\data/'

print("Creating temporary File Geodatabase")
gdb = arcpy.CreateFileGDB_management(arcpy.env.scratchFolder, gdbId)[0]
temp = gdb + ".zip"


def zipDir(dirPath, zipPath):
    zipf = ZipFile(zipPath, mode='w')
    tgdb = os.path.basename(dirPath)
    for root, _, files in os.walk(dirPath):
        for file in files:
            if 'lock' not in file:
                filePath = os.path.join(root, file)
                zipf.write(filePath, os.path.join(tgdb, file))
    zipf.close()


print("Zipping temp FGD")
zipDir(fgdb, temp)

print("Uploading File Geodatabase")
fgd_properties = {'title': gdbId, 'tags': 'temp file geodatabase', 'type': 'File Geodatabase'}
fgd_item = source.content.add(item_properties=fgd_properties, data=temp)
nID = fgd_item.id


stat = 'yes'

def StuffManager(q):
    Lyr = ''
    def FCIterator():
        with arcpy.EnvManager(workspace=workspace):
            gd = arcpy.Describe(workspace)
            fds = gd.children
            for fd in fds:
                fdd = fd.name
                fds = arcpy.Describe(fdd)
                fcs = fds.children
                for fcc in fcs:
                    fc = fcc.name
                    print(f'Loading feature class {fc}')
                    yield fc

    def AppendWebLayer(lyr, lID):
        svc = source.content.get(lID)
        serviceLayer = FeatureLayerCollection.fromitem(svc)
        flyr = serviceLayer.layers[0]
        updateTime = datetime.datetime.fromtimestamp(svc.modified / 1000)
        new_field = {"name": "Owner","type": "esriFieldTypeString","alias": "Owner","length": 50,"nullable": True,"editable": True,"visible": True,"domain": None}
        update_dict = {"fields": [new_field]}
        if updateTime != datetime.date.today():
            flyr.manager.add_to_definition(update_dict)
            flyr.manager.truncate()
            flyr.append(item_id=nID, upload_format='filegdb', source_table_name=lyr, upsert=True, skip_updates=False, update_geometry=True, skip_inserts=False, upsert_matching_field='OBJECTID', return_messages=True)
            return lyr, 'yes'
        else:
            return lyr, 'no'

    def GetWebLayer(layer):
        items = me.items(folder='Utilities')
        ftrlyrs = [i for i in items if i.title == layer]
        for f in ftrlyrs:
            if f.type == "Feature Service":
                flID = f.id
                title = f.title
                print(f'Found web layer {title} with ID {flID}.')
                return AppendWebLayer(layer, flID)


    while q == 'yes':
        ftr = FCIterator()
        values = GetWebLayer(next(ftr))
        Lyr = values[0]
        q = values[1]
        print(f"Layer {Lyr} updated!")
    else:
        print(f"Layer {Lyr} has already been updated.")
StuffManager(stat)
print('Deleting geodatabase from AGOL')
thing = source.content.get(nID)
thing.delete()
print('Script complete')&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Here is the error message:&lt;/P&gt;&lt;BLOCKQUOTE&gt;&lt;P&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\IPython\core\interactiveshell.py", line 3437, in run_code&lt;BR /&gt;exec(code_obj, self.user_global_ns, self.user_ns)&lt;BR /&gt;File "&amp;lt;ipython-input-2-7ddf5671b1b3&amp;gt;", line 1, in &amp;lt;module&amp;gt;&lt;BR /&gt;runfile('C:\\Users\\ThisUser\\PycharmProjects\\automateupdateweblayer\\Iterate and append', wdir='C:\\Users\\ThisUser\\PycharmProjects\\automateupdateweblayer')&lt;BR /&gt;File "C:\ThisUser\AppData\Local\JetBrains\Toolbox\apps\PyCharm-E\ch-0\222.4345.35\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile&lt;BR /&gt;pydev_imports.execfile(filename, global_vars, local_vars) # execute the script&lt;BR /&gt;File "C:\Users\ThisUser\AppData\Local\JetBrains\Toolbox\apps\PyCharm-E\ch-0\222.4345.35\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile&lt;BR /&gt;exec(compile(contents+"\n", file, 'exec'), glob, loc)&lt;BR /&gt;File "C:\Users\ThisUser\PycharmProjects\automateupdateweblayer\Iterate and append", line 101, in &amp;lt;module&amp;gt;&lt;BR /&gt;StuffManager(stat)&lt;BR /&gt;File "C:\Users\ThisUser\PycharmProjects\automateupdateweblayer\Iterate and append", line 95, in ShitManager&lt;BR /&gt;values = GetWebLayer(next(ftr))&lt;BR /&gt;File "C:\Users\ThisUser\PycharmProjects\automateupdateweblayer\Iterate and append", line 90, in GetWebLayer&lt;BR /&gt;return AppendWebLayer(layer, flID)&lt;BR /&gt;File "C:\Users\ThisUser\PycharmProjects\automateupdateweblayer\Iterate and append", line 77, in AppendWebLayer&lt;BR /&gt;flyr.append(item_id=nID, upload_format='filegdb', source_table_name=lyr, upsert=True, skip_updates=False, update_geometry=True, skip_inserts=False, upsert_matching_field='OBJECTID', return_messages=True)&lt;BR /&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\features\layer.py", line 2384, in append&lt;BR /&gt;return self._check_append_status(res, return_messages)&lt;BR /&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\features\layer.py", line 2393, in _check_append_status&lt;BR /&gt;sres = self._con.get(path=surl, params={"f": "json"})&lt;BR /&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\gis\_impl\_con\_connection.py", line 763, in get&lt;BR /&gt;return self._handle_response(&lt;BR /&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\gis\_impl\_con\_connection.py", line 900, in _handle_response&lt;BR /&gt;self._handle_json_error(data["error"], errorcode)&lt;BR /&gt;File "D:\Programs\ArcGISPro\ArcGISPro\bin\Python\envs\arcgispro-py3\lib\site-packages\arcgis\gis\_impl\_con\_connection.py", line 923, in _handle_json_error&lt;BR /&gt;raise Exception(errormessage)&lt;BR /&gt;Exception: Unknown Error&lt;BR /&gt;(Error Code: 500)&lt;/P&gt;&lt;/BLOCKQUOTE&gt;&lt;P&gt;If anybody could help me figure out what the heck is wrong with this stupid code, I'd be grateful.&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 09 Feb 2023 22:38:05 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256769#M66823</guid>
      <dc:creator>KitTompkins</dc:creator>
      <dc:date>2023-02-09T22:38:05Z</dc:date>
    </item>
    <item>
      <title>Re: Unknown error when appending feature layer in arcpy</title>
      <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256844#M66824</link>
      <description>&lt;P&gt;Wrap your processes up in try/ excepts and try to catch the error.&amp;nbsp; For example:&lt;/P&gt;&lt;LI-CODE lang="c"&gt;def AppendWebLayer(lyr, lID):
    try:
        svc = source.content.get(lID)
        serviceLayer = FeatureLayerCollection.fromitem(svc)
        flyr = serviceLayer.layers[0]
        updateTime = datetime.datetime.fromtimestamp(svc.modified / 1000)
        new_field = {"name": "Owner", "type": "esriFieldTypeString", "alias": "Owner", "length": 50, "nullable": True,
                     "editable": True, "visible": True, "domain": None}
        update_dict = {"fields": [new_field]}
        if updateTime != datetime.date.today():
            flyr.manager.add_to_definition(update_dict)
            flyr.manager.truncate()
            flyr.append(item_id=nID, upload_format='filegdb', source_table_name=lyr, upsert=True, skip_updates=False,
                        update_geometry=True, skip_inserts=False, upsert_matching_field='OBJECTID', return_messages=True)
            return lyr, 'yes'
        else:
            return lyr, 'no'
    except Exception as ex:
        arcpy.AddMessage(ex)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;This might sound odd, but for two of my scripts that involve the arcgis module, I have to run them in debug mode for them to work and they run without exceptions. When I run them as production, exceptions are thrown. Might try running it in debug mode.&lt;/P&gt;</description>
      <pubDate>Fri, 10 Feb 2023 02:13:08 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256844#M66824</guid>
      <dc:creator>Anonymous User</dc:creator>
      <dc:date>2023-02-10T02:13:08Z</dc:date>
    </item>
    <item>
      <title>Re: Unknown error when appending feature layer in arcpy</title>
      <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256895#M66825</link>
      <description>&lt;P&gt;Hello&amp;nbsp;&lt;a href="https://community.esri.com/t5/user/viewprofilepage/user-id/638741"&gt;@KitTompkins&lt;/a&gt;,&lt;/P&gt;&lt;P&gt;Looking at the traceback it&lt;EM&gt;&amp;nbsp;&lt;/EM&gt;seems some kind of issue with the connection when trying to request _&lt;EM&gt;check_append_status.&amp;nbsp;&lt;/EM&gt;Code 500 stands for Internal Server Error (quite broad error related to the target server, in this case your organization).&lt;/P&gt;&lt;P&gt;I'd suggest trying to append it manually and check if it crashes. If not, I'd execute the code line by line on the console (at least the &lt;EM&gt;AppendWebLayer&lt;/EM&gt; function). Sometimes following the workflow just helps to solve the problem.&amp;nbsp;Also check if the target service has the Append capability enabled if you are running the script with a nonadministrative user.&lt;/P&gt;&lt;P&gt;And like&amp;nbsp;@Anonymous User&amp;nbsp;said, it is strongly recommended to use try/except blocks to catch any error, although &lt;EM&gt;Exception&lt;/EM&gt; is too general class is enough when you don't know what kind of exception may arise.&lt;/P&gt;&lt;P&gt;Regards,&lt;/P&gt;</description>
      <pubDate>Fri, 10 Feb 2023 08:06:48 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1256895#M66825</guid>
      <dc:creator>Kepa</dc:creator>
      <dc:date>2023-02-10T08:06:48Z</dc:date>
    </item>
    <item>
      <title>Re: Unknown error when appending feature layer in arcpy</title>
      <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1257564#M66834</link>
      <description>&lt;P&gt;When I used the try: except and got messages it said the layer didn't exist, even though it found the web layer in the previous step. I'm wondering if using truncate changes the id or something.&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 13 Feb 2023 16:15:33 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1257564#M66834</guid>
      <dc:creator>KitTompkins</dc:creator>
      <dc:date>2023-02-13T16:15:33Z</dc:date>
    </item>
    <item>
      <title>Re: Unknown error when appending feature layer in arcpy</title>
      <link>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1257620#M66835</link>
      <description>&lt;P&gt;In line 77 you are passing the following paramater:&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="c"&gt;source_table_name=lyr&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;But &lt;EM&gt;lyr&amp;nbsp;&lt;/EM&gt;on the code is the layer you get from&amp;nbsp;GetWebLayer (layers from AGOL's folder). That parameter &lt;STRONG&gt;must be the name of the layer in the geodatabase&lt;/STRONG&gt; you just uploaded. Unless they're called completely equal it's going to output an error 500. I managed to reproduce your error passing an unexisting layer in that parameter:&lt;/P&gt;&lt;P&gt;&lt;span class="lia-inline-image-display-wrapper lia-image-align-left" image-alt="Snipaste_2023-02-13_18-43-02.png" style="width: 999px;"&gt;&lt;img src="https://community.esri.com/t5/image/serverpage/image-id/62710i40AC02A377CE7B33/image-size/large?v=v2&amp;amp;px=999" role="button" title="Snipaste_2023-02-13_18-43-02.png" alt="Snipaste_2023-02-13_18-43-02.png" /&gt;&lt;/span&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;Hope that helps!&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Mon, 13 Feb 2023 17:44:16 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/unknown-error-when-appending-feature-layer-in/m-p/1257620#M66835</guid>
      <dc:creator>Kepa</dc:creator>
      <dc:date>2023-02-13T17:44:16Z</dc:date>
    </item>
  </channel>
</rss>

