示例#1
0
    def __init__(self):
        self.c = 0

        gws.ensure_dir(TMP_DIR)

        self.services = {
            'wms': {
                'image_formats': ['image/png'],
                'max_output_pixels': [9000, 9000]
            },
            'wmts': {
                'kvp': True,
                'restful': False
            }
        }

        self.globals = {
            # https://mapproxy.org/docs/1.11.0/configuration.html#id14
            # "By default MapProxy assumes lat/long (north/east) order for all geographic and x/y (east/north) order for all projected SRS."
            # we need to change that because our extents are always x/y (lon/lat) even if a CRS says otherwise
            'srs': {
                'axis_order_en': ['EPSG:4326']
            },
            'cache': {
                'base_dir': gws.MAPPROXY_CACHE_DIR,
                'lock_dir': TMP_DIR + '/locks_' + gws.random_string(16),
                'tile_lock_dir': TMP_DIR + '/tile_locks_' + gws.random_string(16),
                'concurrent_tile_creators': 1,
                'max_tile_limit': 5000,

            },
            'image': {
                'resampling_method': 'bicubic',
                'stretch_factor': 1.15,
                'max_shrink_factor': 4.0,

                'formats': {
                    'png8': {
                        'format': 'image/png',
                        'mode': 'P',
                        'colors': 256,
                        'transparent': True,
                        'resampling_method': 'bicubic',
                    },
                    'png24': {
                        'format': 'image/png',
                        'mode': 'RGBA',
                        'colors': 0,
                        'transparent': True,
                        'resampling_method': 'bicubic',
                    }

                }
            }
        }

        self.cfg = {}
示例#2
0
    def api_import(self, req: gws.IWebRequest, p: ImportParams) -> StatusResponse:
        try:
            rec = gws.lib.upload.get(p.uploadUid)
        except gws.lib.upload.Error as e:
            gws.log.error(e)
            raise gws.base.web.error.BadRequest()

        job_uid = gws.random_string(64)

        args = {
            'actionUid': self.uid,
            'auUid': self._check_au(req, p.auUid),
            'path': rec.path,
            'replace': p.replace,
        }

        job = gws.lib.job.create(
            uid=job_uid,
            user=req.user,
            args=gws.lib.json2.to_string(args),
            worker=__name__ + '._worker')

        gws.server.spool.add(job)

        return StatusResponse(
            jobUid=job.uid,
            state=job.state,
        )
示例#3
0
def run(action,
        src_path: str,
        replace: bool,
        au_uid: str = None,
        job: gws.lib.job.Job = None) -> Stats:
    """"Import bplan data from a file or a directory."""

    tmp_dir = None

    if os2.is_file(src_path):
        # a file is given - unpack it into a temp dir
        tmp_dir = gws.ensure_dir(gws.TMP_DIR + '/bplan_' +
                                 gws.random_string(32))
        _extract(src_path, tmp_dir)

    stats = None

    try:
        stats = _run2(action, tmp_dir or src_path, replace, au_uid, job)
    except gws.lib.job.PrematureTermination as e:
        pass

    if tmp_dir:
        shutil.rmtree(tmp_dir)

    return stats
示例#4
0
    def create(self, method_uid, typ, provider_uid, user_uid, str_user, str_data=''):
        uid = gws.random_string(64)

        with self._connection as conn:
            conn.execute('''INSERT
                INTO sess(
                    uid,
                    method_uid,
                    typ,
                    provider_uid,
                    user_uid,
                    str_user,
                    str_data,
                    created,
                    updated
                )
                VALUES(?,?,?,?,?,?,?,?,?)
            ''', [
                uid,
                method_uid,
                typ,
                provider_uid,
                user_uid,
                str_user,
                str_data,
                gws.lib.date.timestamp(),
                gws.lib.date.timestamp()
            ])

        gws.log.debug('session: created:', uid)
        return uid
示例#5
0
def from_string(s, **opts):
    fname = '/vsimem/' + gws.random_string(64)
    osgeo.gdal.FileFromMemBuffer(fname, s)

    ds = osgeo.gdal.OpenEx(fname, **opts)
    yield ds
    del ds
    osgeo.gdal.Unlink(fname)
示例#6
0
def store_in_web_cache(url: str, img: bytes):
    path = gws.WEB_CACHE_DIR + url
    dirname = os.path.dirname(path)
    tmp = dirname + '/' + gws.random_string(64)
    try:
        os.makedirs(dirname, 0o755, exist_ok=True)
        gws.write_file_b(tmp, img)
        os.rename(tmp, path)
    except OSError:
        gws.log.warn(f'store_in_web_cache FAILED path={path!r}')
示例#7
0
    def server_select(self, sql, params=None):
        uid = 'cur' + gws.random_string(32)
        cnames = None

        self.exec('BEGIN')
        try:
            with self.conn.cursor() as cur:
                self._exec(cur, f'DECLARE {uid} CURSOR FOR {sql}', params)
                while True:
                    self._exec(cur, f'FETCH FORWARD {self.itersize} FROM {uid}')
                    rs = cur.fetchall()
                    if not rs:
                        break
                    if not cnames:
                        cnames = [c.name for c in cur.description]
                    for rec in rs:
                        yield dict(zip(cnames, rec))
        finally:
            if self.conn:
                self.exec('COMMIT')
示例#8
0
    def configure(self):
        

        self.crs = self.var('crs')
        self.db = t.cast(
            gws.ext.db.provider.postgres.Object,
            gws.base.db.require_provider(self, 'gws.ext.db.provider.postgres'))

        self.templates: t.List[gws.ITemplate] = gws.base.template.bundle(self, self.var('templates'))
        self.qgis_template: gws.ITemplate = gws.base.template.find(self.templates, subject='bplan.qgis')
        self.info_template: gws.ITemplate = gws.base.template.find(self.templates, subject='bplan.info')

        self.plan_table = self.db.configure_table(self.var('planTable'))
        self.meta_table = self.db.configure_table(self.var('metaTable'))
        self.data_dir = self.var('dataDir')

        self.au_list = self.var('administrativeUnits')
        self.type_list = self.var('planTypes')
        self.image_quality = self.var('imageQuality')

        p = self.var('exportDataModel')
        self.export_data_model: t.Optional[gws.IDataModel] = self.create_child('gws.base.model', p) if p else None

        for sub in 'png', 'pdf', 'cnv', 'qgs':
            gws.ensure_dir(self.data_dir + '/' + sub)

        self.key_col = 'plan_id'
        self.au_key_col = 'ags'
        self.au_name_col = 'gemeinde'
        self.type_col = 'typ'
        self.time_col = 'rechtskr'
        self.x_coord_col = 'utm_ost'
        self.y_coord_col = 'utm_nord'

        gws.write_file(_RELOAD_FILE, gws.random_string(16))
        self.root.application.monitor.add_path(_RELOAD_FILE)
示例#9
0
def shape_to_fragment(shape: gws.IShape,
                      view: gws.MapView,
                      style: gws.IStyle = None,
                      label: str = None) -> t.List[gws.XmlElement]:
    if not shape:
        return []

    geom = t.cast(gws.gis.shape.Shape, shape).geom
    if geom.is_empty:
        return []

    trans = gws.gis.render.map_view_transformer(view)
    geom = shapely.ops.transform(trans, geom)

    if not style:
        return [_geometry(geom)]

    sv = style.values
    with_geometry = sv.with_geometry == 'all'
    with_label = label and _is_label_visible(view, sv)
    gt = _geom_type(geom)

    text = None
    if with_label:
        extra_y_offset = 0
        if sv.label_offset_y is None:
            if gt == _TYPE_POINT:
                extra_y_offset = 12
            if gt == _TYPE_LINESTRING:
                extra_y_offset = 6
        text = _label(geom, label, sv, extra_y_offset)

    marker = None
    marker_id = None
    if with_geometry and sv.marker:
        marker_id = '_M' + gws.random_string(8)
        marker = _marker(marker_id, sv)

    icon = None
    atts: dict = {}
    if with_geometry and sv.icon:
        res = _parse_icon(sv.icon, view.dpi)
        if res:
            el, w, h = res
            x, y, w, h = _icon_size_position(geom, sv, w, h)
            atts = {
                'x': f'{int(x)}',
                'y': f'{int(y)}',
                'width': f'{int(w)}',
                'height': f'{int(h)}',
            }
            icon = xml2.element(name=el.name,
                                attributes=gws.merge(el.attributes, atts),
                                children=el.children)

    body = None
    if with_geometry:
        _add_paint_atts(atts, sv)
        if marker:
            atts['marker-start'] = atts['marker-mid'] = atts[
                'marker-end'] = f'url(#{marker_id})'
        if gt == _TYPE_POINT or gt == _TYPE_MULTIPOINT:
            atts['r'] = (sv.point_size or DEFAULT_POINT_SIZE) // 2
        if gt == _TYPE_LINESTRING or gt == _TYPE_MUTLILINESTRING:
            atts['fill'] = 'none'
        body = _geometry(geom, atts)

    return gws.compact([marker, body, icon, text])
示例#10
0
 def signal_reload(self, source):
     gws.log.debug(f'bplan reload signal {source!r}')
     gws.write_file(_RELOAD_FILE, gws.random_string(16))