示例#1
0
    def _clearSslTempCertsIfAny(self, connectionInfo):
        # remove certs (if any) of the connectionInfo
        expandedUri = QgsDataSourceUri(connectionInfo)

        def removeCert(certFile):
            certFile = certFile.replace("'", "")
            file = QFile(certFile)
            # set permission to allow removing on Win.
            # On linux and Mac if file is set with QFile::>ReadUser
            # does not create problem removing certs
            if not file.setPermissions(QFile.WriteOwner):
                raise Exception('Cannot change permissions on {}: error code: {}'.format(file.fileName(), file.error()))
            if not file.remove():
                raise Exception('Cannot remove {}: error code: {}'.format(file.fileName(), file.error()))

        sslCertFile = expandedUri.param("sslcert")
        if sslCertFile:
            removeCert(sslCertFile)

        sslKeyFile = expandedUri.param("sslkey")
        if sslKeyFile:
            removeCert(sslKeyFile)

        sslCAFile = expandedUri.param("sslrootcert")
        if sslCAFile:
            removeCert(sslCAFile)
示例#2
0
    def testWfsSettings(self):
        uri = QgsDataSourceUri()
        QgsOwsConnection.addWfsConnectionSettings(uri, 'qgis/connections-wfs/test/')

        self.assertEqual(uri.param('version'), '1.1.0')
        self.assertEqual(uri.param('maxNumFeatures'), '47')
        self.assertEqual(uri.param('IgnoreAxisOrientation'), '1')
        self.assertEqual(uri.param('InvertAxisOrientation'), '1')
示例#3
0
    def testWfsSettings(self):
        uri = QgsDataSourceUri()
        QgsOwsConnection.addWfsConnectionSettings(
            uri, 'qgis/connections-wfs/test/')

        self.assertEqual(uri.param('version'), '1.1.0')
        self.assertEqual(uri.param('maxNumFeatures'), '47')
        self.assertEqual(uri.param('IgnoreAxisOrientation'), '1')
        self.assertEqual(uri.param('InvertAxisOrientation'), '1')
示例#4
0
    def testWmsSettings(self):
        uri = QgsDataSourceUri()
        QgsOwsConnection.addWmsWcsConnectionSettings(uri, 'qgis/connections-wms/test/')

        self.assertEqual(uri.httpHeader('referer'), 'my_ref')
        self.assertEqual(uri.param('IgnoreGetMapUrl'), '1')
        self.assertEqual(uri.param('IgnoreGetFeatureInfoUrl'), '1')
        self.assertEqual(uri.param('SmoothPixmapTransform'), '1')
        self.assertEqual(uri.param('dpiMode'), '4')
        self.assertEqual(uri.param('IgnoreAxisOrientation'), '1')
        self.assertEqual(uri.param('InvertAxisOrientation'), '1')
def getWFSScriptTag(layer, layerName):
    layerSource = layer.source()
    if ("retrictToRequestBBOX" in layerSource or
            "restrictToRequestBBOX" in layerSource):
        provider = layer.dataProvider()
        uri = QgsDataSourceUri(provider.dataSourceUri())
        wfsURL = uri.param("url")
        wfsTypename = uri.param("typename")
        wfsSRS = uri.param("srsname")
        layerSource = wfsURL
        layerSource += "?SERVICE=WFS&VERSION=1.0.0&"
        layerSource += "REQUEST=GetFeature&TYPENAME="
        layerSource += wfsTypename
        layerSource += "&SRSNAME="
        layerSource += wfsSRS
    scriptTag = re.sub(r'SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:4326', layerSource)
    scriptTag += "&outputFormat=text%2Fjavascript&format_options=callback%3A"
    scriptTag += "get" + layerName + "Json"
    return scriptTag
示例#6
0
def getWFSScriptTag(layer, layerName):
    layerSource = layer.source()
    if ("retrictToRequestBBOX" in layerSource
            or "restrictToRequestBBOX" in layerSource):
        provider = layer.dataProvider()
        uri = QgsDataSourceUri(provider.dataSourceUri())
        wfsURL = uri.param("url")
        wfsTypename = uri.param("typename")
        wfsSRS = uri.param("srsname")
        layerSource = wfsURL
        layerSource += "?SERVICE=WFS&VERSION=1.0.0&"
        layerSource += "REQUEST=GetFeature&TYPENAME="
        layerSource += wfsTypename
        layerSource += "&SRSNAME="
        layerSource += wfsSRS
    scriptTag = re.sub(r'SRSNAME\=EPSG\:\d+', 'SRSNAME=EPSG:4326', layerSource)
    scriptTag += "&outputFormat=text%2Fjavascript&format_options=callback%3A"
    scriptTag += "get" + layerName + "Json"
    return scriptTag
示例#7
0
def writeScriptIncludes(layers, json, matchCRS):
    geojsonVars = ""
    wfsVars = ""
    styleVars = ""
    for count, (layer, encode2json) in enumerate(zip(layers, json)):
        vts = layer.customProperty("VectorTilesReader/vector_tile_url")
        sln = safeName(layer.name()) + "_" + unicode(count)
        if layer.type() == layer.VectorLayer:
            if layer.providerType() != "WFS" or encode2json:
                if vts is None:
                    geojsonVars += ('<script src="layers/%s"></script>' %
                                    (sln + ".js"))
            else:
                layerSource = layer.source()
                if ("retrictToRequestBBOX" in layerSource or
                        "restrictToRequestBBOX" in layerSource):
                    provider = layer.dataProvider()
                    uri = QgsDataSourceUri(provider.dataSourceUri())
                    wfsURL = uri.param("url")
                    wfsTypename = uri.param("typename")
                    wfsSRS = uri.param("srsname")
                    layerSource = wfsURL
                    layerSource += "?SERVICE=WFS&VERSION=1.0.0&"
                    layerSource += "REQUEST=GetFeature&TYPENAME="
                    layerSource += wfsTypename
                    layerSource += "&SRSNAME="
                    layerSource += wfsSRS
                if not matchCRS:
                    layerSource = re.sub(r'SRSNAME\=EPSG\:\d+',
                                         'SRSNAME=EPSG:3857',
                                         layerSource)
                layerSource += "&outputFormat=text%2Fjavascript&"
                layerSource += "format_options=callback%3A"
                layerSource += "get" + sln + "Json"
                wfsVars += ('<script src="%s"></script>' % layerSource)
            if vts is not None:
                sln = safeName(vts)
            styleVars += ('<script src="styles/%s_style.js">'
                          '</script>' % sln)
    return (geojsonVars, wfsVars, styleVars)
def writeScriptIncludes(layers, json, matchCRS):
    geojsonVars = ""
    wfsVars = ""
    styleVars = ""
    for count, (layer, encode2json) in enumerate(zip(layers, json)):
        vts = layer.customProperty("VectorTilesReader/vector_tile_url")
        sln = safeName(layer.name()) + "_" + unicode(count)
        if layer.type() == layer.VectorLayer:
            if layer.providerType() != "WFS" or encode2json:
                if vts is None:
                    geojsonVars += ('<script src="layers/%s"></script>' %
                                    (sln + ".js"))
            else:
                layerSource = layer.source()
                if ("retrictToRequestBBOX" in layerSource
                        or "restrictToRequestBBOX" in layerSource):
                    provider = layer.dataProvider()
                    uri = QgsDataSourceUri(provider.dataSourceUri())
                    wfsURL = uri.param("url")
                    wfsTypename = uri.param("typename")
                    wfsSRS = uri.param("srsname")
                    layerSource = wfsURL
                    layerSource += "?SERVICE=WFS&VERSION=1.0.0&"
                    layerSource += "REQUEST=GetFeature&TYPENAME="
                    layerSource += wfsTypename
                    layerSource += "&SRSNAME="
                    layerSource += wfsSRS
                if not matchCRS:
                    layerSource = re.sub(r'SRSNAME\=EPSG\:\d+',
                                         'SRSNAME=EPSG:3857', layerSource)
                layerSource += "&outputFormat=text%2Fjavascript&"
                layerSource += "format_options=callback%3A"
                layerSource += "get" + sln + "Json"
                wfsVars += ('<script src="%s"></script>' % layerSource)
            if vts is not None:
                sln = safeName(vts)
            styleVars += ('<script src="styles/%s_style.js">'
                          '</script>' % sln)
    return (geojsonVars, wfsVars, styleVars)
示例#9
0
    def testWmsSettings(self):
        uri = QgsDataSourceUri()
        QgsOwsConnection.addWmsWcsConnectionSettings(uri, 'qgis/connections-wms/test/')

        self.assertEqual(uri.param('referer'), 'my_ref')
        self.assertEqual(uri.param('IgnoreGetMapUrl'), '1')
        self.assertEqual(uri.param('IgnoreGetFeatureInfoUrl'), '1')
        self.assertEqual(uri.param('SmoothPixmapTransform'), '1')
        self.assertEqual(uri.param('dpiMode'), '4')
        self.assertEqual(uri.param('IgnoreAxisOrientation'), '1')
        self.assertEqual(uri.param('InvertAxisOrientation'), '1')
示例#10
0
    def filename(self) -> str:
        """Returns the filename of the file if the layer is file based. E.g. GPKG, CSV, but not PostGIS, WFS

        Note: This may return garbage path, e.g. on online layers such as PostGIS or WFS. Always check with os.path.isfile(),
        as Path.is_file() raises an exception prior to Python 3.8
        """
        metadata = self.metadata
        filename = ""

        if self.layer.type() == QgsMapLayer.VectorTileLayer:
            uri = QgsDataSourceUri()
            uri.setEncodedUri(self.layer.source())
            return uri.param("url")
        elif self.layer.dataProvider() is None:
            return ""

        filename = metadata.get("path", "")
        path_resolver = self.project.pathResolver()
        resolved_filename = path_resolver.writePath(filename)
        if resolved_filename.startswith("localized:"):
            return resolved_filename[10:]

        return filename
示例#11
0
    def getOgrCompatibleSource(self, parameter_name, parameters, context,
                               feedback, executing):
        """
        Interprets a parameter as an OGR compatible source and layer name
        :param executing:
        """
        if not executing and parameter_name in parameters and isinstance(
                parameters[parameter_name],
                QgsProcessingFeatureSourceDefinition):
            # if not executing, then we throw away all 'selected features only' settings
            # since these have no meaning for command line gdal use, and we don't want to force
            # an export of selected features only to a temporary file just to show the command!
            parameters = {parameter_name: parameters[parameter_name].source}

        input_layer = self.parameterAsVectorLayer(parameters, parameter_name,
                                                  context)
        ogr_data_path = None
        ogr_layer_name = None
        if input_layer is None or input_layer.dataProvider().name(
        ) == 'memory':
            if executing:
                # parameter is not a vector layer - try to convert to a source compatible with OGR
                # and extract selection if required
                ogr_data_path = self.parameterAsCompatibleSourceLayerPath(
                    parameters,
                    parameter_name,
                    context,
                    QgsVectorFileWriter.supportedFormatExtensions(),
                    QgsVectorFileWriter.supportedFormatExtensions()[0],
                    feedback=feedback)
                ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
            else:
                #not executing - don't waste time converting incompatible sources, just return dummy strings
                #for the command preview (since the source isn't compatible with OGR, it has no meaning anyway and can't
                #be run directly in the command line)
                ogr_data_path = 'path_to_data_file'
                ogr_layer_name = 'layer_name'
        elif input_layer.dataProvider().name() == 'ogr':
            if executing and (isinstance(parameters[parameter_name], QgsProcessingFeatureSourceDefinition) and parameters[parameter_name].selectedFeaturesOnly) \
                    or input_layer.subsetString():
                # parameter is a vector layer, with OGR data provider
                # so extract selection if required
                ogr_data_path = self.parameterAsCompatibleSourceLayerPath(
                    parameters,
                    parameter_name,
                    context,
                    QgsVectorFileWriter.supportedFormatExtensions(),
                    feedback=feedback)
                parts = QgsProviderRegistry.instance().decodeUri(
                    'ogr', ogr_data_path)
                ogr_data_path = parts['path']
                if 'layerName' in parts and parts['layerName']:
                    ogr_layer_name = parts['layerName']
                else:
                    ogr_layer_name = GdalUtils.ogrLayerName(ogr_data_path)
            else:
                #either not using the selection, or
                #not executing - don't worry about 'selected features only' handling. It has no meaning
                #for the command line preview since it has no meaning outside of a QGIS session!
                ogr_data_path = GdalUtils.ogrConnectionStringAndFormatFromLayer(
                    input_layer)[0]
                ogr_layer_name = GdalUtils.ogrLayerName(
                    input_layer.dataProvider().dataSourceUri())
        elif input_layer.dataProvider().name().lower() == 'wfs':
            uri = QgsDataSourceUri(input_layer.source())
            baseUrl = uri.param('url').split('?')[0]
            ogr_data_path = "WFS:{}".format(baseUrl)
            ogr_layer_name = uri.param('typename')
        else:
            # vector layer, but not OGR - get OGR compatible path
            # TODO - handle "selected features only" mode!!
            ogr_data_path = GdalUtils.ogrConnectionStringFromLayer(input_layer)
            ogr_layer_name = GdalUtils.ogrLayerName(
                input_layer.dataProvider().dataSourceUri())
        return ogr_data_path, ogr_layer_name
示例#12
0
    def __init__(self, uri):
        DBConnector.__init__(self, uri)

        self.host = uri.host() or os.environ.get('PGHOST')
        self.port = uri.port() or os.environ.get('PGPORT')

        username = uri.username() or os.environ.get('PGUSER')
        password = uri.password() or os.environ.get('PGPASSWORD')

        # Do not get db and user names from the env if service is used
        if uri.service() is None:
            if username is None:
                username = os.environ.get('USER')
            self.dbname = uri.database() or os.environ.get('PGDATABASE') or username
            uri.setDatabase(self.dbname)

        expandedConnInfo = self._connectionInfo()
        try:
            self.connection = psycopg2.connect(expandedConnInfo.encode('utf-8'))
        except self.connection_error_types() as e:
            err = unicode(e)
            uri = self.uri()
            conninfo = uri.connectionInfo(False)

            for i in range(3):
                (ok, username, password) = QgsCredentials.instance().get(conninfo, username, password, err)
                if not ok:
                    raise ConnectionError(e)

                if username:
                    uri.setUsername(username)

                if password:
                    uri.setPassword(password)

                newExpandedConnInfo = uri.connectionInfo(True)
                try:
                    self.connection = psycopg2.connect(newExpandedConnInfo.encode('utf-8'))
                    QgsCredentials.instance().put(conninfo, username, password)
                except self.connection_error_types() as e:
                    if i == 2:
                        raise ConnectionError(e)

                    err = unicode(e)
                finally:
                    # remove certs (if any) of the expanded connectionInfo
                    expandedUri = QgsDataSourceUri(newExpandedConnInfo)

                    sslCertFile = expandedUri.param("sslcert")
                    if sslCertFile:
                        sslCertFile = sslCertFile.replace("'", "")
                        os.remove(sslCertFile)

                    sslKeyFile = expandedUri.param("sslkey")
                    if sslKeyFile:
                        sslKeyFile = sslKeyFile.replace("'", "")
                        os.remove(sslKeyFile)

                    sslCAFile = expandedUri.param("sslrootcert")
                    if sslCAFile:
                        sslCAFile = sslCAFile.replace("'", "")
                        os.remove(sslCAFile)
        finally:
            # remove certs (if any) of the expanded connectionInfo
            expandedUri = QgsDataSourceUri(expandedConnInfo)

            sslCertFile = expandedUri.param("sslcert")
            if sslCertFile:
                sslCertFile = sslCertFile.replace("'", "")
                os.remove(sslCertFile)

            sslKeyFile = expandedUri.param("sslkey")
            if sslKeyFile:
                sslKeyFile = sslKeyFile.replace("'", "")
                os.remove(sslKeyFile)

            sslCAFile = expandedUri.param("sslrootcert")
            if sslCAFile:
                sslCAFile = sslCAFile.replace("'", "")
                os.remove(sslCAFile)

        self.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

        c = self._execute(None, u"SELECT current_user,current_database()")
        self.user, self.dbname = self._fetchone(c)
        self._close_cursor(c)

        self._checkSpatial()
        self._checkRaster()
        self._checkGeometryColumnsTable()
        self._checkRasterColumnsTable()
示例#13
0
文件: GdalUtils.py 项目: zyhgit/QGIS
    def ogrConnectionStringAndFormatFromLayer(layer):
        provider = layer.dataProvider().name()
        if provider == 'spatialite':
            # dbname='/geodata/osm_ch.sqlite' table="places" (Geometry) sql=
            regex = re.compile("dbname='(.+)'")
            r = regex.search(str(layer.source()))
            ogrstr = r.groups()[0]
            format = 'SQLite'
        elif provider == 'postgres':
            # dbname='ktryjh_iuuqef' host=spacialdb.com port=9999
            # user='******' password='******' sslmode=disable
            # key='gid' estimatedmetadata=true srid=4326 type=MULTIPOLYGON
            # table="t4" (geom) sql=
            dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
            conninfo = dsUri.connectionInfo()
            conn = None
            ok = False
            while not conn:
                try:
                    conn = psycopg2.connect(dsUri.connectionInfo())
                except psycopg2.OperationalError:
                    (ok, user, passwd) = QgsCredentials.instance().get(
                        conninfo, dsUri.username(), dsUri.password())
                    if not ok:
                        break

                    dsUri.setUsername(user)
                    dsUri.setPassword(passwd)

            if not conn:
                raise RuntimeError(
                    'Could not connect to PostgreSQL database - check connection info'
                )

            if ok:
                QgsCredentials.instance().put(conninfo, user, passwd)

            ogrstr = "PG:%s" % dsUri.connectionInfo()
            format = 'PostgreSQL'
        elif provider == 'mssql':
            # 'dbname=\'db_name\' host=myHost estimatedmetadata=true
            # srid=27700 type=MultiPolygon table="dbo"."my_table"
            # #(Shape) sql='
            dsUri = layer.dataProvider().uri()
            ogrstr = 'MSSQL:'
            ogrstr += 'database={0};'.format(dsUri.database())
            ogrstr += 'server={0};'.format(dsUri.host())
            if dsUri.username() != "":
                ogrstr += 'uid={0};'.format(dsUri.username())
            else:
                ogrstr += 'trusted_connection=yes;'
            if dsUri.password() != '':
                ogrstr += 'pwd={0};'.format(dsUri.password())
            ogrstr += 'tables={0}'.format(dsUri.table())
            format = 'MSSQL'
        elif provider == "oracle":
            # OCI:user/password@host:port/service:table
            dsUri = QgsDataSourceUri(layer.dataProvider().dataSourceUri())
            ogrstr = "OCI:"
            if dsUri.username() != "":
                ogrstr += dsUri.username()
                if dsUri.password() != "":
                    ogrstr += "/" + dsUri.password()
                delim = "@"

            if dsUri.host() != "":
                ogrstr += delim + dsUri.host()
                delim = ""
                if dsUri.port() != "" and dsUri.port() != '1521':
                    ogrstr += ":" + dsUri.port()
                ogrstr += "/"
                if dsUri.database() != "":
                    ogrstr += dsUri.database()
            elif dsUri.database() != "":
                ogrstr += delim + dsUri.database()

            if ogrstr == "OCI:":
                raise RuntimeError(
                    'Invalid oracle data source - check connection info')

            ogrstr += ":"
            if dsUri.schema() != "":
                ogrstr += dsUri.schema() + "."

            ogrstr += dsUri.table()
            format = 'OCI'
        elif provider.lower() == "wfs":
            uri = QgsDataSourceUri(layer.source())
            baseUrl = uri.param('url').split('?')[0]
            ogrstr = "WFS:{}".format(baseUrl)
            format = 'WFS'
        else:
            ogrstr = str(layer.source()).split("|")[0]
            path, ext = os.path.splitext(ogrstr)
            format = QgsVectorFileWriter.driverForExtension(ext)

        return ogrstr, '"' + format + '"'
示例#14
0
    def __init__(self, uri):
        DBConnector.__init__(self, uri)

        self.host = uri.host() or os.environ.get('PGHOST')
        self.port = uri.port() or os.environ.get('PGPORT')

        username = uri.username() or os.environ.get('PGUSER')
        password = uri.password() or os.environ.get('PGPASSWORD')

        # Do not get db and user names from the env if service is used
        if uri.service() is None:
            if username is None:
                username = os.environ.get('USER')
            self.dbname = uri.database() or os.environ.get(
                'PGDATABASE') or username
            uri.setDatabase(self.dbname)

        expandedConnInfo = self._connectionInfo()
        try:
            self.connection = psycopg2.connect(
                expandedConnInfo.encode('utf-8'))
        except self.connection_error_types() as e:
            err = unicode(e)
            uri = self.uri()
            conninfo = uri.connectionInfo(False)

            for i in range(3):
                (ok, username, password) = QgsCredentials.instance().get(
                    conninfo, username, password, err)
                if not ok:
                    raise ConnectionError(e)

                if username:
                    uri.setUsername(username)

                if password:
                    uri.setPassword(password)

                newExpandedConnInfo = uri.connectionInfo(True)
                try:
                    self.connection = psycopg2.connect(
                        newExpandedConnInfo.encode('utf-8'))
                    QgsCredentials.instance().put(conninfo, username, password)
                except self.connection_error_types() as e:
                    if i == 2:
                        raise ConnectionError(e)

                    err = unicode(e)
                finally:
                    # remove certs (if any) of the expanded connectionInfo
                    expandedUri = QgsDataSourceUri(newExpandedConnInfo)

                    sslCertFile = expandedUri.param("sslcert")
                    if sslCertFile:
                        sslCertFile = sslCertFile.replace("'", "")
                        os.remove(sslCertFile)

                    sslKeyFile = expandedUri.param("sslkey")
                    if sslKeyFile:
                        sslKeyFile = sslKeyFile.replace("'", "")
                        os.remove(sslKeyFile)

                    sslCAFile = expandedUri.param("sslrootcert")
                    if sslCAFile:
                        sslCAFile = sslCAFile.replace("'", "")
                        os.remove(sslCAFile)
        finally:
            # remove certs (if any) of the expanded connectionInfo
            expandedUri = QgsDataSourceUri(expandedConnInfo)

            sslCertFile = expandedUri.param("sslcert")
            if sslCertFile:
                sslCertFile = sslCertFile.replace("'", "")
                os.remove(sslCertFile)

            sslKeyFile = expandedUri.param("sslkey")
            if sslKeyFile:
                sslKeyFile = sslKeyFile.replace("'", "")
                os.remove(sslKeyFile)

            sslCAFile = expandedUri.param("sslrootcert")
            if sslCAFile:
                sslCAFile = sslCAFile.replace("'", "")
                os.remove(sslCAFile)

        self.connection.set_isolation_level(
            psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

        c = self._execute(None, u"SELECT current_user,current_database()")
        self.user, self.dbname = self._fetchone(c)
        self._close_cursor(c)

        self._checkSpatial()
        self._checkRaster()
        self._checkGeometryColumnsTable()
        self._checkRasterColumnsTable()
示例#15
0
    def __init__(self, host=None, port=None, dbname=None, user=None,
                 passwd=None, service=None, uri=None):
        # Regular expression for identifiers without need to quote them
        self.re_ident_ok = re.compile(r"^\w+$")
        port = str(port)

        if uri:
            self.uri = uri
        else:
            self.uri = QgsDataSourceUri()
            if service:
                self.uri.setConnection(service, dbname, user, passwd)
            else:
                self.uri.setConnection(host, port, dbname, user, passwd)

        conninfo = self.uri.connectionInfo(False)
        err = None
        for i in range(4):
            expandedConnInfo = self.uri.connectionInfo(True)
            try:
                self.con = psycopg2.connect(expandedConnInfo)
                if err is not None:
                    QgsCredentials.instance().put(conninfo,
                                                  self.uri.username(),
                                                  self.uri.password())
                break
            except psycopg2.OperationalError as e:
                if i == 3:
                    raise QgsProcessingException(str(e))

                err = str(e)
                user = self.uri.username()
                password = self.uri.password()
                (ok, user, password) = QgsCredentials.instance().get(conninfo,
                                                                     user,
                                                                     password,
                                                                     err)
                if not ok:
                    raise QgsProcessingException(QCoreApplication.translate("PostGIS", 'Action canceled by user'))
                if user:
                    self.uri.setUsername(user)
                if password:
                    self.uri.setPassword(password)
            finally:
                # remove certs (if any) of the expanded connectionInfo
                expandedUri = QgsDataSourceUri(expandedConnInfo)

                sslCertFile = expandedUri.param("sslcert")
                if sslCertFile:
                    sslCertFile = sslCertFile.replace("'", "")
                    os.remove(sslCertFile)

                sslKeyFile = expandedUri.param("sslkey")
                if sslKeyFile:
                    sslKeyFile = sslKeyFile.replace("'", "")
                    os.remove(sslKeyFile)

                sslCAFile = expandedUri.param("sslrootcert")
                if sslCAFile:
                    sslCAFile = sslCAFile.replace("'", "")
                    os.remove(sslCAFile)

        self.has_postgis = self.check_postgis()
示例#16
0
文件: postgis.py 项目: gpsbird/QGIS
    def __init__(self,
                 host=None,
                 port=None,
                 dbname=None,
                 user=None,
                 passwd=None,
                 service=None,
                 uri=None):
        # Regular expression for identifiers without need to quote them
        self.re_ident_ok = re.compile(r"^\w+$")
        port = str(port)

        if uri:
            self.uri = uri
        else:
            self.uri = QgsDataSourceUri()
            if service:
                self.uri.setConnection(service, dbname, user, passwd)
            else:
                self.uri.setConnection(host, port, dbname, user, passwd)

        conninfo = self.uri.connectionInfo(False)
        err = None
        for i in range(4):
            expandedConnInfo = self.uri.connectionInfo(True)
            try:
                self.con = psycopg2.connect(expandedConnInfo)
                if err is not None:
                    QgsCredentials.instance().put(conninfo,
                                                  self.uri.username(),
                                                  self.uri.password())
                break
            except psycopg2.OperationalError as e:
                if i == 3:
                    raise DbError(str(e))

                err = str(e)
                user = self.uri.username()
                password = self.uri.password()
                (ok, user, password) = QgsCredentials.instance().get(
                    conninfo, user, password, err)
                if not ok:
                    raise DbError(
                        QCoreApplication.translate("PostGIS",
                                                   'Action canceled by user'))
                if user:
                    self.uri.setUsername(user)
                if password:
                    self.uri.setPassword(password)
            finally:
                # remove certs (if any) of the expanded connectionInfo
                expandedUri = QgsDataSourceUri(expandedConnInfo)

                sslCertFile = expandedUri.param("sslcert")
                if sslCertFile:
                    sslCertFile = sslCertFile.replace("'", "")
                    os.remove(sslCertFile)

                sslKeyFile = expandedUri.param("sslkey")
                if sslKeyFile:
                    sslKeyFile = sslKeyFile.replace("'", "")
                    os.remove(sslKeyFile)

                sslCAFile = expandedUri.param("sslrootcert")
                if sslCAFile:
                    sslCAFile = sslCAFile.replace("'", "")
                    os.remove(sslCAFile)

        self.has_postgis = self.check_postgis()
示例#17
0
    def addWms(self, wms_name, url, layers, mime_type, epsg_code, protocol):
        """
            # Slot for exposing the same-name function to Javascript. #
            Adding the WMS to the QGis TOC.
            :param wms_name: The WMS name to add in TOC as group
            :type wms_name: str
            :param url: The WMS URL
            :type url: str
            :param layers: The list of the WMS layers to add
            :type layers: list of str
            :param mime_type: The image MIME TYPE (e.g. image/png)
            :type mime_type: str
            :param epsg_code: The EPSG code (e.g. the number 32632)
            :type epsg_code: int
            :param protocol: The protocol (i.e. should be 'ba' for applying basic authentication). Not yet managed.
            :type protocol: str
        """
        qgs_logger = QgsApplication.messageLog()
        qgs_logger.logMessage('addWms: wms_name = {}'.format(wms_name),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('addWms: url = {}'.format(url),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('addWms: layers = {}'.format(layers),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('addWms: mime_type = {}'.format(mime_type),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('addWms: epsg_code = {}'.format(epsg_code),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('addWms: protocol = {}'.format(protocol),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)

        # For storing the URI data
        uri = QgsDataSourceUri()

        # Split the host with the request data
        pieces = url.split("?")
        if len(pieces) == 1:
            qgs_logger.logMessage('len(pieces) == 1',
                                  tag=configuration.LOGGER_TAG,
                                  level=Qgis.Info)
        elif len(pieces) == 2:
            qgs_logger.logMessage('len(pieces) == 2',
                                  tag=configuration.LOGGER_TAG,
                                  level=Qgis.Info)
            # Overriding the URL
            url = "{}{}".format(pieces[0], "?")
            parameters_values = pieces[1].split("=")
            if len(parameters_values) == 2:
                qgs_logger.logMessage('len(parameters) == 2',
                                      tag=configuration.LOGGER_TAG,
                                      level=Qgis.Info)
                uri.setParam(parameters_values[0], parameters_values[1])
                qgs_logger.logMessage('uri.param({}): {}'.format(
                    parameters_values[0], uri.param(parameters_values[0])),
                                      tag=configuration.LOGGER_TAG,
                                      level=Qgis.Info)
            else:
                qgs_logger.logMessage('len(p) != 2',
                                      tag=configuration.LOGGER_TAG,
                                      level=Qgis.Info)
        else:
            qgs_logger.logMessage('len(pieces) > 2 Not yet managed!',
                                  tag=configuration.LOGGER_TAG,
                                  level=Qgis.Warning)

        # Setting the URL to the URI
        uri.setParam("url", url)

        # Process the layers accordingly if just an element or a list of elements
        layers_list = []
        if "," in layers:
            layers_list = layers.split(",")
        else:
            layers_list.append(layers)

        # Setting the parameter 'layers' in the URI
        for val in layers_list:
            uri.setParam("layers", val)

        # Setting the other parameters
        # Styles seems required: https://gis.stackexchange.com/questions/183485/load-wms-with-pyqgis
        uri.setParam("styles", "")
        uri.setParam("format", mime_type)
        uri.setParam("crs", "EPSG:{}".format(epsg_code))

        # https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/loadlayer.html#raster-layers
        # Ignore GetCoverage URL advertised by GetCapabilities. May be necessary if a server is not configured properly.
        uri.setParam("IgnoreGetMapUrl", "1")

        # Adding the parameters for the basic authentication
        qgs_logger.logMessage('Applying Basic-Authentication',
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        uri.setParam("username", self.session_user)
        uri.setParam("password", self.session_password)

        # Logging the parameters for debugging
        qgs_logger.logMessage('uri.param(url): {}'.format(uri.param("url")),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('uri.param(layers): {}'.format(
            uri.param("layers")),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('uri.param(format): {}'.format(
            uri.param("format")),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('uri.param(crs): {}'.format(uri.param("crs")),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('uri.service(): {}'.format(uri.service()),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('encodedUri: {}'.format(str(uri.encodedUri())),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)
        qgs_logger.logMessage('uri.uri(): {}'.format(uri.uri()),
                              tag=configuration.LOGGER_TAG,
                              level=Qgis.Info)

        # Generating the WMS layer
        wms_layer = QgsRasterLayer(str(uri.encodedUri()), wms_name, 'wms')

        # If the WMS is correctly generated, add to the QGis TOC
        if wms_layer.isValid():
            QgsProject.instance().addMapLayer(wms_layer)
        else:
            qgs_logger.logMessage(
                'Impossibile aggiungere il WMS: {}'.format(wms_name),
                tag=configuration.LOGGER_TAG,
                level=Qgis.Warning)
            self.show_message(
                "Attenzione!",
                "Impossibile aggiungere il WMS " + wms_name + " al progetto")