当前位置: 首页>>代码示例>>Python>>正文


Python FeatureLayer.query方法代码示例

本文整理汇总了Python中arcrest.agol.FeatureLayer.query方法的典型用法代码示例。如果您正苦于以下问题:Python FeatureLayer.query方法的具体用法?Python FeatureLayer.query怎么用?Python FeatureLayer.query使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在arcrest.agol.FeatureLayer的用法示例。


在下文中一共展示了FeatureLayer.query方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: QueryAllFeatures

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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()
开发者ID:datastark,项目名称:ArcREST,代码行数:60,代码来源:featureservicetools.py

示例2: main

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
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"])
开发者ID:BrunoCaimar,项目名称:ArcREST,代码行数:32,代码来源:query_agol_layer_using_ArcMap_Creds.py

示例3: FeatureLayer

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    securityinfo['proxy_port'] = proxy_port
    securityinfo['referer_url'] = None
    securityinfo['token_url'] = None
    securityinfo['certificatefile'] = None
    securityinfo['keyfile'] = None
    securityinfo['client_id'] = None
    securityinfo['secret_id'] = None

    shh = securityhandlerhelper.securityhandlerhelper(securityinfo=securityinfo)
    if shh.valid == False:
        print shh.message
    else:
        fl= FeatureLayer(
            url=url,
            securityHandler=shh.securityhandler,
            proxy_port=proxy_port,
            proxy_url=proxy_url,
            initialize=True)

        out_fields = ['objectid']
        for fld in fieldInfo:
            out_fields.append(fld['FieldName'])

        resFeats = fl.query(where=sql,
                            out_fields=",".join(out_fields))
        for feat in resFeats:

            for fld in fieldInfo:
                feat.set_value(fld["FieldName"],fld['ValueToSet'])

        print fl.updateFeature(features=resFeats)
开发者ID:BrunoCaimar,项目名称:ArcREST,代码行数:33,代码来源:update_features.py

示例4: AGOLTokenSecurityHandler

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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")
    # arcpy.CreateFileGDB_management(output, "GET" + curYear + curMonth + curDay)
    werkspace = output + os.sep + "GET" + curYear + curMonth + curDay + ".gdb"

    # sample = "C:\\TxDOT\\Scripts\\javascript\\Guardrail\\Data\\GuardrailPoints.gdb\\GuardrailPoints"
    # sr = arcpy.SpatialReference(3857)
    # arcpy.CreateFeatureclass_management(werkspace, "GuardrailEndTreatments", "POINT", sample, "DISABLED", "DISABLED", sr)
开发者ID:adambreznicky,项目名称:python,代码行数:33,代码来源:tester.py

示例5: DeleteFeaturesFromFeatureLayer

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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"}

                    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()
开发者ID:datastark,项目名称:crime-analysis-toolbox,代码行数:73,代码来源:featureservicetools.py

示例6: QueryAllFeatures

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    def QueryAllFeatures(self, url=None,
                         where="1=1",
                        out_fields="*",
                        timeFilter=None,
                        geometryFilter=None,
                        returnFeatureClass=False,
                        out_fc=None,
                        outSR=None,
                        chunksize=1000,
                        printIndent=""):

        """Performs an SQL query against a hosted feature service layer
        and returns all features regardless of service limit.

        Args:
            url (str): The URL of the feature service layer.
            where - the selection sql statement
            out_fields - the attribute fields to return
            timeFilter - a TimeFilter object where either the start time
                         or start and end time are defined to limit the
                         search results for a given time.  The values in
                         the timeFilter should be as UTC timestampes in
                         milliseconds.  No checking occurs to see if they
                         are in the right format.
            geometryFilter - a GeometryFilter object to parse down a given
                            query by another spatial dataset.
            returnFeatureClass - Default False. If true, query will be
                                 returned as feature class
            chunksize (int): The maximum amount of features to query at a time. Defaults to 1000.
            out_fc - only valid if returnFeatureClass is set to True.
                        Output location of query.

            Output:
               A list of Feature Objects (default) or a path to the output featureclass if
               returnFeatureClass is set to True.

        """
        if (url is None):
            return
        fl = None
        try:
            fl = FeatureLayer(url=url, securityHandler=self._securityHandler)
            qRes = fl.query(where=where,
                            returnIDsOnly=True,
                            timeFilter=timeFilter,
                            geometryFilter=geometryFilter)

            if 'error' in qRes:
                print (printIndent + qRes)
                return []
            elif 'objectIds' in qRes:
                oids = qRes['objectIds']
                total = len(oids)
                if total == 0:
                    return fl.query(where=where,
                                    returnGeometry=True,
                                    out_fields=out_fields,
                                    timeFilter=timeFilter,
                                    geometryFilter=geometryFilter,
                                    outSR=outSR)

                print (printIndent + "%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,
                                           timeFilter=timeFilter,
                                            geometryFilter=geometryFilter,
                                            outSR=outSR)
                        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(printIndent + "{:.0%} Completed: {}/{}".format(totalQueried / float(total), totalQueried, total))

                        else:
                            print (printIndent + results)
                if returnFeatureClass == True:
                    return combinedResults.save(*os.path.split(out_fc))
                else:
                    return combinedResults
            else:
                print (printIndent + qRes)
        except:
            line, filename, synerror = trace()
            raise common.ArcRestHelperError({
                        "function": "QueryAllFeatures",
                        "line": line,
                        "filename":  filename,
#.........这里部分代码省略.........
开发者ID:Esri,项目名称:ArcREST,代码行数:103,代码来源:featureservicetools.py

示例7: DeleteFeaturesFromFeatureLayer

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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()
开发者ID:Esri,项目名称:ArcREST,代码行数:81,代码来源:featureservicetools.py

示例8: main

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
def main():
    try:
        proxy_port = None
        proxy_url = None
    
        securityinfo = {}
        securityinfo['security_type'] = 'Portal'#LDAP, NTLM, OAuth, Portal, PKI
        securityinfo['username'] = ""#<UserName>
        securityinfo['password'] = ""#<Password>
        securityinfo['org_url'] = "http://www.arcgis.com"
        securityinfo['proxy_url'] = proxy_url
        securityinfo['proxy_port'] = proxy_port
        securityinfo['referer_url'] = None
        securityinfo['token_url'] = None
        securityinfo['certificatefile'] = None
        securityinfo['keyfile'] = None
        securityinfo['client_id'] = None
        securityinfo['secret_id'] = None
    
    
        workforceProjectID = '' #Workforce project number

        assignmentAreasID = '' #ID of service to get centroids from
        assignmentAreaLayerName = ''#layer in servuce
        assignmentAreaNameField = ''#field with name of id area
        
        csvPath = r".\dataToLookup.csv"#<Path with data>
        workerCol = 'worker'
        areaCol  = 'area'
        descriptionCol = "description"
        notesCol = "notes"
        supervisorCol = "supervisor"
         
        assignmentType = 2
        status = 1
        
        workerNameToID = {}
        dispatcherNameToID = {}
        areaNameToID = {}
        fst = featureservicetools.featureservicetools(securityinfo)
        if fst.valid == False:
            print (fst.message)
        else:
            portalAdmin = arcrest.manageorg.Administration(securityHandler=fst.securityhandler)
            #Get the assignment areas
            fs = fst.GetFeatureService(itemId=assignmentAreasID,returnURLOnly=False)
            if not fs is None:
                fs_url = fst.GetLayerFromFeatureService(fs=fs,layerName=assignmentAreaLayerName,returnURLOnly=True)
                if not fs_url is None:

                    fl = FeatureLayer(
                        url=fs_url,
                        securityHandler=fst.securityhandler,
                        proxy_port=proxy_port,
                        proxy_url=proxy_url,
                        initialize=True)                    
                    areaResults =  fl.query(**{'where':"1=1",'outSR':'102100','out_fields':assignmentAreaNameField,'returnGeometry':False,'returnCentroid':True})
                   
                    for area in areaResults:
                        arDict = area.asDictionary
                        areaNameToID[arDict['attributes'][assignmentAreaNameField]] = arDict['centroid']
                    
            #Get the workers
            item = portalAdmin.content.getItem(itemId=workforceProjectID)
            itemData = item.itemData()
            if 'workers' in itemData:
                fl = FeatureLayer(
                    url=itemData['workers']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
            
                workersResults = fl.query(where="1=1",out_fields='OBJECTID, NAME',returnGeometry=False)
                for worker in workersResults:
                    workerNameToID[worker.get_value('name')] = worker.get_value('OBJECTID')
            
            if 'dispatchers' in itemData:
                fl = FeatureLayer(
                    url=itemData['dispatchers']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
            
                dispatcherResults = fl.query(where="1=1",out_fields='OBJECTID, NAME',returnGeometry=False)
                for dispatcher in dispatcherResults:
                    dispatcherNameToID[dispatcher.get_value('name')] = dispatcher.get_value('OBJECTID')
                    
    
            if 'assignments' in itemData:
                features = []
                
                fl = FeatureLayer(
                    url=itemData['assignments']['url'],
                    securityHandler=fst.securityhandler,
                    proxy_port=proxy_port,
                    proxy_url=proxy_url,
                    initialize=True)
                print(fl.deleteFeatures(where="1=1"))
#.........这里部分代码省略.........
开发者ID:BrunoCaimar,项目名称:ArcREST,代码行数:103,代码来源:load_assignments_lookup.py

示例9: QueryAllFeatures

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    def QueryAllFeatures(self, url, sql, out_fields="*", chunksize=1000, savePath=None):
        """Performs an SQL query against a hosted feature service layer.

        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 returned.
            out_fields (str): A comma delimited list of field names to return.
                Defaults to ``"*"``, i.e., return all fields
            chunksize (int): The maximum amount of features to query at a time. Defaults to 1000.
            savePath (str): The full path on disk where the features will be saved. Defaults to ``None``.
        Returns:
            When ``savePath`` is not provided (``None``), the result from
                :py:func:`arcrest.agol.services.FeatureLayer.query`.

            When ``savePath`` is provided, the result from
                :py:func:`arcrest.common.general.FeatureSet.save`.

        """
        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 savePath is None or savePath == '':
                    return combinedResults
                else:
                    return combinedResults.save(*os.path.split(savePath))
            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()
开发者ID:adamkerz,项目名称:ArcREST,代码行数:78,代码来源:featureservicetools.py

示例10: AGOLTokenSecurityHandler

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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")
    arcpy.CreateFileGDB_management(output, "GET" + curYear + curMonth + curDay)
    werkspace = output + os.sep + "GET" + curYear + curMonth + curDay + ".gdb"

    sample = "C:\\TxDOT\\Scripts\\javascript\\Guardrail\\Data\\GuardrailPoints.gdb\\GuardrailPoints"
    sr = arcpy.SpatialReference(3857)
    arcpy.CreateFeatureclass_management(werkspace, "GuardrailEndTreatments", "POINT", sample, "DISABLED", "DISABLED", sr)
开发者ID:adambreznicky,项目名称:javascript,代码行数:33,代码来源:backup_v1.py

示例11: AGOLTokenSecurityHandler

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
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) )
开发者ID:BrunoCaimar,项目名称:ArcREST,代码行数:24,代码来源:query_agol_layer.py

示例12: DeleteFeaturesFromFeatureLayer

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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()
开发者ID:vsingh58,项目名称:ArcREST,代码行数:73,代码来源:featureservicetools.py

示例13: QueryAllFeatures

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
    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()            
开发者ID:jmk201,项目名称:ArcREST,代码行数:78,代码来源:featureservicetools.py

示例14: downloadData

# 需要导入模块: from arcrest.agol import FeatureLayer [as 别名]
# 或者: from arcrest.agol.FeatureLayer import query [as 别名]
def downloadData():
    print "beginning data download..."
    proxy_port = None
    proxy_url = None

    agolSH = AGOLTokenSecurityHandler(username=username,
                                      password=password)

    fl = FeatureLayer(
        url=feature_service_url,
        securityHandler=agolSH,
        proxy_port=proxy_port,
        proxy_url=proxy_url,
        initialize=True)

    oid_query_response = fl.query(returnIDsOnly=True)
    oid_list = oid_query_response["objectIds"]
    oid_list.sort()
    list_length = len(oid_list)
    print list_length

    if os.path.exists(output_folder + os.sep + feature_class_name + "_" + the_date + ".gdb"):
        shutil.rmtree(output_folder + os.sep + feature_class_name + "_" + the_date + ".gdb")
    if os.path.isfile(output_folder + os.sep + "Errors.csv"):
        os.remove(output_folder + os.sep + "Errors.csv")
    arcpy.CreateFileGDB_management(output_folder, feature_class_name + "_" + the_date)
    output_fgdb = output_folder + os.sep + feature_class_name + "_" + the_date + ".gdb"

    def updatedQuery(low, high, trigger):
        if low != high:
            updated_query = """"OBJECTID" >= """ + str(low) + " AND " + """"OBJECTID" < """ + str(high)
            if trigger == 1:
                updated_query = """"OBJECTID" >= """ + str(low)
        else:
            updated_query = """"OBJECTID" = """ + str(low)
        return updated_query

    errors = []
    error_fields = []
    fc = ""
    fields = ["[email protected]"]
    low = 0
    high = 1000
    counter = 0
    while low <= list_length:
        min = oid_list[low]
        try:
            max = oid_list[high]
            trigger = 0
        except:
            totalFixed = list_length - 1
            max = oid_list[totalFixed]
            trigger = 1
        updated_query = updatedQuery(min, max, trigger)
        returned_data = fl.query(where=updated_query,out_fields='*',returnGeometry=True)
        returned_data_string = str(returned_data)
        d = json.loads(returned_data_string)
        print "dictionary compiled."

        if counter == 0:
            wkid = d['spatialReference']['latestWkid']
            sr = arcpy.SpatialReference(wkid)
            arcpy.CreateFeatureclass_management(output_fgdb, feature_class_name, "POLYLINE", "", "DISABLED", "DISABLED", sr)
            fc = output_fgdb + os.sep + feature_class_name
            for field in d['fields']:
                print field["name"]
                error_fields.append(field["name"])
                if field["name"] != "OBJECTID" and field["name"] != "Shape_Length" and field["name"] != "GlobalID":
                    text_length = ""
                    if field["type"] == "esriFieldTypeInteger":
                        type = "LONG"
                    elif field["type"] == "esriFieldTypeSmallInteger":
                        type = "SHORT"
                    elif field["type"] == "esriFieldTypeString":
                        type = "TEXT"
                        text_length = field["length"]
                    elif field["type"] == "esriFieldTypeDouble":
                        type = "DOUBLE"
                    elif field["type"] == "esriFieldTypeFloat":
                        type = "FLOAT"
                    elif field["type"] == "esriFieldTypeDate":
                        type = "DATE"
                    arcpy.AddField_management(fc, field["name"], type, "", "", text_length, field["alias"])
                    fields.append(field["name"])
            errors.append(error_fields)

        cursor = arcpy.da.InsertCursor(fc, fields)
        records = d["features"]
        for record in records:
            try:
                geom = record["geometry"]
                paths = geom["paths"]
                new_geom = arcpy.Array()
                for part in paths:
                    this_part = arcpy.Array()
                    for point in part:
                        this_point = arcpy.Point(point[0], point[1])
                        this_part.append(this_point)
                    new_geom.append(this_part)
                polyline = arcpy.Polyline(new_geom)
#.........这里部分代码省略.........
开发者ID:TxDOT,项目名称:python,代码行数:103,代码来源:Download_Entire_Service_arcRest_Polyline.py


注:本文中的arcrest.agol.FeatureLayer.query方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。