It's a bit long, and I've been making changes up until the Append error to try and fix it so Line 166 down is untested. Let me know if anything jumps out at you! I'm still relatively new to arcpy.
# Import packages
print("Loading packages...")
import os, sys, traceback, datetime, arcpy, shutil
from arcgis.gis import GIS, Layer
from arcgis.features import FeatureLayer
print("Packages loaded.")
# Global Variables
itemid = r'73a9b37fcfb048c3b524217dd5dda916' #tell script to update Layer 'Previous Designs'
dwnpath = r'C:/Users/mattl/Desktop/Test_Folder/AGO_Upload/'
gdb = r"C:/Users/mattl/Desktop/Test_Folder/Scratch.gdb"
dir_path = r'C:/Users/mattl/Desktop/Test_Folder/CAD_to_ArcOnline/'
def make_archive(source, destination):
base = os.path.basename(destination)
name = base.split('.')[0]
format = base.split('.')[1]
archive_from = os.path.dirname(source)
archive_to = os.path.basename(source.strip(os.sep))
print(source, destination, archive_from, archive_to)
shutil.make_archive(name, format, archive_from, archive_to)
shutil.move('%s.%s'%(name,format), destination)
# Check to see if connected to Network Drive
print('Connecting to network...')
if os.path.exists('W:/'):
print('Connected.')
pass
else:
print('Could not connect to network drive W:/')
print('Exiting script...')
raise SystemExit()
# Log into ArcGIS Online
print('Logging into ArcGIS Online...')
user = 'nunya'
password = 'biznis'
try:
gis = GIS('url', user, password) #not specifying password will ask for user input
un = gis.properties.user.username
print('Logged in as: {}'.format(un))
except Exception as error:
print(error)
print('Login Failed')
print('Exiting script...')
raise SystemExit()
# Gather CAD .dwg's to Process
print('Finding CAD drawings...')
ext = '.dwg'
dwg_list = []
# Tell Arc where to look for files
arcpy.env.workspace = dir_path
# Put files in list
for file in os.listdir(dir_path):
file.replace(" ", "")
if file.endswith(ext):
counter = file.count('_') # Perform check for two underscores
if counter == 2:
dwg_list.append(file) # Add to list of files
else:
continue
else:
continue
print('Drawings compiled.')
print(dwg_list)
# Perform Geoprocessing for each CAD Drawing
print('Processing...')
arcpy.env.workspace = gdb
# Clear gdb
fc_list = arcpy.ListFeatureClasses()
for fc in fc_list:
arcpy.Delete_management(fc)
# Create a feature layer to hold input feature classes
arcpy.CreateFeatureclass_management(gdb, 'CAD_FC', 'POLYLINE')
arcpy.MakeFeatureLayer_management(gdb + '/CAD_FC', 'cad_fc')
fd = { #field dictionary
'Date_Uploaded' : ['Date_Upld', 'DATE', 'Date Uploaded', None, datetime.date.today()],
'OBJECTID' : ['OBJECTID', 'SHORT', 'OID', None, None],
'GlobalID' : ['GlobalID', 'GUID', 'GlobalID', 38, None],
'Shape__Length' : ['Shp__Len', 'DOUBLE', 'Shape_Length', None, None],
'CreationDate' : ['CreateDate', 'DATE', 'CreationDate', 8, None],
'Creator' : ['Creator', 'TEXT', 'Creator', 128, None],
'EditDate' : ['EditDate', 'DATE', 'EditDate', 8, None],
'Editor' : ['Editor', 'TEXT', 'Editor', 128, None],
'Customer' : ['Customer', 'TEXT', 'Customer', 100, None],
'Job_Name' : ['Job_Name', 'TEXT', 'Job Name', 256, None],
'Design_Stage' : ['Dsgn_Stg', 'TEXT', 'Design Stage', 255, None],
'State' : ['State', 'TEXT', 'State', 2, None],
'GD_Folder' : ['GD_Folder', 'TEXT', 'GD Folder', 256, None]
}
arcpy.AddFields_management('cad_fc', [fd['CreationDate'], fd['Creator'], fd['EditDate'], fd['Editor'], fd['Customer'], fd['Job_Name'], fd['Design_Stage'], fd['State'], fd['GD_Folder']])
# Iterate through dwg list
arcpy.env.workspace = dir_path
arcpy.env.overwriteOutput = True
query = "Layer LIKE '%PROPOSED%' OR Layer = 'u_CENTURYLINK'"
for file in arcpy.ListDatasets(dwg_list):
print(file + '...')
f_name = os.path.splitext(file)[0]
full_path = dir_path + '/' + f_name.replace(" ", "")
arcpy.Delete_management(['file_pl', 'file_dissolved'])
#Parse name for customer, job name, design stage
new_fields = f_name.split("_")
customer = str(new_fields[0])
job = str(new_fields[1])
design = str(new_fields[2])
#Extract PROPOSED Polylines
arcpy.MakeFeatureLayer_management(file + "/Polyline", 'file_pl', query)
#merge (dissolve) polylines to one feature
arcpy.Dissolve_management('file_pl', 'file_dissolved', multi_part="MULTI_PART", unsplit_lines="DISSOLVE_LINES")
#delete fields from attribute table
arcpy.DeleteField_management('file_dissolved', ['Entity', 'Handle', 'Layer', 'LyrFrzn', 'LyrOn', 'Color', 'Linetype', 'Elevation', 'LineWt', 'RefName', 'DocUpdate', 'DocId', 'X3', 'X2', 'X1'], "DELETE_FIELDS")
#add and populate new fields
arcpy.AddFields_management('file_dissolved', [fd['CreationDate'], fd['Creator'], fd['EditDate'], fd['Editor'], fd['Customer'], fd['Job_Name'], fd['Design_Stage'], fd['State'], fd['GD_Folder']])
arcpy.CalculateField_management('file_dissolved', "Customer", "'"+customer+"'")
arcpy.CalculateField_management('file_dissolved', "Job_Name", "'"+job+"'")
arcpy.CalculateField_management('file_dissolved', "Dsgn_Stg", "'"+design+"'")
#add to the new layer
arcpy.Append_management('file_dissolved', 'cad_fc', "NO_TEST")
#clear variables and gdb
arcpy.Delete_management(['file_pl', 'file_dissolved'])
del full_path, new_fields, customer, job, design#, file_pl, file_dissolved, file_clean
print(file + " done.")
print('Processing complete.')
# Reset workspace to .gdb
arcpy.env.workspace = gdb
# Impart Spatial Reference/Coordinate system
arcpy.SpatialReference(4326) #NAD1983
#arcpy.FeatureClassToGeodatabase_conversion('cad_fc', gdb)
# Download hosted feature layer
print('Downloading online layer...')
dataitem = gis.content.get(itemid)
raise SystemExit
#flayer = dataitem.layers[0].url
flayer = FeatureLayer.fromitem(dataitem)
print('Download complete.') # https://developers.arcgis.com/python/guide/working-with-feature-layers-and-features/
geo_zip = r'C:/Users/mattl/Desktop/Test_Folder/AGO_Upload/Archive/Scratch.zip'
# Update online filegdb
old_gdb = gis.content.search(query='title:xyz, owner:' + gis.properties.user.username, item_type='filegdb')
print(old_gdb, type(old_gdb))
old_gdb.delete()
make_archive(gdb, geo_zip)
gdb_properties = {'title': 'Updated Works',
'type': 'File Geodatabase',
'tags' : 'tag, tag'}
item_cad = gis.content.add(data=geo_zip, item_properties=gdb_properties)
# https://developers.arcgis.com/rest/services-reference/enterprise/append-feature-service-layer-.htm
# Combine then Compare via Job Name (Unique) and delete older Job Name feature if there's a match
print('Comparing to online layer...')
#arcpy.Append_management(flayer, 'cad_fc', "NO_TEST") #online layer added to end of new layer's features ###### Keeps throwing an error at me.
status = flayer.append(item_id=None, upload_format='filegdb', source_table_name='Scratch')
print(status)
arcpy.Delete_management(compare_fc) ####################################################################### clears last test run, remove from final script
compare_fc = gdb + '/CAD_COPY'
arcpy.CopyFeatures_management(cad_fc, compare_fc)
arcpy.CalculateField_management(compare_fc, 'Job_Name', '!Job_Name!.replace(" ", "").lower()', "PYTHON3")
duplicates = arcpy.ValueTable(3)
arcpy.FindIdentical_management(compare_fc, duplicates, ['Job_Name'], output_record_option="ONLY_DUPLICATES")
if duplicates.empty():
pass
else:
#create index of duplicate features, 'IN_FID' being the OID of duplicate in online layer
duplicate_index = []
with arcpy.da.SearchCursor(duplicates, ['IN_FID']) as index:
for x in index:
duplicate_index.append(x[0])
#remove duplicate features by index list
with arcpy.da.UpdateCursor(cad_fc, ['OID']) as features:
for x in features:
if x[0] in duplicate_index:
x.deleteRow()
final_fc = cad_fc
print('Complete')
# Overwrite hosted feature layer
# save to upload folder
print('Saving to upload folder...')
outLayerFile = dwnpath + 'Previous_Designs_' + str(datetime.date.today()) + '.lyrx'
arcpy.SaveToLayerFile_management(final_fc, outLayerFile, "ABSOLUTE")
print('Done.')
print('Updating online layer...')
#flayer.manager.overwrite(outLayerFile)
print('Complete.')
# Move and Zip Processed .dwg's to 'Processed' Folder with date in name
print('Cleaning folders...')
zip_name = '_Processed_' + str(datetime.date.today())
dest = dir_path + zip_name
os.mkdir(dest)
for file in dwg_list:
full_path = dir_path + file
shutil.move(full_path, dest)
shutil.make_archive(zip_name, 'zip', dir_path)
del dest, full_path
dest = '_Previous_Designs_' + str(datetime.date.today())
full_path = dwnpath + dest
os.mkdir(full_path)
shutil.move(outLayerFile, full_path)
shutil.make_archive(full_path, 'zip', dwnpath)
print('Complete.')
print('Emptying .gdb...')
arcpy.Delete_management(in_data=[cad_fc, flayer, final_fc, compare_fc])
print('Complete.')
print('Script successful. Exiting...')
raise SystemExit()