Python psycopg2.extensions.parse_dsn() Examples

The following are 5 code examples of psycopg2.extensions.parse_dsn(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psycopg2.extensions , or try the search function .
Example #1
Source File: pgmigrate.py    From pgmigrate with PostgreSQL License 5 votes vote down vote up
def get_conn_id(conn):
    """
    Extract application_name from dsn
    """
    parsed = parse_dsn(conn.dsn)
    return parsed['application_name'] 
Example #2
Source File: dataframe.py    From a2ml with Apache License 2.0 5 votes vote down vote up
def load(self, features=None, nrows=None):
        self.categoricals = {}
        self.transforms_log = [[],[],[],[]]

        import csv
        from io import StringIO

        path = self.options['data_path']
        if isinstance(path, StringIO):
            path.seek(0)
            self.df = pd.read_csv(path, encoding='utf-8', escapechar="\\", usecols=features, na_values=['?'], nrows=nrows)
            if self.options.get("targetFeature") in self.df.columns:
                self.dropna([self.options["targetFeature"]])
        else:
            if path.startswith("jdbc:"):
                import psycopg2
                from psycopg2.extensions import parse_dsn
                path = path.replace('sslfactory=org.postgresql.ssl.NonValidatingFactory&', '')
                ary = path.split('tablename')
                path = ary[0]
                tablename = ary[1]
                dataset_name = tablename

                self.dbconn_args = parse_dsn(path[5:])
                conn = psycopg2.connect(**self.dbconn_args)
                self.df = pd.read_sql("select * from %s"%tablename, con=conn)
            else:
                path, remote_path = self._check_remote_path()
                try:
                    self.df = self.load_from_file(path, features=features, nrows=nrows)
                except:
                    if remote_path:
                        logging.exception("Loading local file failed. Download it again...")
                        self.options['data_path'] = remote_path
                        path, remote_path = self._check_remote_path(force_download=True)
                        self.df = self.load_from_file(path, features=features, nrows=nrows)
                    else:
                        raise

                self.dataset_name = os.path.basename(path)

            if self.options.get("targetFeature") in self.df.columns:
                self.dropna([self.options["targetFeature"]])
        return self 
Example #3
Source File: auto_db.py    From iopipe-python with Apache License 2.0 5 votes vote down vote up
def collect_psycopg2_metrics(context, trace, instance, args):
    try:
        from psycopg2.extensions import parse_dsn
    except ImportError:  # pragma: no cover
        from .dbapi import parse_dsn

    connection = instance.connection_proxy
    dsn = parse_dsn(connection.dsn)

    db = dsn.get("dbname")
    hostname = dsn.get("host", "localhost")
    port = dsn.get("port", 5432)

    command, table = None, None

    query = sqlparse.parse(instance.query)

    if not query and args:
        query = sqlparse.parse(args[0])

    if query:
        query = query[0]
        command = query.get_type()
        table = query.get_name()

    request = Request(
        command=ensure_utf8(command),
        key=None,
        hostname=ensure_utf8(hostname),
        port=ensure_utf8(port),
        connectionName=None,
        db=ensure_utf8(db),
        table=ensure_utf8(table),
    )
    request = request._asdict()
    context.iopipe.mark.db_trace(trace, "postgresql", request) 
Example #4
Source File: engine.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def _set_attributes_from_cursor(span: trace.Span, vendor, cursor):
    """Attempt to set db connection attributes by introspecting the cursor."""
    if vendor == "postgres":
        # pylint: disable=import-outside-toplevel
        from psycopg2.extensions import parse_dsn

        if hasattr(cursor, "connection") and hasattr(cursor.connection, "dsn"):
            dsn = getattr(cursor.connection, "dsn", None)
            if dsn:
                data = parse_dsn(dsn)
                span.set_attribute(_DB, data.get("dbname"))
                span.set_attribute(_HOST, data.get("host"))
                span.set_attribute(_PORT, int(data.get("port"))) 
Example #5
Source File: test_sa_engine.py    From aiopg with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_dsn(engine, pg_params):
    params = pg_params.copy()
    params['password'] = 'xxx'
    params['dbname'] = params.pop('database')
    params['port'] = str(params['port'])
    assert parse_dsn(engine.dsn) == params