v.in.wfs.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. #!/usr/bin/env python
  2. ############################################################################
  3. #
  4. # MODULE: v.in.wfs
  5. # AUTHOR(S): Markus Neteler. neteler itc it
  6. # Hamish Bowman
  7. # Converted to Python by Glynn Clements
  8. # PURPOSE: WFS support
  9. # COPYRIGHT: (C) 2006-2012 Markus Neteler and the GRASS Development Team
  10. #
  11. # This program is free software under the GNU General
  12. # Public License (>=v2). Read the file COPYING that
  13. # comes with GRASS for details.
  14. #
  15. # GetFeature example:
  16. # http://mapserver.gdf-hannover.de/cgi-bin/grassuserwfs?REQUEST=GetFeature&SERVICE=WFS&VERSION=1.0.0
  17. #############################################################################
  18. #
  19. # TODO: suggest to depend on the OWSLib for OGC web service needs
  20. # http://pypi.python.org/pypi/OWSLib
  21. #
  22. #%Module
  23. #% description: Imports GetFeature from a WFS server.
  24. #% keyword: vector
  25. #% keyword: import
  26. #% keyword: OGC web services
  27. #%end
  28. #%option
  29. #% key: url
  30. #% type: string
  31. #% description: Base URL starting with 'http' and ending in '?'
  32. #% required: yes
  33. #%end
  34. #%option G_OPT_V_OUTPUT
  35. #%end
  36. #%option
  37. #% key: name
  38. #% type: string
  39. #% description: Comma separated names of data layers to download
  40. #% multiple: yes
  41. #% required: no
  42. #%end
  43. #%option
  44. #% key: srs
  45. #% type: string
  46. #% label: Specify alternate spatial reference system (example: EPSG:4326)
  47. #% description: The given code must be supported by the server, consult the capabilities file
  48. #% required: no
  49. #%end
  50. #%option
  51. #% key: maximum_features
  52. #% type: integer
  53. #% label: Maximum number of features to download
  54. #% description: (default: unlimited)
  55. #%end
  56. #%option
  57. #% key: start_index
  58. #% type: integer
  59. #% label: Skip earlier feature IDs and start downloading at this one
  60. #% description: (default: start with the first feature)
  61. #%end
  62. #%flag
  63. #% key: l
  64. # todo #% description: List available layers and exit
  65. #% description: Download server capabilities to 'wms_capabilities.xml' in the current directory and exit
  66. #% suppress_required: yes
  67. #%end
  68. #%flag
  69. #% key: r
  70. #% description: Restrict fetch to features which touch the current region
  71. #%end
  72. import os
  73. import sys
  74. from grass.script.utils import try_remove
  75. from grass.script import core as grass
  76. try:
  77. from urllib2 import urlopen, URLError, HTTPError
  78. except ImportError:
  79. from urllib.request import urlopen
  80. from urllib.error import URLError, HTTPError
  81. # i18N
  82. import gettext
  83. gettext.install('grassmods', os.path.join(os.getenv("GISBASE"), 'locale'))
  84. def main():
  85. out = options['output']
  86. wfs_url = options['url']
  87. request_base = 'REQUEST=GetFeature&SERVICE=WFS&VERSION=1.0.0'
  88. wfs_url += request_base
  89. if options['name']:
  90. wfs_url += '&TYPENAME=' + options['name']
  91. if options['srs']:
  92. wfs_url += '&SRS=' + options['srs']
  93. if options['maximum_features']:
  94. wfs_url += '&MAXFEATURES=' + options['maximum_features']
  95. if int(options['maximum_features']) < 1:
  96. # GTC Invalid WFS maximum features parameter
  97. grass.fatal(_("Invalid maximum number of features"))
  98. if options['start_index']:
  99. wfs_url += '&STARTINDEX=' + options['start_index']
  100. if int(options['start_index']) < 1:
  101. # GTC Invalid WFS start index parameter
  102. grass.fatal(_('Features begin with index "1"'))
  103. if flags['r']:
  104. bbox = grass.read_command("g.region", flags='w').split('=')[1]
  105. wfs_url += '&BBOX=' + bbox
  106. if flags['l']:
  107. wfs_url = options['url'] + 'REQUEST=GetCapabilities&SERVICE=WFS&VERSION=1.0.0'
  108. tmp = grass.tempfile()
  109. tmpxml = tmp + '.xml'
  110. grass.debug(wfs_url)
  111. # GTC Downloading WFS features
  112. grass.message(_("Retrieving data..."))
  113. try:
  114. inf = urlopen(wfs_url)
  115. except HTTPError as e:
  116. # GTC WFS request HTTP failure
  117. grass.fatal(_("The server couldn't fulfill the request.\nError code: %s") % e.code)
  118. except URLError as e:
  119. # GTC WFS request network failure
  120. grass.fatal(_("Failed to reach the server.\nReason: %s") % e.reason)
  121. outf = file(tmpxml, 'wb')
  122. while True:
  123. s = inf.read()
  124. if not s:
  125. break
  126. outf.write(s)
  127. inf.close()
  128. outf.close()
  129. if flags['l']:
  130. import shutil
  131. if os.path.exists('wms_capabilities.xml'):
  132. grass.fatal(_('A file called "wms_capabilities.xml" already exists here'))
  133. # os.move() might fail if the temp file is on another volume, so we copy instead
  134. shutil.copy(tmpxml, 'wms_capabilities.xml')
  135. try_remove(tmpxml)
  136. sys.exit(0)
  137. grass.message(_("Importing data..."))
  138. try:
  139. grass.run_command('v.in.ogr', flags='o', input=tmpxml, output=out)
  140. grass.message(_("Vector map <%s> imported from WFS.") % out)
  141. except:
  142. grass.message(_("WFS import failed"))
  143. finally:
  144. try_remove(tmpxml)
  145. if __name__ == "__main__":
  146. options, flags = grass.parser()
  147. main()