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


Python WebFeatureService.getfeature方法代码示例

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


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

示例1: getWFSData

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def getWFSData():
   from owslib.wfs import WebFeatureService   
   import string
   
   params = getWFSParams() # Get parameters     
   params = checkParams(params) # Check parameters
   
   wfs = WebFeatureService(params['baseURL'].value, version=params['version'].value)
   response = wfs.getfeature(typename=str(params['typeName'].value), featureid=[params['featureID'].value]) # Contact server
   
   if string.find(params['baseURL'].value, 'bodc', 0): 
      response = processBODCResponse(response.read(), params) # Get data from response
   else:
      pass
   
   current_app.logger.debug('Jsonifying response...') # DEBUG
   
   # Convert to json
   try:
      jsonData = jsonify(output = response)
   except TypeError as e:
      g.error = "Request aborted, exception encountered: %s" % e
      error_handler.setError('2-06', None, g.user.id, "views/wfs.py:getWFSData - Type error, returning 500 to user. Exception %s" % e, request)
      abort(500) # If we fail to jsonify the data return 500
      
   current_app.logger.debug('Request complete, Sending results') # DEBUG
   
   return jsonData # return json
开发者ID:OPEC-PML,项目名称:GISportal,代码行数:30,代码来源:wfs.py

示例2: getAttributes

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def getAttributes(shapefile, WFS_URL):
    """
    Given a valid shapefile(WFS Featuretype as returned by getShapefiles), this function will 
    make a request for one feature from the featureType and parse out the attributes that come from
    a namespace not associated with the normal GML schema. There may be a better way to determine 
    which are shapefile dbf attributes, but this should work pretty well.
    """
    wfs = WebFeatureService(WFS_URL, version='1.1.0')
    feature = wfs.getfeature(typename=shapefile, maxfeatures=1, propertyname=None)
    gml = etree.parse(feature)
    gml_root=gml.getroot()
    name_spaces = gml_root.nsmap
    
    attributes = []
    
    for namespace in name_spaces.values():
        if namespace not in ['http://www.opengis.net/wfs',
                             'http://www.w3.org/2001/XMLSchema-instance',
                             'http://www.w3.org/1999/xlink',
                             'http://www.opengis.net/gml',
                             'http://www.opengis.net/ogc',
                             'http://www.opengis.net/ows']:
            custom_namespace = namespace
            
            for element in gml.iter('{'+custom_namespace+'}*'):
                if etree.QName(element).localname not in ['the_geom', 'Shape', shapefile.split(':')[1]]:
                    attributes.append(etree.QName(element).localname)
    return attributes
开发者ID:ColinTalbert,项目名称:pyGDP,代码行数:30,代码来源:shapefile_value_handle.py

示例3: getValues

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def getValues(shapefile, attribute, getTuples, limitFeatures, wfs_url):
    """
    Similar to get attributes, given a shapefile and a valid attribute this function
    will make a call to the Web Feature Services returning a list of values associated
    with the shapefile and attribute.

    If getTuples = True, will also return the tuples of [feature:id]  along with values [feature]
    """

    wfs = WebFeatureService(wfs_url, version='1.1.0')

    feature = wfs.getfeature(typename=shapefile, maxfeatures=limitFeatures, propertyname=[attribute])
    content = BytesIO(feature.read().encode())
    gml = etree.parse(content)

    values = []

    for el in gml.iter():
        if attribute in el.tag:
            if el.text not in values:
                values.append(el.text)

    if getTuples == 'true' or getTuples == 'only':
        tuples = []
        att = False

        # If features are encoded as a list of featureMember elements.
        gmlid_found = False
        for featureMember in gml.iter('{' + GML_NAMESPACE + '}featureMember'):
            for el in featureMember.iter():
                if el.get('{' + GML_NAMESPACE + '}id'):
                    gmlid = el.get('{' + GML_NAMESPACE + '}id')
                    att = True
                    gmlid_found = True
                if attribute in el.tag and att is True:
                    value = el.text
                    tuples.append((value, gmlid))
                    att = False
            if not gmlid_found:
                raise Exception('No gml:id found in source feature service. This form of GML is not supported.')

        # If features are encoded as a featureMembers element.
        for featureMember in gml.iter('{' + GML_NAMESPACE + '}featureMembers'):
            for el in featureMember.iter():
                gmlid = el.get('{' + GML_NAMESPACE + '}id')
                for feat in el.getchildren():
                    if attribute in feat.tag:
                        value = feat.text
                        tuples.append((value, gmlid))

    if getTuples == 'true':
        return sorted(values), sorted(tuples)
    elif getTuples == 'only':
        return sorted(tuples)
    else:
        return sorted(values)
开发者ID:USGS-CIDA,项目名称:pyGDP,代码行数:58,代码来源:shapefile_value_handle.py

示例4: runTest

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
 def runTest(self):
     minX = -76.766960
     minY = 39.283611
     maxX = -76.684120
     maxY = 39.338394
     
     filter = "<Filter><BBOX><PropertyName>Geometry</PropertyName> <Box srsName='EPSG:4326'><coordinates>%f,%f %f,%f</coordinates> </Box></BBOX></Filter>" % (minX, minY, maxX, maxY)
     wfs = WebFeatureService('http://SDMDataAccess.nrcs.usda.gov/Spatial/SDMWGS84Geographic.wfs', version='1.0.0')
     response = wfs.getfeature(typename=('MapunitPolyExtended',), filter=filter, propertyname=None)
     self.assertTrue(response.read().find('<wfs:FeatureCollection') > 0,
                     'Unable to find feature dataset in WFS response')
开发者ID:CowanSM,项目名称:owslib,代码行数:13,代码来源:test_wfs_USDASSURGO.py

示例5: getValues

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def getValues(shapefile, attribute, getTuples, limitFeatures, WFS_URL):
    """
    Similar to get attributes, given a shapefile and a valid attribute this function
    will make a call to the Web Feature Services returning a list of values associated
    with the shapefile and attribute.
    
    If getTuples = True, will also return the tuples of [feature:id]  along with values [feature]
    """

    wfs = WebFeatureService(WFS_URL, version="1.1.0")

    feature = wfs.getfeature(typename=shapefile, maxfeatures=limitFeatures, propertyname=[attribute])

    gml = etree.parse(feature)

    values = []

    for el in gml.iter():
        if attribute in el.tag:
            if el.text not in values:
                values.append(el.text)

    if getTuples == "true" or getTuples == "only":
        tuples = []
        # If features are encoded as a list of featureMember elements.
        gmlid_found = False
        for featureMember in gml.iter("{" + GML_NAMESPACE + "}featureMember"):
            for el in featureMember.iter():
                if el.get("{" + GML_NAMESPACE + "}id"):
                    gmlid = el.get("{" + GML_NAMESPACE + "}id")
                    att = True
                    gmlid_found = True
                if attribute in el.tag and att == True:
                    value = el.text
                    tuples.append((value, gmlid))
                    att = False
            if gmlid_found == False:
                raise Exception("No gml:id found in source feature service. This form of GML is not supported.")
        # If features are encoded as a featureMembers element.
        for featureMember in gml.iter("{" + GML_NAMESPACE + "}featureMembers"):
            for el in featureMember.iter():
                gmlid = el.get("{" + GML_NAMESPACE + "}id")
                for feat in el.getchildren():
                    if attribute in feat.tag:
                        value = feat.text
                        tuples.append((value, gmlid))

    if getTuples == "true":
        return sorted(values), sorted(tuples)
    elif getTuples == "only":
        return sorted(tuples)
    else:
        return sorted(values)
开发者ID:ayan-usgs,项目名称:pyGDP,代码行数:55,代码来源:shapefile_value_handle.py

示例6: webgisfilter

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def webgisfilter(mapserv, layer, maxfeatures=None, startindex=None, bbox=None,
        filters=None):
    """webgis wfs client

    Each filter format should look like:

    {
        'attribute': ATTRIBUTE_NAME, # e.g. 'NAME'
        'operator': OPERATOR, # e.g. '='
        'value': VALUE # e.g. 'Prague'
    }

    Operators: = != ~ IN

    :param str mapserv: url to mapserver
    :param str layer: layer name
    :param int maxfeatures: number of returned features
    :param int startindex: starting feature index
    :param Tupple.<dict> filters: tupple of filters
    :return: json-encoded result
    :rtype: dict
    """

    mywfs = WebFeatureService(url=mapserv, version='1.0.0')
    fes = None
    if filters:
        if bbox:
            filters.append({ 'operator':'BBOX', 'value': bbox})
        fes = get_filter_root(get_filter_fes(filters))
        fes = etree.tostring(fes)

    if bbox and not filters:
        fes = None
    elif not bbox and filters:
        bbox = None
    elif bbox and filters:
        bbox = None

    layer_data = mywfs.getfeature(typename=[layer],
                                  filter=fes,
                                  bbox=bbox,
                                  featureid=None,
                                  outputFormat="GeoJSON",
                                  maxfeatures=maxfeatures,
                                  startindex=startindex)
    data = json.load(layer_data)

    for feature in data['features']:
        feature.pop('geometry')

    return data
开发者ID:bstroebl,项目名称:gislab-web,代码行数:53,代码来源:wfsfilter.py

示例7: GetWFSLayer

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def GetWFSLayer(u, p):
  start = time.time()
  # Separate the WFS URL & the layer name
  split_url = u.split('?')
  server_url = split_url[0]
  ows = server_url[-3:]
  print 'The OGC standard is: '+ ows
  
  spacename_wfs = split_url[1]
  tmp_chemin = p + spacename_wfs+"_.zip"
  chemin = tmp_chemin[:-5]+".zip"
  
  if not os.path.exists(chemin):
    # Get the vector layer using OGC WFS standard
    wfs = WebFeatureService(server_url ,version='1.0.0')
    getFeature = wfs.getfeature(typename = [spacename_wfs], outputFormat ="shape-zip") 
    
    print('Downloading... : '+ spacename_wfs)
    print("From: "+ server_url)
    
    # Download the zipped shapefile
    data = getFeature.read()
    f = open(tmp_chemin ,'wb')
    f.write(data)
    f.close()
    
    # Delete .txt & .cst files from the zipped file
    zin = zipp(tmp_chemin, 'r')
#    zin.extractall(p)
    zout = zipp(chemin, 'w')
    for item in zin.infolist():
      buffer = zin.read(item.filename)
      ext = item.filename[-4:]
      if (ext != '.txt' and ext != '.cst'):
          zout.writestr(item, buffer)
          
    zout.close()
    zin.close()
    os.remove(tmp_chemin)
    
#    # Unzip zipped shapefile
    os.system("unzip "+ chemin + ' -d '+ p)
  
  # Calculat time
  temps =time.time() - start
  tps = round(temps,2)
  temps_ms = str(tps)
  
  print "GetWFSLayer download time : " + temps_ms +" ms"
  
  return
开发者ID:BVService,项目名称:bvservice-wps,代码行数:53,代码来源:GetWFSLayer.py

示例8: load_layer_data

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def load_layer_data(request, template='layers/layer_detail.html'):
    context_dict = {}
    data_dict = json.loads(request.POST.get('json_data'))
    layername = data_dict['layer_name']
    filtered_attributes = data_dict['filtered_attributes']
    workspace, name = layername.split(':')
    location = "{location}{service}".format(** {
        'location': settings.OGC_SERVER['default']['LOCATION'],
        'service': 'wms',
    })

    try:
        username = settings.OGC_SERVER['default']['USER']
        password = settings.OGC_SERVER['default']['PASSWORD']
        wfs = WebFeatureService(location, version='1.1.0', username=username, password=password)
        response = wfs.getfeature(typename=name, propertyname=filtered_attributes, outputFormat='application/json')
        x = response.read()
        x = json.loads(x)
        features_response = json.dumps(x)
        decoded = json.loads(features_response)
        decoded_features = decoded['features']
        properties = {}
        for key in decoded_features[0]['properties']:
            properties[key] = []

        # loop the dictionary based on the values on the list and add the properties
        # in the dictionary (if doesn't exist) together with the value
        for i in range(len(decoded_features)):

            for key, value in decoded_features[i]['properties'].iteritems():
                if value != '' and isinstance(value, (string_types, int, float)):
                    properties[key].append(value)

        for key in properties:
            properties[key] = list(set(properties[key]))
            properties[key].sort()

        context_dict["feature_properties"] = properties
    except:
        print "Possible error with OWSLib."
    return HttpResponse(json.dumps(context_dict), content_type="application/json")
开发者ID:ingenieroariel,项目名称:geonode,代码行数:43,代码来源:views.py

示例9: get_wfs

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def get_wfs(server_url, spacename_wfs):

    chemin = '/home/tmp/'+spacename_wfs+'.gml'

    if not os.path.exists(chemin):
        
        wfs = WebFeatureService(server_url +"/wfs/",version='1.0.0')
    
        vector = spacename_wfs
        
        print "Downloading the WFS: "+spacename_wfs
        print "From: "+server_url
        response = wfs.getfeature(typename =[vector])    
    
        data = response.read()
        f = open(chemin,'wb')
        f.write(data)
        f.close()
        print "Done"

    return chemin
开发者ID:geosas,项目名称:WPS_Process_SIGnature_target,代码行数:23,代码来源:get_wfs.py

示例10: get_features

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def get_features(wfs_url, layer, verbose=False):
    """Get feature from Web Feature Service (WFS) in GeoJSON format
    
    Input:
       wfs_url: URL for web feature service. E.g. http://www.aifdr.org:8080/geoserver/ows?
       layer: Feature layer name as <workspace>:<layer>
       verbose [optional]: Flag controlling the verbosity level. Default is False.
       
    Output:
       GEOJSON dictionary or None.
    """
    
    if verbose:
        print('Retrieving %s from %s' % (layer, wfs_url))
        
    wfs = WebFeatureService(wfs_url, version='1.0.0')
    
    if layer not in wfs.contents.keys():
        return None
    response = wfs.getfeature(typename=[layer], outputFormat='json', maxfeatures=1)
    return geojson.loads(response.read())
开发者ID:sabman,项目名称:gs-science,代码行数:23,代码来源:api.py

示例11: getMapunitFeaturesForBoundingBox

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def getMapunitFeaturesForBoundingBox(config, outputDir, bbox, tileBbox=False, t_srs='EPSG:4326'):
    """ Query USDA Soil Data Mart for SSURGO MapunitPolyExtended features with a given bounding box.
        Features will be written to one or more shapefiles, one file for each bboxTile tile,
        stored in the specified output directory. The filename will be returned as a string.
        Will fetch SSURGO tabular data (see ssurgolib.attributequery.ATTRIBUTE_LIST for a list
        of attributes) and join those data to the features in the final shapefiles(s).
    
        @note Will silently exit if features already exist.
    
        @param config onfigParser containing the section 'GDAL/OGR' and option 'PATH_OF_OGR2OGR'
        @param outputDir String representing the absolute/relative path of the directory into which features should be written
        @param bbox A dict containing keys: minX, minY, maxX, maxY, srs, where srs='EPSG:4326'
        @param tileBoundingBox True if bounding box should be tiled if extent exceeds featurequery.MAX_SSURGO_EXTENT
        @param t_srs String representing the spatial reference system of the output shapefiles, of the form 'EPSG:XXXX'
        
        @return A list of strings representing the name of the shapefile(s) to which the mapunit features were saved.
        
        @exception IOError if output directory is not a directory
        @exception IOError if output directory is not writable
        @exception Exception if bounding box area is greater than MAX_SSURGO_EXTENT
        @exception Exception if no MUKEYs were returned
    """
    if not os.path.isdir(outputDir):
        raise IOError(errno.ENOTDIR, "Output directory %s is not a directory" % (outputDir,))
    if not os.access(outputDir, os.W_OK):
        raise IOError(errno.EACCES, "Not allowed to write to output directory %s" % (outputDir,))
    outputDir = os.path.abspath(outputDir)

    typeName = 'MapunitPolyExtended'

    if tileBbox:
        bboxes = tileBoundingBox(bbox, MAX_SSURGO_EXTENT)
        sys.stderr.write("Dividing bounding box %s into %d tiles\n" % (str(bbox), len(bboxes)))
    else:
        if calculateBoundingBoxArea(bbox, t_srs) > MAX_SSURGO_EXTENT:
            raise Exception("Bounding box area is greater than %f sq. meters" % (MAX_SSURGO_EXTENT,))
        bboxes = [bbox]
    
    outFiles = []
    
    for bboxTile in bboxes:
        minX = bboxTile['minX']; minY = bboxTile['minY']; maxX = bboxTile['maxX']; maxY = bboxTile['maxY']
        bboxLabel = str(minX) + "_" + str(minY) + "_" + str(maxX) + "_" + str(maxY)
    
        gmlFilename = "%s_bbox_%s-attr.gml" % (typeName, bboxLabel)
        gmlFilepath = os.path.join(outputDir, gmlFilename)
    
        if not os.path.exists(gmlFilepath):
            sys.stderr.write("Fetching SSURGO data for sub bboxTile %s\n" % bboxLabel)
        
            wfs = WebFeatureService(WFS_URL, version='1.0.0')
            filter = "<Filter><BBOX><PropertyName>Geometry</PropertyName> <Box srsName='EPSG:4326'><coordinates>%f,%f %f,%f</coordinates> </Box></BBOX></Filter>" % (minX, minY, maxX, maxY)
            gml = wfs.getfeature(typename=(typeName,), filter=filter, propertyname=None)
    
            # Write intermediate GML to a file
            intGmlFilename = "%s_bbox_%s.gml" % (typeName, bboxLabel)
            intGmlFilepath = os.path.join(outputDir, intGmlFilename)
            out = open(intGmlFilepath, 'w')
            out.write(gml.read())
            out.close()
            
            # Parse GML to get list of MUKEYs
            gmlFile = open(intGmlFilepath, 'r')
            ssurgoFeatureHandler = SSURGOFeatureHandler()
            xml.sax.parse(gmlFile, ssurgoFeatureHandler)
            gmlFile.close()
            mukeys = ssurgoFeatureHandler.mukeys
            
            if len(mukeys) < 1:
                raise Exception("No SSURGO features returned from WFS query.  SSURGO GML format may have changed.\nPlease contact the developer.")
            
            # Get attributes (ksat, texture, %clay, %silt, and %sand) for all components in MUKEYS
            attributes = getParentMatKsatTexturePercentClaySiltSandForComponentsInMUKEYs(mukeys)
            
            # Compute weighted average of soil properties across all components in each map unit
            avgAttributes = computeWeightedAverageKsatClaySandSilt(attributes)
            
            # Convert GML to GeoJSON so that we can add fields easily (GDAL 1.10+ validates GML schema 
            #   and won't let us add fields)
            tmpGeoJSONFilename = convertGMLToGeoJSON(config, outputDir, intGmlFilepath, typeName)
            tmpGeoJSONFilepath = os.path.join(outputDir, tmpGeoJSONFilename)
            
            # Join map unit component-averaged soil properties to attribute table in GML file
#             gmlFile = open(intGmlFilepath, 'r')
#             joinedGmlStr = joinSSURGOAttributesToFeaturesByMUKEY(gmlFile, typeName, avgAttributes)
#             gmlFile.close()
            tmpGeoJSONFile = open(tmpGeoJSONFilepath, 'r')
            geojson = json.load(tmpGeoJSONFile)
            tmpGeoJSONFile.close()
            joinSSURGOAttributesToFeaturesByMUKEY_GeoJSON(geojson, typeName, avgAttributes)
            
            # Write Joined GeoJSON to a file
            out = open(tmpGeoJSONFilepath, 'w')
            json.dump(geojson, out)
            out.close()
            
            # Convert GeoJSON to shapefile
            filename = os.path.splitext(intGmlFilename)[0]
            shpFilename = convertGeoJSONToShapefile(config, outputDir, tmpGeoJSONFilepath, filename, t_srs=t_srs)
            
#.........这里部分代码省略.........
开发者ID:npp2016,项目名称:EcohydroLib,代码行数:103,代码来源:featurequery.py

示例12: WebFeatureService

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
from owslib.wfs import WebFeatureService
wfs11 = WebFeatureService(url='http://geoserv.weichand.de:8080/geoserver/wfs', version='1.1.0')
print(wfs11.identification.title)

[print(operation.name) for operation in wfs11.operations]

print(list(wfs11.contents))

response = wfs11.getfeature(typename='bvv:gmd_ex', bbox=(4500000,5500000,4500500,5500500), srsname='urn:x-ogc:def:crs:EPSG:31468')

out = open('/tmp/data.gml', 'wb')
out.write(bytes(response.read(), 'UTF-8'))
out.close()
开发者ID:bukun,项目名称:book_python_gis,代码行数:15,代码来源:g10_1_2_wfc.py

示例13: WebFeatureService

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
#!/usr/bin/python
# -*- coding: UTF-8 -*-
__author__ = "Juergen Weichand"


from owslib.wfs import WebFeatureService

wfs = WebFeatureService(url="http://geoserv.weichand.de:8080/geoserver/wfs", version="2.0.0", timeout=30)

# List StoredQueries
print("\nStoredQueries for %s" % wfs.identification.title)
for storedquery in wfs.storedqueries:
    print(storedquery.id, storedquery.title)

# List Parameter for a given StoredQuery
storedquery = wfs.storedqueries[5]
print("\nStoredQuery parameters for %s" % storedquery.id)
for parameter in storedquery.parameters:
    print(parameter.name, parameter.type)

# GetFeature StoredQuery
print("\nDownload data from %s" % wfs.identification.title)
response = wfs.getfeature(
    storedQueryID="GemeindeByGemeindeschluesselEpsg31468", storedQueryParams={"gemeindeschluessel": "09162000"}
)
out = open("/tmp/test-storedquery.gml", "wb")
out.write(response.read())
out.close()
print("... done")
开发者ID:pmdias,项目名称:OWSLib,代码行数:31,代码来源:wfs-wei-script.py

示例14: get_feature

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]
def get_feature(url, typename, features):
    """Return geometry for WFS server."""
    wfs = WebFeatureService(url, version='2.0.0')
    resp = wfs.getfeature([typename], featureid=features,
                          outputFormat='application/json')
    return json.loads(resp.read())
开发者ID:bird-house,项目名称:flyingpigeon,代码行数:8,代码来源:subset_base.py

示例15: WoudcClient

# 需要导入模块: from owslib.wfs import WebFeatureService [as 别名]
# 或者: from owslib.wfs.WebFeatureService import getfeature [as 别名]

#.........这里部分代码省略.........
                raise ValueError(msg)

            LOGGER.info('Setting temporal constraint')
            temporal_start = date2string(temporal[0], 'begin')
            temporal_end = date2string(temporal[1], 'end')

            constraints.append(fes.PropertyIsBetween(
                'instance_datetime', temporal_start, temporal_end))

        if sort_order not in ['asc', 'desc']:
            raise ValueError('sort_order must be asc or desc')
        else:
            if sort_order == 'desc':
                sort_descending = True

        if variables != '*':
            if not isinstance(variables, list):
                raise ValueError('variables must be list')

        if constraints:
            LOGGER.debug('Combining constraints')
            flt = fes.FilterRequest()
            if len(constraints) == 1:
                LOGGER.debug('Single constraint')
                filter_string = flt.setConstraint(constraints[0],
                                                  tostring=True)
            if len(constraints) > 1:
                LOGGER.debug('Multiple constraints')
                filter_string = flt.setConstraintList([constraints],
                                                      tostring=True)

        LOGGER.info('Fetching observations')
        LOGGER.info('Filters:')
        LOGGER.info('bbox: %r', bbox)
        LOGGER.info('temporal: %r', temporal)
        LOGGER.info('attribute query: %r = %r', property_name, property_value)

        # page download and assemble single list of JSON features
        while True:
            LOGGER.debug('Fetching features %d - %d',
                         startindex, startindex + self.maxfeatures)

            payload = self.server.getfeature(
                typename=typename,
                startindex=startindex,
                propertyname=variables,
                maxfeatures=self.maxfeatures,
                filter=filter_string,
                outputFormat=self.outputformat).read()

            LOGGER.debug('Processing response')
            if payload.isspace():
                LOGGER.debug('Empty response. Exiting')
                break

            try:
                features = json.loads(payload)
            except ValueError:
                msg = 'Query produced no results'
                LOGGER.info(msg)
                return None

            len_features = len(features['features'])

            LOGGER.debug('Found %d features', len_features)

            if feature_collection is None:
                feature_collection = features
            else:
                feature_collection['features'].extend(features['features'])

            if len_features < self.maxfeatures:
                break

            startindex = startindex + self.maxfeatures

        len_feature_collection = len(feature_collection['features'])
        LOGGER.info('Found %d total features', len_feature_collection)

        if sort_property is not None:
            LOGGER.info('Sorting response by %s', sort_property)
            feature_collection['features'].sort(
                key=lambda e: e['properties'][sort_property],
                reverse=sort_descending)

        return feature_collection

    def _get_metadata(self, typename, raw=False):
        """generic design pattern to download WOUDC metadata"""

        LOGGER.debug('Fetching data from server')
        features = self.server.getfeature(typename=typename,
                                          outputFormat=self.outputformat)

        LOGGER.debug('Processing response')
        if raw:
            LOGGER.info('Emitting raw GeoJSON response')
            return features.read()
        LOGGER.info('Emitting GeoJSON features as list')
        return json.loads(features.read())
开发者ID:tomkralidis,项目名称:pywoudc,代码行数:104,代码来源:__init__.py


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