Example #1
0
File: utils.py Project: pmav99/gst
def temp_mapset(*,
                mapset_name: Optional[str] = None,
                cleanup: bool = True) -> "ggis.Mapset":
    """
    Context manager that creates a temporary mapset which gets removed on exit.

    Parameters
    ----------

    mapset_name:
        The name of the temporary mapset. If it is not provided, then a random hex
        will be used (via `uuid.uuid4().hex`).

    cleanup:
        If `cleanup` is `False` then the mapset will not be removed when the wrapped
        function returns (useful for e.g. tests).

    """
    import grass.pygrass.gis as ggis

    if mapset_name is None:
        mapset_name = uuid.uuid4().hex
    ggis.make_mapset(mapset_name)
    ggis.set_current_mapset(mapset_name)
    temp_mapset = ggis.Mapset(mapset_name)
    try:
        yield temp_mapset
    finally:
        ggis.set_current_mapset("PERMANENT")
        if cleanup:
            # remove the test mapset
            temp_mapset.delete()
Example #2
0
 def setUpClass(cls):
     cls.org_mapset = Mapset()
     cls.tmp_mapset_name = tempname(10)
     make_mapset(mapset=cls.tmp_mapset_name)
     cls.tmp_mapset = Mapset(mapset=cls.tmp_mapset_name)
     cls.tmp_mapset.current()
     cls.tmp_mapset_path = cls.tmp_mapset.path()
Example #3
0
    def _set_grass(self, wps_request):
        """Handle given grass_location parameter of the constructor

        location is either directory name, 'epsg:1234' form or a georeferenced
        file

        in the first case, new temporary mapset within the location will be
        created

        in the second case, location will be created in self.workdir

        the mapset should be deleted automatically using self.clean() method
        """
        if self.grass_location:

            import random
            import string
            from grass.script import core as grass
            from grass.script import setup as gsetup

            # HOME needs to be set - and that is usually not the case for httpd
            # server
            os.environ['HOME'] = self.workdir

            # GISRC envvariable needs to be set
            gisrc = open(os.path.join(self.workdir, 'GISRC'), 'w')
            gisrc.write("GISDBASE: {}\n".format(self.workdir))
            gisrc.write("GUI: txt\n")
            gisrc.close()
            os.environ['GISRC'] = gisrc.name

            new_loc_args = dict()
            mapset_name = 'pywps_ms_{}'.format(''.join(
                random.sample(string.ascii_letters, 5)))

            if self.grass_location.startswith('complexinput:'):
                # create new location from a georeferenced file
                ref_file_parameter = self.grass_location.split(':')[1]
                ref_file = wps_request.inputs[ref_file_parameter][0].file
                new_loc_args.update({'filename': ref_file})
            elif self.grass_location.lower().startswith('epsg:'):
                # create new location from epsg code
                epsg = self.grass_location.lower().replace('epsg:', '')
                new_loc_args.update({'epsg': epsg})

            if new_loc_args:
                dbase = self.workdir
                location = str()
                while os.path.isdir(os.path.join(dbase, location)):
                    location = 'pywps_loc_{}'.format(''.join(
                        random.sample(string.ascii_letters, 5)))

                gsetup.init(os.environ['GISBASE'], dbase, location,
                            'PERMANENT')

                grass.create_location(dbase=dbase,
                                      location=location,
                                      **new_loc_args)
                LOGGER.debug('GRASS location based on {} created'.format(
                    list(new_loc_args.keys())[0]))
                grass.run_command('g.mapset',
                                  mapset=mapset_name,
                                  flags='c',
                                  dbase=dbase,
                                  location=location,
                                  quiet=True)

            # create temporary mapset within existing location
            elif os.path.isdir(self.grass_location):
                from grass.pygrass.gis import make_mapset

                LOGGER.debug('Temporary mapset will be created')

                dbase = os.path.dirname(self.grass_location)
                location = os.path.basename(self.grass_location)

                grass.run_command('g.gisenv', set="GISDBASE={}".format(dbase))
                grass.run_command('g.gisenv',
                                  set="LOCATION_NAME=%s" % location)

                while os.path.isdir(os.path.join(dbase, location,
                                                 mapset_name)):
                    mapset_name = 'pywps_ms_{}'.format(''.join(
                        random.sample(string.ascii_letters, 5)))
                make_mapset(mapset=mapset_name,
                            location=location,
                            gisdbase=dbase)
                grass.run_command('g.gisenv', set="MAPSET=%s" % mapset_name)

            else:
                raise NoApplicableCode(
                    'Location does exists or does not seem '
                    'to be in "EPSG:XXXX" form nor is it existing directory: {}'
                    .format(location))

            # set _grass_mapset attribute - will be deleted once handler ends
            self._grass_mapset = mapset_name

            # final initialization
            LOGGER.debug('GRASS Mapset set to {}'.format(mapset_name))

            LOGGER.debug('GRASS environment initialised')
            LOGGER.debug(
                'GISRC {}, GISBASE {}, GISDBASE {}, LOCATION {}, MAPSET {}'.
                format(os.environ.get('GISRC'), os.environ.get('GISBASE'),
                       dbase, location, os.path.basename(mapset_name)))
Example #4
0
    def _set_grass(self, wps_request):
        """Handle given grass_location parameter of the constructor

        location is either directory name, 'epsg:1234' form or a georeferenced
        file

        in the first case, new temporary mapset within the location will be
        created

        in the second case, location will be created in self.workdir

        the mapset should be deleted automatically using self.clean() method
        """
        if self.grass_location:

            import random
            import string
            from grass.script import core as grass
            from grass.script import setup as gsetup

            # HOME needs to be set - and that is usually not the case for httpd
            # server
            os.environ['HOME'] = self.workdir

            # GISRC envvariable needs to be set
            gisrc = open(os.path.join(self.workdir, 'GISRC'), 'w')
            gisrc.write("GISDBASE: {}\n".format(self.workdir))
            gisrc.write("GUI: txt\n")
            gisrc.close()
            os.environ['GISRC'] = gisrc.name

            new_loc_args = dict()
            mapset_name = 'pywps_ms_{}'.format(
                ''.join(random.sample(string.ascii_letters, 5)))

            if self.grass_location.startswith('complexinput:'):
                # create new location from a georeferenced file
                ref_file_parameter = self.grass_location.split(':')[1]
                ref_file = wps_request.inputs[ref_file_parameter][0].file
                new_loc_args.update({'filename': ref_file})
            elif self.grass_location.lower().startswith('epsg:'):
                # create new location from epsg code
                epsg = self.grass_location.lower().replace('epsg:', '')
                new_loc_args.update({'epsg': epsg})

            if new_loc_args:
                dbase = self.workdir
                location = str()
                while os.path.isdir(os.path.join(dbase, location)):
                    location = 'pywps_loc_{}'.format(
                        ''.join(random.sample(string.ascii_letters, 5)))

                gsetup.init(os.environ['GISBASE'], dbase,
                            location, 'PERMANENT')

                grass.create_location(dbase=dbase,
                                      location=location,
                                      **new_loc_args)
                LOGGER.debug('GRASS location based on {} created'.format(
                    list(new_loc_args.keys())[0]))
                grass.run_command('g.mapset',
                                  mapset=mapset_name,
                                  flags='c',
                                  dbase=dbase,
                                  location=location,
                                  quiet=True)

            # create temporary mapset within existing location
            elif os.path.isdir(self.grass_location):
                from grass.pygrass.gis import make_mapset

                LOGGER.debug('Temporary mapset will be created')

                dbase = os.path.dirname(self.grass_location)
                location = os.path.basename(self.grass_location)

                grass.run_command('g.gisenv', set="GISDBASE={}".format(dbase))
                grass.run_command('g.gisenv', set="LOCATION_NAME=%s" % location)

                while os.path.isdir(os.path.join(dbase, location, mapset_name)):
                    mapset_name = 'pywps_ms_{}'.format(
                        ''.join(random.sample(string.ascii_letters, 5)))
                make_mapset(mapset=mapset_name, location=location,
                            gisdbase=dbase)
                grass.run_command('g.gisenv', set="MAPSET=%s" % mapset_name)

            else:
                raise NoApplicableCode('Location does exists or does not seem '
                                       'to be in "EPSG:XXXX" form nor is it existing directory: {}'.format(location))

            # set _grass_mapset attribute - will be deleted once handler ends
            self._grass_mapset = mapset_name

            # final initialization
            LOGGER.debug('GRASS Mapset set to {}'.format(mapset_name))

            LOGGER.debug('GRASS environment initialised')
            LOGGER.debug('GISRC {}, GISBASE {}, GISDBASE {}, LOCATION {}, MAPSET {}'.format(
                         os.environ.get('GISRC'), os.environ.get('GISBASE'),
                         dbase, location, os.path.basename(mapset_name)))