本文整理汇总了Python中arcrest.agol.FeatureLayer类的典型用法代码示例。如果您正苦于以下问题:Python FeatureLayer类的具体用法?Python FeatureLayer怎么用?Python FeatureLayer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FeatureLayer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main(*argv):
""" main driver of program """
try:
url = str(argv[0])
arcgisSH = ArcGISTokenSecurityHandler()
if arcgisSH.valid == False:
arcpy.AddError(arcgisSH.message)
return
fl = FeatureLayer(
url=url,
securityHandler=arcgisSH,
initialize=True)
res = fl.query(where="1=1",out_fields='*',returnGeometry=False)
arcpy.AddMessage(res)
arcpy.SetParameterAsText(1, str(res))
except arcpy.ExecuteError:
line, filename, synerror = trace()
arcpy.AddError("error on line: %s" % line)
arcpy.AddError("error in file name: %s" % filename)
arcpy.AddError("with error message: %s" % synerror)
arcpy.AddError("ArcPy Error Message: %s" % arcpy.GetMessages(2))
except FunctionError, f_e:
messages = f_e.args[0]
arcpy.AddError("error in function: %s" % messages["function"])
arcpy.AddError("error on line: %s" % messages["line"])
arcpy.AddError("error in file name: %s" % messages["filename"])
arcpy.AddError("with error message: %s" % messages["synerror"])
arcpy.AddError("ArcPy Error Message: %s" % messages["arc"])
示例2: AddFeaturesToFeatureLayer
def AddFeaturesToFeatureLayer(self,url,pathToFeatureClass):
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
return fl.addFeatures(fc=pathToFeatureClass)
except arcpy.ExecuteError:
line, filename, synerror = Common.trace()
raise ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
"arcpyError": arcpy.GetMessages(2),
}
)
except:
line, filename, synerror = Common.trace()
raise ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例3: DeleteFeaturesFromFeatureLayer
def DeleteFeaturesFromFeatureLayer(self,url,sql):
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler,)
return fl.deleteFeatures(where=sql)
except arcpy.ExecuteError:
line, filename, synerror = Common.trace()
raise ArcRestHelperError({
"function": "DeleteFeaturesFromFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
"arcpyError": arcpy.GetMessages(2),
}
)
except:
line, filename, synerror = Common.trace()
raise ArcRestHelperError({
"function": "DeleteFeaturesFromFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例4: QueryAllFeatures
def QueryAllFeatures(self,url,sql,out_fields="*",chunksize=1000,saveLocation="",outName=""):
fl = None
try:
fl = FeatureLayer(url=url, securityHandler=self._securityHandler)
qRes = fl.query(where=sql, returnIDsOnly=True)
if 'error' in qRes:
print (qRes)
return qRes
elif 'objectIds' in qRes:
oids = qRes['objectIds']
total = len(oids)
if total == 0:
return {'success':True, 'message':"No features matched the query"}
print ("%s features to be downloaded" % total)
chunksize = min(chunksize, fl.maxRecordCount)
combinedResults = None
totalQueried = 0
for chunk in chunklist(l=oids, n=chunksize):
oidsQuery = ",".join(map(str, chunk))
if not oidsQuery:
continue
else:
results = fl.query(objectIds=oidsQuery,
returnGeometry=True,
out_fields=out_fields)
if isinstance(results,FeatureSet):
if combinedResults is None:
combinedResults = results
else:
for feature in results.features:
combinedResults.features.append(feature)
totalQueried += len(results.features)
print("{:.0%} Completed: {}/{}".format(totalQueried / float(total), totalQueried, total))
else:
print (results)
if saveLocation == "" or outName == "":
return combinedResults
else:
return combinedResults.save(saveLocation=saveLocation, outName=outName)
else:
print (qRes)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "QueryFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例5: DeleteFeaturesFromFeatureLayer
def DeleteFeaturesFromFeatureLayer(self,url,sql):
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
return fl.deleteFeatures(where=sql)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "DeleteFeaturesFromFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例6: AddFeaturesToFeatureLayer
def AddFeaturesToFeatureLayer(self, url, pathToFeatureClass, chunksize=0, lowerCaseFieldNames=False):
"""Appends local features to a hosted feature service layer.
Args:
url (str): The URL of the feature service layer.
pathToFeatureClass (str): The path of the feature class on disk.
chunksize (int): The maximum amount of features to upload at a time. Defaults to 0.
lowerCaseFieldNames (bool): A boolean value indicating if field names should be converted
to lowercase before uploading. Defaults to ``False``.
Returns:
The result from :py:func:`arcrest.agol.services.FeatureLayer.addFeatures`.
Raises:
ArcRestHelperError: if ``arcpy`` can't be found.
Notes:
If publishing to a PostgreSQL database, it is suggested to to set ``lowerCaseFieldNames`` to ``True``.
"""
if arcpyFound == False:
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "ArcPy required for this function"
})
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
if chunksize > 0:
fc = os.path.basename(pathToFeatureClass)
inDesc = arcpy.Describe(pathToFeatureClass)
oidName = inDesc.oidFieldName
arr = arcpy.da.FeatureClassToNumPyArray(pathToFeatureClass, (oidName))
syncSoFar = 0
messages = {'addResults':[],'errors':[]}
total = len(arr)
errorCount = 0
if total == '0':
print ("0 features in %s" % pathToFeatureClass)
return "0 features in %s" % pathToFeatureClass
print ("%s features in layer" % (total))
arcpy.env.overwriteOutput = True
if int(total) < int(chunksize):
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
else:
newArr = chunklist(arr,chunksize)
exprList = ["{0} >= {1} AND {0} <= {2}".format(oidName, nArr[0][0], nArr[len(nArr)-1][0])
for nArr in newArr]
for expr in exprList:
UploadLayer = arcpy.MakeFeatureLayer_management(pathToFeatureClass, 'TEMPCOPY', expr).getOutput(0)
#print(arcpy.GetCount_management(in_rows=UploadLayer).getOutput(0) + " features in the chunk")
results = fl.addFeatures(fc=UploadLayer,lowerCaseFieldNames=lowerCaseFieldNames)
chunkCount = arcpy.GetCount_management(in_rows=UploadLayer).getOutput(0)
print(chunkCount + " features in the chunk")
if chunkCount > 0:
if results is not None and 'addResults' in results and results['addResults'] is not None:
featSucces = 0
for result in results['addResults']:
if 'success' in result:
if result['success'] == False:
if 'error' in result:
errorCount = errorCount + 1
print ("\tError info: %s" % (result))
else:
featSucces = featSucces + 1
syncSoFar = syncSoFar + featSucces
print ("%s features added in this chunk" % (featSucces))
print ("%s/%s features added, %s errors" % (syncSoFar,total,errorCount ))
if 'addResults' in messages:
messages['addResults'] = messages['addResults'] + results['addResults']
else:
messages['addResults'] = results['addResults']
else:
messages['errors'] = result
return messages
else:
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
except arcpy.ExecuteError:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
"arcpyError": arcpy.GetMessages(2),
}
)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
#.........这里部分代码省略.........
示例7: AddFeaturesToFeatureLayer
def AddFeaturesToFeatureLayer(self,url,pathToFeatureClass,chunksize=0,lowerCaseFieldNames=False):
if arcpyFound == False:
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "ArcPy required for this function"
})
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
if chunksize > 0:
messages = {'addResults':[]}
total = arcpy.GetCount_management(pathToFeatureClass).getOutput(0)
if total == '0':
print ("0 features in %s" % pathToFeatureClass)
return "0 features in %s" % pathToFeatureClass
arcpy.env.overwriteOutput = True
if int(total) < int(chunksize):
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
else:
inDesc = arcpy.Describe(pathToFeatureClass)
oidName = arcpy.AddFieldDelimiters(pathToFeatureClass,inDesc.oidFieldName)
sql = '%s = (select min(%s) from %s)' % (oidName,oidName,os.path.basename(pathToFeatureClass))
cur = arcpy.da.SearchCursor(pathToFeatureClass,[inDesc.oidFieldName],sql)
minOID = cur.next()[0]
del cur, sql
sql = '%s = (select max(%s) from %s)' % (oidName,oidName,os.path.basename(pathToFeatureClass))
cur = arcpy.da.SearchCursor(pathToFeatureClass,[inDesc.oidFieldName],sql)
maxOID = cur.next()[0]
del cur, sql
breaks = range(minOID,maxOID)[0:-1:chunksize]
breaks.append(maxOID+1)
exprList = [oidName + ' >= ' + str(breaks[b]) + ' and ' + \
oidName + ' < ' + str(breaks[b+1]) for b in range(len(breaks)-1)]
for expr in exprList:
UploadLayer = arcpy.MakeFeatureLayer_management(pathToFeatureClass, 'TEMPCOPY', expr).getOutput(0)
result = fl.addFeatures(fc=UploadLayer,lowerCaseFieldNames=lowerCaseFieldNames)
if messages is None:
messages = result
else:
if result is not None and 'addResults' in result:
if 'addResults' in messages:
messages['addResults'] = messages['addResults'] + result['addResults']
print ("%s/%s features added" % (len(messages['addResults']),total))
else:
messages['addResults'] = result['addResults']
print ("%s/%s features added" % (len(messages['addResults']),total))
else:
messages['errors'] = result
return messages
else:
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
except arcpy.ExecuteError:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
"arcpyError": arcpy.GetMessages(2),
}
)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例8: AGOLTokenSecurityHandler
output = "C:\\TxDOT\\Scripts\\javascript\\Guardrail\\Snake\\BACKUP"
if __name__ == "__main__":
username = "Adam.Breznicky_TXDOT"
password = mohawk.hangnail(username)
url = "http://services.arcgis.com/KTcxiTD9dsQw4r7Z/arcgis/rest/services/OnSystemRoadways/FeatureServer/0"
proxy_port = None
proxy_url = None
agolSH = AGOLTokenSecurityHandler(username=username,
password=password)
fl = FeatureLayer(
url=url,
securityHandler=agolSH,
proxy_port=proxy_port,
proxy_url=proxy_url,
initialize=True)
qmin = 0
qmax = 2000
count = fl.query(returnIDsOnly=True)
cList = count["objectIds"]
cValue = cList[-1]
listLen = len(cList)
print listLen
now = datetime.datetime.now()
curMonth = now.strftime("%m")
curDay = now.strftime("%d")
curYear = now.strftime("%Y")
示例9: RemoveAndAddFeatures
def RemoveAndAddFeatures(self, url, pathToFeatureClass,id_field,chunksize=1000):
fl = None
try:
if arcpyFound == False:
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "ArcPy required for this function"
})
arcpy.env.overwriteOutput = True
tempaddlayer= 'ewtdwedfew'
if not arcpy.Exists(pathToFeatureClass):
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "%s does not exist" % pathToFeatureClass
}
)
fields = arcpy.ListFields(pathToFeatureClass,wild_card=id_field)
if len(fields) == 0:
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "%s field does not exist" % id_field
})
strFld = True
if fields[0].type != 'String':
strFld = False
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
id_field_local = arcpy.AddFieldDelimiters(pathToFeatureClass, id_field)
idlist = []
print( arcpy.GetCount_management(in_rows=pathToFeatureClass).getOutput(0) + " features in the layer")
with arcpy.da.SearchCursor(pathToFeatureClass, (id_field)) as cursor:
allidlist = []
for row in cursor:
if (strFld):
idlist.append("'" + row[0] +"'")
else:
idlist.append(row[0])
if len(idlist) >= chunksize:
allidlist.append(idlist)
idlist = []
if len(idlist) > 0:
allidlist.append(idlist)
for idlist in allidlist:
idstring = ' in (' + ','.join(idlist) + ')'
sql = id_field + idstring
sqlLocalFC = id_field_local + idstring
results = fl.deleteFeatures(where=sql,
rollbackOnFailure=True)
if 'error' in results:
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror":results['error']
})
elif 'deleteResults' in results:
print ("%s features deleted" % len(results['deleteResults']))
for itm in results['deleteResults']:
if itm['success'] != True:
print (itm)
else:
print (results)
arcpy.MakeFeatureLayer_management(pathToFeatureClass,tempaddlayer,sqlLocalFC)
results = fl.addFeatures(fc=tempaddlayer)
if 'error' in results:
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror":results['error']
})
elif 'addResults' in results:
print ("%s features added" % len(results['addResults']))
for itm in results['addResults']:
if itm['success'] != True:
print (itm)
else:
print (results)
idlist = []
if 'error' in results:
raise common.ArcRestHelperError({
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
#.........这里部分代码省略.........
示例10: AddFeaturesToFeatureLayer
def AddFeaturesToFeatureLayer(self,url,pathToFeatureClass,chunksize=0,lowerCaseFieldNames=False):
if arcpyFound == False:
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": inspect.currentframe().f_back.f_lineno,
"filename": 'featureservicetools',
"synerror": "ArcPy required for this function"
})
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
if chunksize > 0:
fc = os.path.basename(pathToFeatureClass)
inDesc = arcpy.Describe(pathToFeatureClass)
oidName = arcpy.AddFieldDelimiters(pathToFeatureClass,inDesc.oidFieldName)
arr = arcpy.da.FeatureClassToNumPyArray(pathToFeatureClass, (oidName))
syncSoFar = 0
messages = {'addResults':[],'errors':[]}
total = len(arr)
errorCount = 0
if total == '0':
print ("0 features in %s" % pathToFeatureClass)
return "0 features in %s" % pathToFeatureClass
print ("%s features in layer" % (total))
arcpy.env.overwriteOutput = True
if int(total) < int(chunksize):
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
else:
newArr = chunklist(arr,chunksize)
exprList = ["{0} >= {1} AND {0} <= {2}".format(oidName, nArr[0][0], nArr[len(nArr)-1][0])
for nArr in newArr]
for expr in exprList:
UploadLayer = arcpy.MakeFeatureLayer_management(pathToFeatureClass, 'TEMPCOPY', expr).getOutput(0)
#print(arcpy.GetCount_management(in_rows=UploadLayer).getOutput(0) + " features in the chunk")
results = fl.addFeatures(fc=UploadLayer,lowerCaseFieldNames=lowerCaseFieldNames)
chunkCount = arcpy.GetCount_management(in_rows=UploadLayer).getOutput(0)
print(chunkCount + " features in the chunk")
if chunkCount > 0:
if results is not None and 'addResults' in results and results['addResults'] is not None:
featSucces = 0
for result in results['addResults']:
if 'success' in result:
if result['success'] == False:
if 'error' in result:
errorCount = errorCount + 1
print ("\tError info: %s" % (result))
else:
featSucces = featSucces + 1
syncSoFar = syncSoFar + featSucces
print ("%s features added in this chunk" % (featSucces))
print ("%s/%s features added, %s errors" % (syncSoFar,total,errorCount ))
if 'addResults' in messages:
messages['addResults'] = messages['addResults'] + results['addResults']
else:
messages['addResults'] = results['addResults']
else:
messages['errors'] = result
return messages
else:
return fl.addFeatures(fc=pathToFeatureClass,lowerCaseFieldNames=lowerCaseFieldNames)
except arcpy.ExecuteError:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
"arcpyError": arcpy.GetMessages(2),
}
)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "AddFeaturesToFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例11: AGOLTokenSecurityHandler
from __future__ import print_function
from arcrest.security import AGOLTokenSecurityHandler
from arcrest.agol import FeatureLayer
if __name__ == "__main__":
username = "<username>"
password = "<password>"
url = "<URL to Feature Layer>"
proxy_port = None
proxy_url = None
agolSH = AGOLTokenSecurityHandler(username=username,
password=password)
fl = FeatureLayer(
url=url,
securityHandler=agolSH,
proxy_port=proxy_port,
proxy_url=proxy_url,
initialize=True)
print (fl.query(where="1=1",out_fields='*',returnGeometry=False) )
示例12: DeleteFeaturesFromFeatureLayer
def DeleteFeaturesFromFeatureLayer(self, url, sql, chunksize=0):
fl = None
try:
fl = FeatureLayer(url=url, securityHandler=self._securityHandler)
totalDeleted = 0
if chunksize > 0:
qRes = fl.query(where=sql, returnIDsOnly=True)
if "error" in qRes:
print qRes
return qRes
elif "objectIds" in qRes:
oids = qRes["objectIds"]
total = len(oids)
if total == 0:
return {"success": "true", "message": "No features matched the query"}
minId = min(oids)
maxId = max(oids)
i = 0
print "%s features to be deleted" % total
while i <= len(oids):
oidsDelete = ",".join(str(e) for e in oids[i : i + chunksize])
if oidsDelete == "":
continue
else:
results = fl.deleteFeatures(objectIds=oidsDelete)
if "deleteResults" in results:
totalDeleted += len(results["deleteResults"])
print "%s%% Completed: %s/%s " % (
int(totalDeleted / float(total) * 100),
totalDeleted,
total,
)
i += chunksize
else:
print results
return {"success": "true", "message": "%s deleted" % totalDeleted}
qRes = fl.query(where=sql, returnIDsOnly=True)
if "objectIds" in qRes:
oids = qRes["objectIds"]
if len(oids) > 0:
print "%s features to be deleted" % len(oids)
results = fl.deleteFeatures(where=sql)
if "deleteResults" in results:
totalDeleted += len(results["deleteResults"])
return {"success": "true", "message": "%s deleted" % totalDeleted}
else:
return results
return {"success": "true", "message": "%s deleted" % totalDeleted}
else:
print qRes
else:
results = fl.deleteFeatures(where=sql)
if "deleteResults" in results:
return {"success": "true", "message": totalDeleted + len(results["deleteResults"])}
else:
return results
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError(
{"function": "DeleteFeaturesFromFeatureLayer", "line": line, "filename": filename, "synerror": synerror}
)
finally:
fl = None
del fl
gc.collect()
示例13: RemoveAndAddFeatures
def RemoveAndAddFeatures(self, url, pathToFeatureClass, id_field, chunksize=1000):
fl = None
try:
arcpy.env.overwriteOutput = True
tempaddlayer = "ewtdwedfew"
if not arcpy.Exists(pathToFeatureClass):
raise common.ArcRestHelperError(
{
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": "featureservicetools",
"synerror": "%s does not exist" % pathToFeatureClass,
}
)
fields = arcpy.ListFields(pathToFeatureClass, wild_card=id_field)
if len(fields) == 0:
raise common.ArcRestHelperError(
{
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": "featureservicetools",
"synerror": "%s field does not exist" % id_field,
}
)
strFld = True
if fields[0].type != "String":
strFld = False
fl = FeatureLayer(url=url, securityHandler=self._securityHandler)
id_field_local = arcpy.AddFieldDelimiters(pathToFeatureClass, id_field)
idlist = []
print arcpy.GetCount_management(in_rows=pathToFeatureClass).getOutput(0) + " features in the layer"
with arcpy.da.SearchCursor(pathToFeatureClass, (id_field)) as cursor:
for row in cursor:
if strFld:
idlist.append("'" + row[0] + "'")
else:
idlist.append(row[0])
if len(idlist) >= chunksize:
idstring = " in (" + ",".join(idlist) + ")"
sql = id_field + idstring
sqlLocalFC = id_field_local + idstring
results = fl.deleteFeatures(where=sql, rollbackOnFailure=True)
if "error" in results:
raise common.ArcRestHelperError(
{
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": "featureservicetools",
"synerror": results["error"],
}
)
elif "deleteResults" in results:
print "%s features deleted" % len(results["deleteResults"])
for itm in results["deleteResults"]:
if itm["success"] != True:
print itm
else:
print results
arcpy.MakeFeatureLayer_management(pathToFeatureClass, tempaddlayer, sqlLocalFC)
results = fl.addFeatures(fc=tempaddlayer)
if "error" in results:
raise common.ArcRestHelperError(
{
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": "featureservicetools",
"synerror": results["error"],
}
)
elif "addResults" in results:
print "%s features added" % len(results["addResults"])
for itm in results["addResults"]:
if itm["success"] != True:
print itm
else:
print results
idlist = []
if "error" in results:
raise common.ArcRestHelperError(
{
"function": "RemoveAndAddFeatures",
"line": inspect.currentframe().f_back.f_lineno,
"filename": "featureservicetools",
"synerror": results["error"],
}
)
else:
print results
except arcpy.ExecuteError:
line, filename, synerror = trace()
raise common.ArcRestHelperError(
#.........这里部分代码省略.........
示例14: QueryAllFeatures
def QueryAllFeatures(self,url,sql,chunksize=0,saveLocation="",outName=""):
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
totalQueried = 0
if chunksize > 0:
qRes = fl.query(where=sql, returnIDsOnly=True)
if 'error' in qRes:
print qRes
return qRes
elif 'objectIds' in qRes:
oids = qRes['objectIds']
total = len(oids)
if total == 0:
return {'success':'true','message': "No features matched the query"}
minId = min(oids)
maxId = max(oids)
i = 0
print "%s features to be downloaded" % total
combinedResults = None
while(i <= len(oids)):
oidsQuery = ','.join(str(e) for e in oids[i:i+chunksize])
if oidsQuery == '':
continue
else:
results = fl.query(objectIds=oidsQuery,
returnGeometry=True,
out_fields='*')
if isinstance(results,FeatureSet):
if combinedResults is None:
combinedResults = results
else:
for feature in results.features:
combinedResults.features.append(feature)
totalQueried += len(results.features)
print "%s%% Completed: %s/%s " % (int(totalQueried / float(total) *100), totalQueried, total)
i += chunksize
else:
print results
print combinedResults.save(saveLocation=saveLocation, outName=outName)
else:
print qRes
else:
return fl.query(where=sql,
returnFeatureClass=True,
returnGeometry=True,
out_fields='*',
out_fc=os.path.join(saveLocation,outName)
)
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "QueryFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()
示例15: DeleteFeaturesFromFeatureLayer
def DeleteFeaturesFromFeatureLayer(self, url, sql, chunksize=0):
"""Removes features from a hosted feature service layer by SQL query.
Args:
url (str): The URL of the feature service layer.
sql (str): The SQL query to apply against the feature service.
Those features that satisfy the query will be deleted.
chunksize (int): The maximum amount of features to remove at a time. Defaults to 0.
Returns:
The result from :py:func:`arcrest.agol.services.FeatureLayer.deleteFeatures`.
Notes:
If you want to delete all features, it is suggested to use the SQL query ``"1=1"``.
"""
fl = None
try:
fl = FeatureLayer(
url=url,
securityHandler=self._securityHandler)
totalDeleted = 0
if chunksize > 0:
qRes = fl.query(where=sql, returnIDsOnly=True)
if 'error' in qRes:
print (qRes)
return qRes
elif 'objectIds' in qRes:
oids = qRes['objectIds']
total = len(oids)
if total == 0:
return {'success':True,'message': "No features matched the query"}
i = 0
print ("%s features to be deleted" % total)
while(i <= len(oids)):
oidsDelete = ','.join(str(e) for e in oids[i:i+chunksize])
if oidsDelete == '':
continue
else:
results = fl.deleteFeatures(objectIds=oidsDelete)
if 'deleteResults' in results:
totalDeleted += len(results['deleteResults'])
print ("%s%% Completed: %s/%s " % (int(totalDeleted / float(total) *100), totalDeleted, total))
i += chunksize
else:
print (results)
return {'success':True,'message': "%s deleted" % totalDeleted}
qRes = fl.query(where=sql, returnIDsOnly=True)
if 'objectIds' in qRes:
oids = qRes['objectIds']
if len(oids)> 0 :
print ("%s features to be deleted" % len(oids))
results = fl.deleteFeatures(where=sql)
if 'deleteResults' in results:
totalDeleted += len(results['deleteResults'])
return {'success':True,'message': "%s deleted" % totalDeleted}
else:
return results
return {'success':True,'message': "%s deleted" % totalDeleted}
else:
print (qRes)
else:
results = fl.deleteFeatures(where=sql)
if results is not None:
if 'deleteResults' in results:
return {'success':True,'message': totalDeleted + len(results['deleteResults'])}
else:
return results
except:
line, filename, synerror = trace()
raise common.ArcRestHelperError({
"function": "DeleteFeaturesFromFeatureLayer",
"line": line,
"filename": filename,
"synerror": synerror,
}
)
finally:
fl = None
del fl
gc.collect()