Python psycopg2.__version__() Examples

The following are 21 code examples of psycopg2.__version__(). 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 , or try the search function .
Example #1
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check6_bsddb3(self):
        '''bsddb3 - Python Bindings for Oracle Berkeley DB

        requires Berkeley DB

        PY_BSDDB3_VER_MIN = (6, 0, 1) # 6.x series at least
        '''
        self.append_text("\n")
        # Start check

        try:
            import bsddb3 as bsddb
            bsddb_str = bsddb.__version__  # Python adaptation layer
            # Underlying DB library
            bsddb_db_str = str(bsddb.db.version()).replace(', ', '.')\
                .replace('(', '').replace(')', '')
        except ImportError:
            bsddb_str = 'not found'
            bsddb_db_str = 'not found'

        result = ("* Berkeley Database library (bsddb3: " + bsddb_db_str +
                  ") (Python-bsddb3 : " + bsddb_str + ")")
        # End check
        self.append_text(result) 
Example #2
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check_fontconfig(self):
        ''' The python-fontconfig library is used to support the Genealogical
        Symbols tab of the Preferences.  Without it Genealogical Symbols don't
        work '''
        try:
            import fontconfig
            vers = fontconfig.__version__
            if vers.startswith("0.5."):
                result = ("* python-fontconfig " + vers +
                          " (Success version 0.5.x is installed.)")
            else:
                result = ("* python-fontconfig " + vers +
                          " (Requires version 0.5.x)")
        except ImportError:
            result = "* python-fontconfig Not found, (Requires version 0.5.x)"
        # End check
        self.append_text(result)

    #Optional 
Example #3
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 6 votes vote down vote up
def check23_pedigreechart(self):
        '''PedigreeChart - Can optionally use - NumPy if installed

        https://github.com/gramps-project/addons-source/blob/master/PedigreeChart/PedigreeChart.py
        '''
        self.append_text("\n")
        self.render_text("""<b>03. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=PedigreeChart">"""
                         """Addon:PedigreeChart</a> :</b> """)
        # Start check

        try:
            import numpy
            numpy_ver = str(numpy.__version__)
            #print("numpy.__version__ :" + numpy_ver )
            # NUMPY_check = True
        except ImportError:
            numpy_ver = "Not found"
            # NUMPY_check = False

        result = "(NumPy : " + numpy_ver + " )"
        # End check
        self.append_text(result)
        #self.append_text("\n") 
Example #4
Source File: config.py    From ldap2pg with PostgreSQL License 6 votes vote down vote up
def __call__(self, parser, *a):
        version = (
            "%(package)s %(version)s\n"
            "psycopg2 %(psycopg2version)s\n"
            "python-ldap %(ldapversion)s\n"
            "Python %(pyversion)s\n"
        ) % dict(
            package=__package__,
            version=__version__,
            psycopg2version=psycopg2.__version__,
            pyversion=sys.version,
            ldapversion=ldap.__version__,

        )
        print(version.strip())
        parser.exit() 
Example #5
Source File: version.py    From temboard with PostgreSQL License 6 votes vote down vote up
def inspect_versions():
    from alembic import __version__ as alembic_version
    from psycopg2 import __version__ as psycopg2_version
    from tornado import version as tornado_version
    from sqlalchemy import __version__ as sqlalchemy_version

    with open('/etc/os-release') as fo:
        distinfos = parse_lsb_release(fo)

    return dict(
        temboard=__version__,
        alembic=alembic_version,
        psycopg2=psycopg2_version,
        python=python_version(),
        pythonbin=sys.executable,
        tornado=tornado_version,
        sqlalchemy=sqlalchemy_version,
        distname=distinfos['NAME'],
        distversion=distinfos['VERSION'],
    ) 
Example #6
Source File: setup_database.py    From scrapydweb with GNU General Public License v3.0 5 votes vote down vote up
def setup_mysql(username, password, host, port):
    """
    ModuleNotFoundError: No module named 'MySQLdb'
    pip install mysqlclient
    Python 2: pip install mysqlclient -> MySQLdb/_mysql.c(29) :
    fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory
    https://stackoverflow.com/questions/51294268/pip-install-mysqlclient-returns-fatal-error-c1083-cannot-open-file-mysql-h
    https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient
    pip install "path to the downloaded mysqlclient.whl file"
    """
    require_version = '0.9.3'  # Dec 18, 2018
    install_command = "pip install --upgrade pymysql"
    try:
        import pymysql
        assert pymysql.__version__ >= require_version, install_command
    except (ImportError, AssertionError):
        sys.exit("Run command: %s" % install_command)
    else:
        # Run scrapydweb: ModuleNotFoundError: No module named 'MySQLdb'
        pymysql.install_as_MySQLdb()

    conn = pymysql.connect(host=host, port=int(port), user=username, password=password,
                           charset='utf8', cursorclass=pymysql.cursors.DictCursor)
    cur = conn.cursor()
    for dbname in DBS:
        if SCRAPYDWEB_TESTMODE:
            drop_database(cur, dbname)
        # pymysql.err.ProgrammingError: (1007, "Can't create database 'scrapydweb_apscheduler'; database exists")
        # cur.execute("CREATE DATABASE IF NOT EXISTS %s CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'" % dbname)
        try:
            cur.execute("CREATE DATABASE %s CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'" % dbname)
        except Exception as err:
            if 'exists' in str(err):
                pass
            else:
                raise
    cur.close()
    conn.close() 
Example #7
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_correct_extraction_psycopg2_version(self):
        from django.db.backends.postgresql.base import psycopg2_version
        with mock.patch('psycopg2.__version__', '4.2.1 (dt dec pq3 ext lo64)'):
            self.assertEqual(psycopg2_version(), (4, 2, 1))
        with mock.patch('psycopg2.__version__', '4.2b0.dev1 (dt dec pq3 ext lo64)'):
            self.assertEqual(psycopg2_version(), (4, 2)) 
Example #8
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_connect_isolation_level(self):
        """
        The transaction level can be configured with
        DATABASES ['OPTIONS']['isolation_level'].
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )
        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close() 
Example #9
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_correct_extraction_psycopg2_version(self):
        from django.db.backends.postgresql.base import psycopg2_version
        with mock.patch('psycopg2.__version__', '4.2.1 (dt dec pq3 ext lo64)'):
            self.assertEqual(psycopg2_version(), (4, 2, 1))
        with mock.patch('psycopg2.__version__', '4.2b0.dev1 (dt dec pq3 ext lo64)'):
            self.assertEqual(psycopg2_version(), (4, 2)) 
Example #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_connect_isolation_level(self):
        """
        The transaction level can be configured with
        DATABASES ['OPTIONS']['isolation_level'].
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )
        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close() 
Example #11
Source File: _requires.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def GetPrerequisites(info=False):
  try:
    import psycopg2
    if psycopg2.__version__ > "2.4":
      return "psycopg2 csv"
    else:
      if info:
        print "psycopg2 too old"
  except:
    if info:
      print "psycopg2 missing"
    pass
  return None 
Example #12
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_correct_extraction_psycopg2_version(self):
        from django.db.backends.postgresql.base import psycopg2_version
        version_path = 'django.db.backends.postgresql.base.Database.__version__'

        with mock.patch(version_path, '2.6.9'):
            self.assertEqual(psycopg2_version(), (2, 6, 9))

        with mock.patch(version_path, '2.5.dev0'):
            self.assertEqual(psycopg2_version(), (2, 5)) 
Example #13
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_connect_isolation_level(self):
        """
        Regression test for #18130 and #24318.
        """
        import psycopg2
        from psycopg2.extensions import (
            ISOLATION_LEVEL_READ_COMMITTED as read_committed,
            ISOLATION_LEVEL_SERIALIZABLE as serializable,
        )

        # Since this is a django.test.TestCase, a transaction is in progress
        # and the isolation level isn't reported as 0. This test assumes that
        # PostgreSQL is configured with the default isolation level.

        # Check the level on the psycopg2 connection, not the Django wrapper.
        default_level = read_committed if psycopg2.__version__ < '2.7' else None
        self.assertEqual(connection.connection.isolation_level, default_level)

        new_connection = connection.copy()
        new_connection.settings_dict['OPTIONS']['isolation_level'] = serializable
        try:
            # Start a transaction so the isolation level isn't reported as 0.
            new_connection.set_autocommit(False)
            # Check the level on the psycopg2 connection, not the Django wrapper.
            self.assertEqual(new_connection.connection.isolation_level, serializable)
        finally:
            new_connection.close() 
Example #14
Source File: test_lobject.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def _has_lo64(conn):
    """Return (bool, msg) about the lo64 support"""
    if conn.server_version < 90300:
        return (False, "server version %s doesn't support the lo64 API"
                % conn.server_version)

    if 'lo64' not in psycopg2.__version__:
        return (False, "this psycopg build doesn't support the lo64 API")

    return (True, "this server and build support the lo64 API") 
Example #15
Source File: postgresql.py    From gprime with GNU General Public License v2.0 5 votes vote down vote up
def get_summary(cls):
        """
        Return a diction of information about this database
        backend.
        """
        summary = {
            "DB-API version": "2.0",
            "Database SQL type": cls.__name__,
            "Database SQL module": "psycopg2",
            "Database SQL module version": psycopg2.__version__,
            "Database SQL module location": psycopg2.__file__,
        }
        return summary 
Example #16
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def check17_pillow(self):
        '''PILLOW
        Allows Production of jpg images from non-jpg images in LaTeX documents

        #TODO prculley mentions that : And PIL (Pillow) is also used by the
        main Gramps ([]narrativeweb and []other reports for image cropping)
        as well as [x]editexifmetadata and the
        new [x]latexdoc type addons (genealogytree).

        #TODO add check for PILLOW to "gramps -v"  section

        https://github.com/gramps-project/gramps/blob/maintenance/gramps50/gramps/plugins/docgen/latexdoc.py
        '''
        #self.append_text("\n")
        # Start check

        try:
            import PIL
            # from PIL import Image
            try:
                pil_ver = PIL.__version__
            except Exception:
                try:
                    pil_ver = str(PIL.PILLOW_VERSION)
                except Exception:
                    try:
                        #print(dir(PIL))
                        pil_ver = str(PIL.VERSION)
                    except Exception:
                        pil_ver = "Installed but does not supply version"
        except ImportError:
            pil_ver = "Not found"

        result = "(PILLOW " + pil_ver + ")"
        # End check
        self.append_text(result) 
Example #17
Source File: postgresql.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def get_summary(self):
        """
        Return a diction of information about this database
        backend.
        """
        summary = super().get_summary()
        summary.update({
            _("Database version"): psycopg2.__version__,
            _("Database module location"): psycopg2.__file__,
        })
        return summary 
Example #18
Source File: setup_database.py    From scrapydweb with GNU General Public License v3.0 4 votes vote down vote up
def setup_postgresql(username, password, host, port):
    """
    https://github.com/my8100/notes/blob/master/back_end/the-flask-mega-tutorial.md
    When working with database servers such as MySQL and PostgreSQL,
    you have to create the database in the database server before running upgrade.
    """
    require_version = '2.7.7'  # Jan 23, 2019
    install_command = "pip install --upgrade psycopg2"
    try:
        import psycopg2
        assert psycopg2.__version__ >= require_version, install_command
    except (ImportError, AssertionError):
        sys.exit("Run command: %s" % install_command)

    conn = psycopg2.connect(host=host, port=int(port), user=username, password=password)
    conn.set_isolation_level(0)  # https://wiki.postgresql.org/wiki/Psycopg2_Tutorial
    cur = conn.cursor()
    for dbname in DBS:
        if SCRAPYDWEB_TESTMODE:
            # database "scrapydweb_apscheduler" is being accessed by other users
            # DETAIL:  There is 1 other session using the database.
            # To restart postgres server on Windonws -> win+R: services.msc
            drop_database(cur, dbname)

        # https://www.postgresql.org/docs/9.0/sql-createdatabase.html
        # https://stackoverflow.com/questions/9961795/
        # utf8-postgresql-create-database-like-mysql-including-character-set-encoding-a

        # psycopg2.ProgrammingError: invalid locale name: "en_US.UTF-8"
        # https://stackoverflow.com/questions/40673339/
        # creating-utf-8-database-in-postgresql-on-windows10

        # cur.execute("CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE 'en-US' LC_CTYPE 'en-US'" % dbname)
        # psycopg2.DataError: new collation (en-US) is incompatible with the collation of the template database
        # (Chinese (Simplified)_People's Republic of China.936)
        # HINT:  Use the same collation as in the template database, or use template0 as template.
        try:
            cur.execute("CREATE DATABASE %s ENCODING 'UTF8' LC_COLLATE 'en_US.UTF-8' LC_CTYPE 'en_US.UTF-8'" % dbname)
        except:
            try:
                cur.execute("CREATE DATABASE %s" % dbname)
            except Exception as err:
                # psycopg2.ProgrammingError: database "scrapydweb_apscheduler" already exists
                if 'exists' in str(err):
                    pass
                else:
                    raise
    cur.close()
    conn.close() 
Example #19
Source File: config.py    From ldap2pg with PostgreSQL License 4 votes vote down vote up
def load(self, argv=None):
        # argv processing.
        logger.debug("Processing CLI arguments.")
        parser = ArgumentParser(
            add_help=False,
            # Only store value from argv. Defaults are managed by
            # Configuration.
            argument_default=SUPPRESS_ARG,
            description="PostgreSQL roles and privileges management.",
            epilog=self.EPILOG,
        )
        define_arguments(parser)
        args = parser.parse_args(sys.argv[1:] if argv is None else argv)

        # Setup logging before parsing options. Reset verbosity with env var,
        # and compute verbosity from cumulated args.
        args.verbosity[0] = V.VERBOSITIES.index(self['verbosity'])
        self['verbosity'] = V.verbosity(args.verbosity)
        if hasattr(args, 'color'):
            self['color'] = args.color
        dictConfig(self.logging_dict())

        logger.info("Starting ldap2pg %s.", __version__)

        # File loading.
        filename, mode = self.find_filename(os.environ, args)
        if filename == '-':
            logger.info("Reading configuration from stdin.")
            file_config = self.read(sys.stdin, 'stdin', mode)
        else:
            logger.info("Using %s.", filename)
            try:
                with open(filename, encoding='utf-8') as fo:
                    file_config = self.read(fo, filename, mode)
            except OSError as e:
                msg = "Failed to read configuration: %s" % (e,)
                raise UserError(msg)

        V.alias(
            file_config.get('postgres', {}),
            'roles_blacklist_query', 'blacklist',
        )

        # Now close stdin. To make SASL non-interactive.
        if not self.get('debug'):
            sys.stdin.close()

        check_yaml_gotchas(file_config)
        self.warn_unknown_config(file_config)

        # Now merge all config sources.
        default_privileges = make_well_known_privileges()
        try:
            self.merge(file_config=file_config, environ=os.environ, args=args)
            postprocess_privilege_options(self, default_privileges)
        except ValueError as e:
            raise ConfigurationError("Failed to load configuration: %s" % (e,))

        logger.debug("Configuration loaded.") 
Example #20
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 4 votes vote down vote up
def check32_phototagginggramplet(self):
        '''PhotoTaggingGramplet - Gramplet for tagging people in photos

        If the OpenCV is not found, the automatic face detection feature will
        be unavailable, but the Gramplet should otherwise function correctly.

        Automatic detection of faces requires the following to be installed:

        * OpenCV, its dependencies and Python bindings. This library should be
          available in common Linux distributions. For example, Debian package
          python-opencv provides the Python bindings for the library. It will
          require the core library packages (libopencv-*) and the
        * python-numpy package.

        https://gramps-project.org/wiki/index.php?title=Photo_Tagging_Gramplet
        https://github.com/gramps-project/addons-source/blob/master/PhotoTaggingGramplet/facedetection.py
        https://github.com/gramps-project/addons-source/tree/master/PhotoTaggingGramplet
        ......
        ubuntu:
        pip3 install opencv-python

        import cv2
        cv2.__version__
        '3.4.0'
        '''
        self.append_text("\n")
        self.render_text("""<b>12. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=Photo_Tagging_Gramplet">"""
                         """Addon:Photo Tagging Gramplet</a> :</b> """)
        # Start check

        try:
            import cv2
            cv2_ver = cv2.__version__
            #print(dir(cv2))
        except ImportError:
            cv2_ver = "Not found"
        try:
            import numpy
            numpy_ver = str(numpy.__version__)
            #print("numpy.__version__ :" + numpy_ver )
        except ImportError:
            numpy_ver = "Not found"

        self.append_text("(NumPy: " + numpy_ver + ")")
        self.append_text("(OpenCV facedetection: %s)" % cv2_ver) 
Example #21
Source File: PrerequisitesCheckerGramplet.py    From addons-source with GNU General Public License v2.0 4 votes vote down vote up
def check30_PostgreSQL(self):
        '''
        PostgreSQL Database

        requires: PostgreSQL -
        requires: psycopg2 - Python-PostgreSQL Database Adapter

        # https://pypi.python.org/pypi/psycopg2

        # https://gramps-project.org/wiki/index.php?title=DB-API_Database_Backend#Postgresql

        # https://github.com/gramps-project/addons-source/tree/maintenance/gramps50/PostgreSQL

        https://stackoverflow.com/a/39451451

        How get PostgreSQL version using psycopg2?

        According to documentation it is server_version property of connection:

        conn = psycopg2.connect(settings.DB_DSN)
        >>> conn.server_version
        90504
        The number is formed by converting the major, minor, and revision
        numbers into two-decimal-digit numbers and appending them together.
        For example, version 8.1.5 will be returned as 80105.

        command line:
        psql -V
        '''
        self.append_text("\n")
        self.render_text("""<b>10. <a href="https://gramps-project.org/wiki"""
                         """/index.php?title=DB-API_Database_Backend#"""
                         """Postgresql">Addon:PostgreSQL</a></b>"""
                         """ Database library Support : """)
        # Start check
        try:
            import psycopg2
            psycopg2_ver = str(psycopg2.__version__)
            #print(dir(psycopg2))
            #print("psycopg2" + psycopg2_ver)
            try:
                libpq_ver = str(psycopg2.__libpq_version__)
            except AttributeError:
                libpq_ver = "Not found."
        except ImportError:
            psycopg2_ver = "Not found."
            libpq_ver = "Not found."

        result = ("(PostgreSQL " + libpq_ver + ")(psycopg2 : " +
                  psycopg2_ver + ")")
        # End checks
        self.append_text(result)