OWSLib中PropertyIsEqualTo构建Filter时URL畸形问题求助
使用OWSLib构造WFS过滤器请求时出现URL畸形的解决方法
在使用OWSLib的fes.PropertyIsEqualTo构造过滤器,从WFS服务获取JSON格式要素时,生成的请求URL出现畸形,触发org.xml.sax.SAXParseException异常。通过getGETGetFeatureRequest查看发现PropertyIsEqualTo对象未正确生成过滤字符串,尝试FilterRequest也得到相同结果。
原代码
from owslib.wfs import WebFeatureService, Authentication from owslib.fes import PropertyIsEqualTo auth = Authentication() auth.verify = False wfs2 = WebFeatureService(url="https://geoserver.car.gov.br/geoserver/sicar/ows", headers={'Cache-Control': 'no-cache'}, auth=auth, version='1.1.0' ) car = 'MT-5103700-92A39DC62FDF4D88874F218D41BE1C7F' filter_car = PropertyIsEqualTo('cod_imovel', car); wfs2.getfeature(typename='sicar:sicar_imoveis_mt', filter=filter_car, outputFormat='json');
错误信息
Traceback (most recent call last): File "/home/gabrielubuntu/repos/pygeogis/app.py", line 15, in <module> print(wfs2.getfeature(typename='sicar:sicar_imoveis_mt', filter=filter_car, outputFormat='json')) File "/home/gabrielubuntu/repos/pygeogis/.venv/lib/python3.10/site-packages/owslib/feature/wfs110.py", line 348, in getfeature u = openURL(base_url, data, method, timeout=self.timeout, File "/home/gabrielubuntu/repos/pygeogis/.venv/lib/python3.10/site-packages/owslib/util.py", line 235, in openURL raise ServiceException('\n'.join([t.strip() for t in serviceException.itertext() if t.strip()])) owslib.util.ServiceException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 38; Attribute name "object" associated with an element type "owslib.fes.PropertyIsEqualTo" must be followed by the ' = ' character. Attribute name "object" associated with an element type "owslib.fes.PropertyIsEqualTo" must be followed by the ' = ' character.
异常URL
https://geoserver.car.gov.br/geoserver/sicar/wfs?service=WFS&version=1.1.0&request=GetFeature&query=%3Cowslib.fes.PropertyIsEqualTo+object+at+0x7feb355cff70%3E&typename=sicar%3Asicar_imoveis_mt&outputFormat=json
问题原因
WFS 1.1.0版本的getfeature方法要求传入XML格式的过滤字符串,而非直接传入PropertyIsEqualTo对象。原代码直接传递对象时,OWSLib错误地将对象的字符串表示(如<owslib.fes.PropertyIsEqualTo object at 0x...>)作为过滤参数拼接到URL中,导致服务端解析XML时出错。
修正后的代码
from owslib.wfs import WebFeatureService, Authentication from owslib.fes import PropertyIsEqualTo, Filter auth = Authentication() auth.verify = False wfs2 = WebFeatureService(url="https://geoserver.car.gov.br/geoserver/sicar/ows", headers={'Cache-Control': 'no-cache'}, auth=auth, version='1.1.0' ) car = 'MT-5103700-92A39DC62FDF4D88874F218D41BE1C7F' # 明确指定参数名,避免位置参数歧义 filter_car = PropertyIsEqualTo(propertyname='cod_imovel', literal=car) # 将过滤器包装为Filter对象并生成合法的XML字符串 filter_xml = Filter([filter_car]).toXML() # 传入XML格式的过滤器发起请求 response = wfs2.getfeature(typename='sicar:sicar_imoveis_mt', filter=filter_xml, outputFormat='json') # 读取响应内容 print(response.read())
补充说明
- 建议明确指定
PropertyIsEqualTo的参数名(propertyname和literal),避免因位置参数顺序导致的潜在问题。 - 如果使用WFS 2.0.0版本,API接口会有差异,可直接传入过滤器对象,但需要确保服务端支持对应版本。
内容的提问来源于stack exchange,提问作者Gabriel Ferrari
相关产品推荐
相关产品推荐

