I have a python script that has been working fine for some time.
I added a table and a relationship class to my database connecting to the Feature Class I was updating.....and now the python script is complaining that it cannot add outside an edit session.
My python script accepts a json string that can have multiple updates or just 1
I added some Start Edit and Stop Edit code and its still not working and giving me another error
If I modify my edit string to this to include the Feature Class that has the relationship class
edit = arcpy.da.Editor(r"E:/ArcGISProjects/CountySelection/cccc.sde/MultiPartPoly")
I get this error
Executing: createNWTLGEometryJSONJays "{"employees":[{"address":"1520 Split Oak Ln, Henrico, Virginia, 23229","distance":"10", "id" : "1a35172e071f4a33b191172a9b4b02ae" },{"address":"1341 Research Center Dr Blacksburg, VA 24060","distance":"9", "id" : "6a35172e071f4a33b191172a9b4b02ae" }]}"
Start Time: Tue Apr 21 15:42:10 2020
Running script createNWTLGEometryJSONJays...
Failed script createNWTLGEometryJSONJays...
Traceback (most recent call last):
File "E:\Projects\Selection\Python\county.py", line 124, in <module>
edit = arcpy.da.Editor(r"E:/ArcGISProjects/CountySelection/cccc.sde/MultiPartPoly")
RuntimeError: cannot open workspace
Failed to execute (createNWTLGEometryJSONJays).
Failed at Tue Apr 21 15:42:11 2020 (Elapsed Time: 1.50 seconds)
import arcpy
import requests
import json
import uuid
dataInputParameter1 = arcpy.GetParameterAsText(0)
# {"employees":[{"address":"1520 Split Oak Ln, Henrico, Virginia, 23229","distance":"10", "id" : "1a35172e071f4a33b191172a9b4b02ae" },{"address":"1341 Research Center Dr Blacksburg, VA 24060","distance":"9", "id" : "6a35172e071f4a33b191172a9b4b02ae" }]}
textDict = json.loads(dataInputParameter1)
# DELETE ALL ROWS FROM THE FINAL DATASET
#arcpy.DeleteRows_management(r"E:/ArcGISProjects/CountySelection/ccccc.sde/MultiPartPoly_WebMercatorAux")
langs = []
for employee in textDict['employees']:
varsearchAddress = employee["address"]
varsearchDistance = employee["distance"]
varsearchid = employee["id"]
print ("address: " + varsearchAddress)
print ("distance: " + varsearchDistance)
print ("uniqueid: " + varsearchid)
print ""
# LOCAL VARIABLES
coordinates = ""
countList = []
countyField = "FIPS2"
countList2 = []
finalList = []
txt_list = ""
txt_list2 = ""
data = ""
# GEOCODERS
geoCodeUrl = r"https://xxxxx/arcgis/rest/services/Geocoding/Composite_Locator/GeocodeServer/findAddressCandidates"
searchAddress = varsearchAddress
searchDistance = varsearchDistance
searchid = varsearchid
# CONVERT MILE TO METERS FOR SPATIAL BUFFER
distanceMeters = int(varsearchDistance) * 1609.34
def singleAdressGeocode(address, geoCodeUrl, outSR = "26917"):
##clean up the address for url encoding
address = address.replace(" ", "+")
address = address.replace(",", "%3B")
#send address to geocode service
lookup = requests.get(geoCodeUrl + "?SingleLine=" + address + "&outSR=" + outSR + "&maxLocations=1&f=pjson")
data = lookup.json()
if data["candidates"]:
##coords = data["candidates"][0]["location"]
##return coords
return data
else:
##no results
return "Address not geocoded: " + address
# DEFINE VARIABLES FOR THE ADDRESS AND X AND Y VALUES
geocodeResult = singleAdressGeocode(searchAddress, geoCodeUrl)
addressResult = geocodeResult["candidates"][0]["address"]
coordinateX = geocodeResult["candidates"][0]["location"]["x"]
coordinateY = geocodeResult["candidates"][0]["location"]["y"]
strcoordinateX = str(coordinateX)
strcoordinateY = str(coordinateY)
arcpy.env.workspace = r"E:/ArcGISProjects/CountySelection/ccccc.sde"
# CREATE THE POINT FROM THE X AND Y
point = arcpy.Point(coordinateX, coordinateY)
ptGeometry = arcpy.PointGeometry(point)
# FEED THE BUFFER ANALYSIS THE POINT GEOMETRY THE DISTANCE PARAMETERS AND WRITE BUFFER TO MEMORY
arcpy.Buffer_analysis(ptGeometry, 'IN_MEMORY/BufferGeom', distanceMeters)
# DEFINE THE COUNTIES FC
arcpy.MakeFeatureLayer_management(r"E:/ArcGISProjects/CountySelection/ccccc.sde/Counties_1_Dissolved", "counties_lyr")
# SELECT FROM BUFFER PUT INTO RESULTS VARIABLE
results = arcpy.SelectLayerByLocation_management('counties_lyr', 'INTERSECT', 'IN_MEMORY/BufferGeom')
# GET THE FIPS CODES FROM THE RESULTS OF THE SELECTION
rows = arcpy.SearchCursor(results,"","","FIPS2")
for row in rows:
neighborVal = str(row.FIPS2)
#print(neighborVal)
countList.append(neighborVal)
txt_list = ','.join(countList)
# COPY THE SELECT RESULTS INTO MEMORY
arcpy.CopyFeatures_management("counties_lyr", "IN_MEMORY/CountiesSelection")
# DISSOLVE THE RESULTS INTO MULTIPART GEOMETRY AND WRITE TO MEMORY
inFeatures = "IN_MEMORY/CountiesSelection"
outFeatures = "IN_MEMORY/Counties_3_dissolved"
arcpy.Dissolve_management (inFeatures, outFeatures)
## GET THE GEOMETRY FROM THE DISSOLVED FC and PASS THAT TO THE INSERT CURSOR BELOW ALONG WITH THE ATTRIBUTE VALUES
geometries = arcpy.CopyFeatures_management("IN_MEMORY/Counties_3_dissolved", arcpy.Geometry())
arcpy.env.overwriteOutput = True
## SET THE TARGET FEATURE CLASS TO ADD THE FINAL MULTI PART GEOMETRY TO
inputFeatureclass = r"E:/ArcGISProjects/CountySelection/ccccc.sde/Poly_WebMercatorAux"
## CREATE A PROPER GID FORMAT FOR GEODATABASE
validGuid = "{{{0}}}".format(str(uuid.UUID(searchid)))
langs.append("{'address':'" + varsearchAddress + "','fids':'" + txt_list + "','id':'" + varsearchid + "'}" )
print "started"
edit = arcpy.da.Editor(r"E:/ArcGISProjects/CountySelection/cccc.sde")
edit.startEditing()
print "edit started"
# Perform edits
## CREATE THE NEW MULTI PART POLYGON IN THE FC
with arcpy.da.InsertCursor(inputFeatureclass, ['SHAPE@', 'ADDRESSgeocode', 'DISTANCEparameter', 'UNIQUEIDparameter', 'COUNTYLIST', 'NWTLID']) as cursor:
cursor.insertRow([geometries[0], searchAddress, searchDistance, searchid, txt_list, validGuid])
## Delete cursor object
del cursor
edit.stopOperation()
print "operation stopped"
# RETURN THE LIST OF FIPS TO THE REST END POINT SENT TO THE 4th PARAMETER OF THE GP TOOL
#msg =("update successful")
#msg =(txt_list)
langs2 = json.dumps(langs, separators=(',', ':'))
msg =(langs)
arcpy.AddMessage(msg)
resultMsg = msg
arcpy.SetParameterAsText(1, resultMsg)
Executing: createNWTLGEometryJSONJays "{"employees":[{"address":"1520 Split Oak Ln, Henrico, Virginia, 23229","distance":"10", "id" : "1a35172e071f4a33b191172a9b4b02ae" },{"address":"1341 Research Center Dr Blacksburg, VA 24060","distance":"9", "id" : "6a35172e071f4a33b191172a9b4b02ae" }]}"
Start Time: Tue Apr 21 15:33:04 2020
Running script createNWTLGEometryJSONJays...
Failed script createNWTLGEometryJSONJays...
Traceback (most recent call last):
File "E:\ArcGISProjects\CountySelection\Python\county.py", line 130, in <module>
cursor.insertRow([geometries[0], searchAddress, searchDistance, searchid, txt_list, validGuid])
RuntimeError: Objects in this class cannot be updated outside an edit session [xxx.DBO.PartPoly_WebMercatorAux]
Failed to execute (createNWTLGEometryJSONJays).
Failed at Tue Apr 21 15:33:06 2020 (Elapsed Time: 1.53 seconds)
Solved! Go to Solution.
I think I got it working.....maybe a refresh or reopening of ArcCatalog?????
Testing now so hold on...thin it worked two times
workspace = r"E:/ArcGISProjects/CountySelection/cccc.sde"
edit = arcpy.da.Editor(workspace)
# Edit session is started without an undo/redo stack for versioned data
# (for second argument, use False for unversioned data)
edit.startEditing(False, False)
print "edit started"
# Create update cursor
with arcpy.da.InsertCursor(inputFeatureclass, ['SHAPE@', 'ADDRESSgeocode', 'DISTANCEparameter', 'UNIQUEIDparameter', 'COUNTYLIST', 'NWTLID']) as cursor:
# Start an edit operation
edit.startOperation()
# Perform edits
## CREATE THE NEW MULTI PART POLYGON IN THE FC
cursor.insertRow([geometries[0], searchAddress, searchDistance, searchid, txt_list, validGuid])
## Delete cursor object
del cursor
# Stop the edit operation.
edit.stopOperation()
# Stop the edit session and save the changes
edit.stopEditing(True)
print "edit ended"
I change the second argument to False but will not go....
This is not versioned data
It is a Feature Class with a relationship Class to a table
# Edit session is started without an undo/redo stack for versioned data
# (for second argument, use False for unversioned data)
edit.startEditing(False, False)
I think I got it working.....maybe a refresh or reopening of ArcCatalog?????
Testing now so hold on...thin it worked two times
workspace = r"E:/ArcGISProjects/CountySelection/cccc.sde"
edit = arcpy.da.Editor(workspace)
# Edit session is started without an undo/redo stack for versioned data
# (for second argument, use False for unversioned data)
edit.startEditing(False, False)
print "edit started"
# Create update cursor
with arcpy.da.InsertCursor(inputFeatureclass, ['SHAPE@', 'ADDRESSgeocode', 'DISTANCEparameter', 'UNIQUEIDparameter', 'COUNTYLIST', 'NWTLID']) as cursor:
# Start an edit operation
edit.startOperation()
# Perform edits
## CREATE THE NEW MULTI PART POLYGON IN THE FC
cursor.insertRow([geometries[0], searchAddress, searchDistance, searchid, txt_list, validGuid])
## Delete cursor object
del cursor
# Stop the edit operation.
edit.stopOperation()
# Stop the edit session and save the changes
edit.stopEditing(True)
print "edit ended"