Beispiel #1
1
 def ready(self):
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.connection is not None:
             register_type_handlers(conn)
     connection_created.connect(register_type_handlers)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
Beispiel #2
0
 def ready(self):
     for conn in connections.all():
         if conn.connection is not None:
             register_hstore_handler(conn)
     connection_created.connect(connection_handler,
                                weak=CONNECTION_CREATED_SIGNAL_WEAKREF,
                                dispatch_uid="_connection_create_handler")
Beispiel #3
0
 def ready(self):
     sys.stdout.write(f"Loading {self.verbose_name} ...\n")
     connection_created.connect(activate_foreign_keys)
     sys.stdout.write(f" * default TIME_ZONE {settings.TIME_ZONE}.\n")
     if not settings.USE_TZ:
         raise ImproperlyConfigured("EDC requires settings.USE_TZ = True")
     sys.stdout.write(f" Done loading {self.verbose_name}.\n")
Beispiel #4
0
 def ready(self):
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.vendor == 'postgresql':
             conn.introspection.data_types_reverse.update({
                 3802:
                 'django.contrib.postgres.fields.JSONField',
                 3904:
                 'django.contrib.postgres.fields.IntegerRangeField',
                 3906:
                 'django.contrib.postgres.fields.DecimalRangeField',
                 3910:
                 'django.contrib.postgres.fields.DateTimeRangeField',
                 3912:
                 'django.contrib.postgres.fields.DateRangeField',
                 3926:
                 'django.contrib.postgres.fields.BigIntegerRangeField',
             })
             if conn.connection is not None:
                 register_type_handlers(conn)
     connection_created.connect(register_type_handlers)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
Beispiel #5
0
 def ready(self):
     setting_changed.connect(uninstall_if_needed)
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.vendor == 'postgresql':
             conn.introspection.data_types_reverse.update({
                 3904:
                 'django.contrib.postgres.fields.IntegerRangeField',
                 3906:
                 'django.contrib.postgres.fields.DecimalRangeField',
                 3910:
                 'django.contrib.postgres.fields.DateTimeRangeField',
                 3912:
                 'django.contrib.postgres.fields.DateRangeField',
                 3926:
                 'django.contrib.postgres.fields.BigIntegerRangeField',
             })
             if conn.connection is not None:
                 register_type_handlers(conn)
     connection_created.connect(register_type_handlers)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
     CharField.register_lookup(TrigramWordSimilar)
     TextField.register_lookup(TrigramWordSimilar)
     MigrationWriter.register_serializer(RANGE_TYPES, RangeSerializer)
     IndexExpression.register_wrappers(OrderBy, OpClass, Collate)
Beispiel #6
0
def config():
    service_name = os.getenv('DATABASE_SERVICE_NAME',
                             '').upper().replace('-', '_')

    if service_name:
        engine = engines.get(os.getenv('DATABASE_ENGINE'), engines['sqlite'])
    else:
        engine = engines['sqlite']

    name = os.getenv('DATABASE_NAME')

    if not name and engine == engines['sqlite']:
        name = os.path.join(settings.BASE_DIR, 'db.sqlite3')

    if bool(os.getenv('FIX_BROKEN_SQLITE', 'False').lower() in ['true', 1]):
        connection_created.connect(activate_legacy_table_fix)

    return {
        'ENGINE': engine,
        'NAME': name,
        'USER': os.getenv('DATABASE_USER'),
        'PASSWORD': os.getenv('DATABASE_PASSWORD'),
        'HOST': os.getenv('{}_SERVICE_HOST'.format(service_name)),
        'PORT': os.getenv('{}_SERVICE_PORT'.format(service_name)),
        'ATOMIC_REQUESTS': True
    }
Beispiel #7
0
    def ready(self) -> None:
        # from . import receivers  # NOQA
        from django.db.backends.signals import connection_created
        connection_created.connect(set_dummy_active_tenant)

        from occupation.admin import patch_admin
        patch_admin()
Beispiel #8
0
    def ready(self):
        # Register DB credential fetching code so that we can fetch credentials from Vault before
        # attempting to connect to the database.
        if common.VaultAuthenticator.has_envconfig():
            from django.conf import settings
            found = False
            for k, db in settings.DATABASES.items():
                if isinstance(db, database.DjangoAutoRefreshDBCredentialsDict):
                    found = True
            if found:
                database.monkeypatch_django()

        # Register SET_ROLE signal handler for the standard PostgreSQL database wrapper
        from django.db.backends.postgresql.base import DatabaseWrapper as PostgreSQLDatabaseWrapper
        connection_created.connect(database.set_role_connection,
                                   sender=PostgreSQLDatabaseWrapper)

        # Register SET_ROLE signal handler for the PostGIS database wrapper
        try:
            from django.contrib.gis.db.backends.postgis.base import DatabaseWrapper as PostGISDatabaseWrapper
            connection_created.connect(database.set_role_connection,
                                       sender=PostGISDatabaseWrapper)
        except (
                ImportError, ImproperlyConfigured
        ):  # This exception will get thrown if the GDAL C libraries aren't installed.
            pass
Beispiel #9
0
 def add_database_instrumentation(self):
     if not getattr(settings, "DJANGO_MYSQL_REWRITE_QUERIES",
                    False):  # pragma: no cover
         return
     for _alias, connection in mysql_connections():
         install_rewrite_hook(connection)
     connection_created.connect(install_rewrite_hook)
    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        if name == 'CompositeType':
            return

        # Register the type on the first database connection
        connection_created.connect(receiver=cls.database_connected,
                                   dispatch_uid=cls._meta.db_type)
Beispiel #11
0
 def ready(self):
     connection_created.connect(register_hstore_handler)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
 def ready(self):
     from .signals import update_user_profile_on_post_save
     register(edc_base_check)
     sys.stdout.write(f'Loading {self.verbose_name} ...\n')
     connection_created.connect(activate_foreign_keys)
     sys.stdout.write(f' * default TIME_ZONE {settings.TIME_ZONE}.\n')
     if not settings.USE_TZ:
         raise ImproperlyConfigured('EDC requires settings.USE_TZ = True')
     sys.stdout.write(f' Done loading {self.verbose_name}.\n')
    def test_connections(self):
        connection_created.connect(self.count_conn)
        self.connections = 0

        # Checking if DatabaseWrapper object creates a connection by default
        conn = DatabaseWrapper(settings.DATABASES['default'])
        dbo = DatabaseOperations(conn)
        dbo.adapt_timefield_value(datetime.time(3, 3, 3))
        self.assertEqual(self.connections, 0)
Beispiel #14
0
    def test_connections(self):
        connection_created.connect(self.count_conn)
        self.connections = 0

        # Checking if DatabaseWrapper object creates a connection by default
        conn = DatabaseWrapper(settings.DATABASES['default'])
        dbo = DatabaseOperations(conn)
        dbo.value_to_db_time(datetime.time(3, 3, 3))
        self.assertEqual(self.connections, 0)
    def ready(self):
        set_read_only()

        for alias in connections:
            connection = connections[alias]
            install_hook(connection)
        connection_created.connect(install_hook)

        setting_changed.connect(reset_read_only)
    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        if name == 'CompositeType':
            return

        cls._capture_descriptors()  # pylint:disable=no-value-for-parameter

        # Register the type on the first database connection
        connection_created.connect(receiver=cls.database_connected,
                                   dispatch_uid=cls._meta.db_type)
Beispiel #17
0
 def ready(self):
     from .signals import update_user_profile_on_post_save
     register(edc_base_check)
     sys.stdout.write(f'Loading {self.verbose_name} ...\n')
     connection_created.connect(activate_foreign_keys)
     sys.stdout.write(
         f' * default TIME_ZONE {settings.TIME_ZONE}.\n')
     if not settings.USE_TZ:
         raise ImproperlyConfigured('EDC requires settings.USE_TZ = True')
     sys.stdout.write(f' Done loading {self.verbose_name}.\n')
def set_autocommit():
    """
    example:

    from pyutil.program.db import set_autocommit
    set_autocommit()

    """
    from django.db.backends.signals import connection_created
    connection_created.connect(__autocommit_on)
    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        if name == 'CompositeType':
            return

        cls._capture_descriptors()  # pylint:disable=no-value-for-parameter

        # Register the type on the first database connection
        connection_created.connect(receiver=cls.database_connected,
                                   dispatch_uid=cls._meta.db_type)
Beispiel #20
0
 def ready(self):
     db_conn = connections[DEFAULT_DB_ALIAS]
     try:
         c = db_conn.cursor()
     except OperationalError:
         pass
     else:
         db_conn.close()
     connection_created.connect(connection_handler,
                                weak=CONNECTION_CREATED_SIGNAL_WEAKREF,
                                dispatch_uid="_connection_create_handler")
Beispiel #21
0
 def ready(self):
     """
     Sets up PRAGMAs.
     """
     connection_created.connect(self.activate_pragmas_per_connection)
     self.activate_pragmas_on_start()
     # Log the settings file that we are running Kolibri with.
     # Do this logging here, as this will be after Django has done its processing of
     # Any environment variables or --settings command line arguments.
     logger.info("Running Kolibri with the following settings: {settings}".format(
         settings=os.environ["DJANGO_SETTINGS_MODULE"]))
Beispiel #22
0
 def ready(self):
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.connection is not None:
             register_hstore_handler(conn)
     connection_created.connect(register_hstore_handler)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
Beispiel #23
0
def attach_signals():
    if not DJANGO_ENABLED:
        return
    global link
    connection_created.connect(link)
    # Link all connections that might have popped up while we were
    # loading. This will happen for sure if django-livesettings is installed as
    # importing settings will automagically open a connection to the default
    # database.
    for conn in connections.all():
        if conn.connection is not None:
            link(conn.__class__, conn)
Beispiel #24
0
    def test_signal(self):
        data = {}
        def receiver(sender, connection, **kwargs):
            data["connection"] = connection

        connection_created.connect(receiver)
        connection.close()
        cursor = connection.cursor()
        self.assertTrue(data["connection"] is connection)

        connection_created.disconnect(receiver)
        data.clear()
        cursor = connection.cursor()
        self.assertTrue(data == {})
    def ready(self):
        from application import settings
        if not settings.TESTING:
            from django.db.backends.signals import connection_created

            def register_achievements(*args, **kwargs):
                try:
                    from django.utils.module_loading import autodiscover_modules
                    autodiscover_modules('achievements')
                except Exception as e:
                    print e
                    print "Maybe, you need to run migrations first"

            connection_created.connect(register_achievements, weak=False)
Beispiel #26
0
def customize_sqlite(sender, **kw):
    """
    Here is how we install case-insensitive sorting in sqlite3.
    Note that this caused noticeable performance degradation...

    Thanks to 
    - http://efreedom.com/Question/1-3763838/Sort-Order-SQLite3-Umlauts
    - http://docs.python.org/library/sqlite3.html#sqlite3.Connection.create_collation
    - http://www.sqlite.org/lang_createindex.html
    """
    from django.db.backends.signals import connection_created

    def belgian(s):

        s = s.decode('utf-8').lower()

        s = s.replace(u'ä', u'a')
        s = s.replace(u'à', u'a')
        s = s.replace(u'â', u'a')

        s = s.replace(u'ç', u'c')

        s = s.replace(u'é', u'e')
        s = s.replace(u'è', u'e')
        s = s.replace(u'ê', u'e')
        s = s.replace(u'ë', u'e')

        s = s.replace(u'ö', u'o')
        s = s.replace(u'õ', u'o')
        s = s.replace(u'ô', u'o')

        s = s.replace(u'ß', u'ss')

        s = s.replace(u'ù', u'u')
        s = s.replace(u'ü', u'u')
        s = s.replace(u'û', u'u')

        return s

    def stricmp(str1, str2):
        return cmp(belgian(str1), belgian(str2))

    def my_callback(sender, **kw):
        from django.db.backends.sqlite3.base import DatabaseWrapper
        if sender is DatabaseWrapper:
            db = kw['connection']
            db.connection.create_collation('BINARY', stricmp)

    connection_created.connect(my_callback)
    def test_signal(self):
        from django.db import connection

        def conn_setup(*args, **kwargs):
            conn = kwargs['connection']
            cur = conn.cursor()
            cur.execute("SET @xyz=10")
            cur.close()

        connection_created.connect(conn_setup)
        cursor = connection.cursor()
        cursor.execute("SELECT @xyz")

        self.assertEqual((10, ), cursor.fetchone())
        cursor.close()
        self.cnx.close()
    def test_signal(self):
        from django.db import connection

        def conn_setup(*args, **kwargs):
            conn = kwargs['connection']
            cur = conn.cursor()
            cur.execute("SET @xyz=10")
            cur.close()

        connection_created.connect(conn_setup)
        cursor = connection.cursor()
        cursor.execute("SELECT @xyz")

        self.assertEqual((10,), cursor.fetchone())
        cursor.close()
        self.cnx.close()
Beispiel #29
0
def ensure_sql_instrumented():
    global sql_instrumented
    if sql_instrumented:
        return
    sql_instrumented = True

    if django.VERSION >= (2, 0):
        for connection in connections.all():
            install_db_execute_hook(connection=connection)
        connection_created.connect(install_db_execute_hook)
        logger.debug("Installed DB connection created signal handler")
    else:

        CursorWrapper.execute = execute_wrapper(CursorWrapper.execute)
        CursorWrapper.executemany = executemany_wrapper(CursorWrapper.executemany)

        logger.debug("Monkey patched SQL")
Beispiel #30
0
    def test_signal(self):
        data = {}

        def receiver(sender, connection, **kwargs):
            data["connection"] = connection

        connection_created.connect(receiver)
        connection.close()
        with connection.cursor():
            pass
        self.assertIs(data["connection"].connection, connection.connection)

        connection_created.disconnect(receiver)
        data.clear()
        with connection.cursor():
            pass
        self.assertEqual(data, {})
Beispiel #31
0
    def ready(self):
        from django.conf import settings
        if not getattr(settings, "PARLER_DEFAULT_LANGUAGE_CODE", None):
            raise MissingSettingException("PARLER_DEFAULT_LANGUAGE_CODE must be set.")
        if not getattr(settings, "PARLER_LANGUAGES", None):
            raise MissingSettingException("PARLER_LANGUAGES must be set.")

        # set money precision provider function
        from .models import get_currency_precision
        money.set_precision_provider(get_currency_precision)

        if django.conf.settings.SHUUP_ERROR_PAGE_HANDLERS_SPEC:
            from .error_handling import install_error_handlers
            install_error_handlers()

        from shuup.core.utils.context_cache import (
            bump_product_signal_handler, bump_shop_product_signal_handler
        )
        from shuup.core.models import Product, ShopProduct
        from django.db.models.signals import m2m_changed
        m2m_changed.connect(
            bump_shop_product_signal_handler,
            sender=ShopProduct.categories.through,
            dispatch_uid="shop_product:clear_shop_product_cache"
        )
        from django.db.models.signals import post_save
        post_save.connect(
            bump_product_signal_handler,
            sender=Product,
            dispatch_uid="product:bump_product_cache"
        )
        post_save.connect(
            bump_shop_product_signal_handler,
            sender=ShopProduct,
            dispatch_uid="shop_product:bump_shop_product_cache"
        )

        # extends SQLite with necessary functions
        from django.db.backends.signals import connection_created
        from shuup.core.utils.db import extend_sqlite_functions
        connection_created.connect(extend_sqlite_functions)
Beispiel #32
0
 def ready(self):
     # Connections may already exist before we are called.
     for conn in connections.all():
         if conn.vendor == 'postgresql':
             conn.introspection.data_types_reverse.update({
                 3802: 'django.contrib.postgres.fields.JSONField',
                 3904: 'django.contrib.postgres.fields.IntegerRangeField',
                 3906: 'django.contrib.postgres.fields.DecimalRangeField',
                 3910: 'django.contrib.postgres.fields.DateTimeRangeField',
                 3912: 'django.contrib.postgres.fields.DateRangeField',
                 3926: 'django.contrib.postgres.fields.BigIntegerRangeField',
             })
             if conn.connection is not None:
                 register_type_handlers(conn)
     connection_created.connect(register_type_handlers)
     CharField.register_lookup(Unaccent)
     TextField.register_lookup(Unaccent)
     CharField.register_lookup(SearchLookup)
     TextField.register_lookup(SearchLookup)
     CharField.register_lookup(TrigramSimilar)
     TextField.register_lookup(TrigramSimilar)
Beispiel #33
0
def patch():
    if not ConfigProvider.get(
            config_names.THUNDRA_TRACE_INTEGRATIONS_DJANGO_DISABLE) and (
                not utils.get_env_variable(
                    constants.AWS_LAMBDA_FUNCTION_NAME)):
        wrapt.wrap_function_wrapper('django.core.handlers.base',
                                    'BaseHandler.load_middleware', _wrapper)

    if not ConfigProvider.get(
            config_names.THUNDRA_TRACE_INTEGRATIONS_DJANGO_ORM_DISABLE):
        try:
            from django import VERSION
            from django.db import connections
            from django.db.backends.signals import connection_created

            if VERSION >= (2, 0):
                for connection in connections.all():
                    install_db_execute_wrapper(connection)

                connection_created.connect(install_db_execute_wrapper)
        except:
            pass
Beispiel #34
0
    def ready(self):
        from django.conf import settings
        if not getattr(settings, "PARLER_DEFAULT_LANGUAGE_CODE", None):
            raise MissingSettingException(
                "PARLER_DEFAULT_LANGUAGE_CODE must be set.")
        if not getattr(settings, "PARLER_LANGUAGES", None):
            raise MissingSettingException("PARLER_LANGUAGES must be set.")

        # set money precision provider function
        from .models import get_currency_precision
        money.set_precision_provider(get_currency_precision)

        if django.conf.settings.SHUUP_ERROR_PAGE_HANDLERS_SPEC:
            from .error_handling import install_error_handlers
            install_error_handlers()

        from shuup.core.utils.context_cache import (
            bump_product_signal_handler, bump_shop_product_signal_handler)
        from shuup.core.models import Product, ShopProduct
        from django.db.models.signals import m2m_changed
        m2m_changed.connect(
            bump_shop_product_signal_handler,
            sender=ShopProduct.categories.through,
            dispatch_uid="shop_product:clear_shop_product_cache")
        from django.db.models.signals import post_save
        post_save.connect(bump_product_signal_handler,
                          sender=Product,
                          dispatch_uid="product:bump_product_cache")
        post_save.connect(bump_shop_product_signal_handler,
                          sender=ShopProduct,
                          dispatch_uid="shop_product:bump_shop_product_cache")

        # extends SQLite with necessary functions
        from django.db.backends.signals import connection_created
        from shuup.core.utils.db import extend_sqlite_functions
        connection_created.connect(extend_sqlite_functions)
Beispiel #35
0
from django.db.backends.signals import connection_created
from django.utils.importlib import import_module

from multischema import settings
from multischema.handlers import create_namespace_if_not_exist, switch_to_namespace_on_connect


backends = [getattr(import_module('.base', package=backend), 'DatabaseWrapper') for backend in settings.MULTISCHEMA_SUPPORTED_BACKENDS]

if settings.MULTISCHEMA_CREATE_IF_NOT_EXIST:
    for backend in backends:
        connection_created.connect(create_namespace_if_not_exist, sender=backend)

for backend in backends:
    connection_created.connect(switch_to_namespace_on_connect, sender=backend)
Beispiel #36
0
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

# If we're using sqlite, we need to tweak the performance a bit
from django.db.backends.signals import connection_created
def activate_synchronous_off(sender, connection, **kwargs):
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA synchronous = 0;')
connection_created.connect(activate_synchronous_off)
#


Beispiel #37
0
 def ready(self):
     connection_created.connect(connection_handler,
                                weak=CONNECTION_CREATED_SIGNAL_WEAKREF,
                                dispatch_uid="_connection_create_handler")
from django.db.backends.signals import connection_created
try:
    from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper
    from .util import register_hstore

    def register_hstore_extension(sender, connection, *args, **kwargs):
        cursor = connection.cursor()
        cursor.execute("CREATE EXTENSION IF NOT EXISTS hstore")
        connection.commit_unless_managed()
        register_hstore(connection.connection, globally=True, unicode=True)

    connection_created.connect(register_hstore_extension, sender=DatabaseWrapper)
except ImportError:
    pass
Beispiel #39
0
 def ready(self):
     connection_created.connect(connection_handler,
                                dispatch_uid="_connection_create_handler")
Beispiel #40
0
from django.db.backends.signals import connection_created


def activate_foreign_keys(sender, connection, **kwargs):
    """Enable integrity constraint with sqlite."""
    if connection.vendor == "sqlite":
        cursor = connection.cursor()
        cursor.execute("PRAGMA foreign_keys = ON;")


connection_created.connect(activate_foreign_keys)
Beispiel #41
0
from django.conf import settings
from django.db.backends.signals import connection_created

def set_schema_search_path(sender, **kwargs):
    from django.db import connection, transaction
    
    cursor = connection.cursor()
    cursor.execute('SET search_path TO %s' % ', '.join(settings.DATABASES['default']['SCHEMA_SEARCH_PATH']))
    transaction.commit_unless_managed()

if 'postgresql' in settings.DATABASES['default']['ENGINE'] and settings.DATABASES['default'].get('SCHEMA_SEARCH_PATH'):
    connection_created.connect(set_schema_search_path)
Beispiel #42
0
"""Patches to apply to django."""

from django.db.backends.signals import connection_created

from django.db.backends.sqlite3 import base


def get_new_connection(sender=None, connection=None, **kwargs):
    """Assign correct text factory when database backend is sqlite3"""
    if sender is base.DatabaseWrapper:
        connection.connection.text_factory = str

# Connect to django signal
connection_created.connect(get_new_connection)
from django import VERSION
import psycopg2.extras

sitename = 'hiking'

def set_schema(sender, connection, **kwargs):
    cursor = connection.cursor()
    cursor.execute("SET search_path TO %s,public;" % sitename)
    psycopg2.extras.register_hstore(cursor, globally=True, unicode=True)


if __name__ == "__main__":
    from django.core.management import execute_from_command_line

    sys.path.append(os.path.normpath(os.path.join(os.path.realpath(__file__), '../..')))
    sys.path.append(os.path.normpath(os.path.join(os.path.realpath(__file__), '../../../../config')))

    if len(sys.argv) > 1 and sys.argv[-1] in ('hiking', 'cycling', 'skating', 'mtbmap'):
        sitename = sys.argv[-1]
        args = sys.argv[:-1]
    else:
        args = sys.argv

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "routemap.sites.settings." + sitename )
    if VERSION >= (1,1):
        from django.db.backends.signals import connection_created
        connection_created.connect(set_schema)

    execute_from_command_line(args)

Beispiel #44
0
            pg_config = subprocess.Popen(["pg_config", "--sharedir"], stdout=subprocess.PIPE)
            share_dir = pg_config.communicate()[0].strip('\r\n ')
            hstore_sql = os.path.join(share_dir, 'contrib', 'hstore.sql')
            statements = re.compile(r";[ \t]*$", re.M)
            cursor = connection.cursor()
            with open(hstore_sql, 'U') as fp:
                for statement in statements.split(fp.read().decode(settings.FILE_CHARSET)):
                    statement = re.sub(ur"--.*([\n\Z]|$)", "", statement).strip()
                    if statement:
                        cursor.execute(statement + u";")
        else:
            cursor = connection.cursor()
            cursor.execute("CREATE EXTENSION hstore;")
    register_hstore(connection.connection, globally=True)

connection_created.connect(register_hstore_on_connection_creation, dispatch_uid='hstore_field.register_hstore_on_connection_creation')


class HStoreDictionary(dict):

    def __init__(self, value=None, field=None, instance=None, **params):
        super(HStoreDictionary, self).__init__(value, **params)
        self.field = field
        self.instance = instance


class HStoreDescriptor(object):

    def __init__(self, field):
        self.field = field
Beispiel #45
0
#
# You should have received a copy of the GNU Affero General Public License
# along with LAVA.  If not, see <http://www.gnu.org/licenses/>.

import os

from django.core.wsgi import get_wsgi_application
from django.db.backends.signals import connection_created

# Set the environment variables for Django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lava_server.settings.distro")
os.environ.setdefault("DJANGO_DEBIAN_SETTINGS_TEMPLATE",
                      "/etc/lava-server/{filename}.conf")


# Set the postgresql connection timeout
# The timeout is only used when running through wsgi.  This way, command line
# commands are not affected by the timeout.
def setup_postgres(connection, **kwargs):
    if connection.vendor != 'postgresql':
        return

    with connection.cursor() as cursor:
        cursor.execute("SET statement_timeout TO 30000")


connection_created.connect(setup_postgres, dispatch_uid="setup_postgres")

# Create the application
application = get_wsgi_application()
Beispiel #46
0
m2m_changed.connect(handle_shop_product_post_save,
                    sender=ShopProduct.categories.through,
                    dispatch_uid="shop_product:change_categories")
post_save.connect(handle_product_post_save,
                  sender=Product,
                  dispatch_uid="product:bump_product_cache")
post_save.connect(handle_shop_product_post_save,
                  sender=ShopProduct,
                  dispatch_uid="shop_product:bump_shop_product_cache")

# connect signals to bump price caches on Tax and TaxClass change
post_save.connect(handle_post_save_bump_all_prices_caches,
                  sender=Tax,
                  dispatch_uid="tax_class:bump_prices_cache")
post_save.connect(handle_post_save_bump_all_prices_caches,
                  sender=TaxClass,
                  dispatch_uid="tax_class:bump_prices_cache")

# connect signals to bump context cache internal cache for contacts
post_save.connect(handle_contact_post_save,
                  sender=PersonContact,
                  dispatch_uid="person_contact:bump_context_cache")
post_save.connect(handle_contact_post_save,
                  sender=CompanyContact,
                  dispatch_uid="company_contact:bump_context_cache")
m2m_changed.connect(handle_contact_post_save,
                    sender=ContactGroup.members.through,
                    dispatch_uid="contact_group:change_members")

connection_created.connect(extend_sqlite_functions)
Beispiel #47
0
else:
    # We are running in debug
    SECRET_KEY = 'my debug secret key is not a secret'

    from django.db.backends.signals import connection_created

    def speed_up_writes_by_20_percent(sender, connection, **kwargs):
        """Truncate, don't delete, sqlite3 journal.

        This is faster because every write no longer needs to create and
        delete a file (which would mean two directory writes).
        """
        cursor = connection.cursor()
        cursor.execute('PRAGMA journal_mode=TRUNCATE')

    connection_created.connect(speed_up_writes_by_20_percent)

    DATABASES = {
        'default': {
            'ENGINE': 'cjworkbench.sqlite3withbeginimmediate',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
            'OPTIONS': {
                'timeout': 30,
                'isolation_level': 'IMMEDIATE',
            },
        },
    }

    EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'
    EMAIL_FILE_PATH = os.path.join(BASE_DIR, 'local_mail')
        cur.execute("SELECT NULL::BIT")
        bit_oid = cur.description[0].type_code
        cur.execute("SELECT NULL::VARBIT")
        varbit_oid = cur.description[0].type_code
    bit_caster = ext.new_type((bit_oid, varbit_oid), 'BIT', cast_bits)

    # There are conflict with `django-postgrespool`.
    # From this app we use just `View` and we no need this functionality.
    # ext.register_type(bit_caster, connection)


def register_types_on_connection_creation(connection, sender, *args, **kwargs):
    if not issubclass(sender, PGDatabaseWrapper):
        return
    register_bitstring_types(connection.connection)
connection_created.connect(register_types_on_connection_creation)


class BitStringField(models.Field):

    """A Postgres bit string."""

    def __init__(self, *args, **kwargs):
        self.max_length = kwargs.setdefault('max_length', 1)
        self.varying = kwargs.pop('varying', False)

        if 'default' in kwargs:
            default = kwargs.pop('default')
        elif kwargs.get('null', False):
            default = None
        elif self.max_length is not None and not self.varying:
Beispiel #49
0
        'toaster': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'WARN',
            'propagate': True,
        },
    }
}

if DEBUG and SQL_DEBUG:
    LOGGING['loggers']['django.db.backends'] = {
        'level': 'DEBUG',
        'handlers': ['console'],
    }

# If we're using sqlite, we need to tweak the performance a bit
from django.db.backends.signals import connection_created


def activate_synchronous_off(sender, connection, **kwargs):
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA synchronous = 0;')


connection_created.connect(activate_synchronous_off)
#
Beispiel #50
0
    @staticmethod
    def update_timestamp_for_string(s, override_time=None):
        timestamp, _ = Timestamp.objects.get_or_create(key=Timestamp.hash(s), defaults={
            'timestamp': datetime.datetime.utcnow()})
        timestamp.timestamp = override_time or datetime.datetime.utcnow()
        timestamp.save()  # definitely!
        return timestamp


# Adjustments to default Django sqlite3 behavior
def activate_foreign_keys(sender, connection, **kwargs):
    """Enable integrity constraint with sqlite."""
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA foreign_keys = ON;')


def set_asynchronous_for_sqlite(sender, connection, **kwargs):
    """Make sqlite3 be asynchronous. This is risky in case your
    machine crashes, but comes at such a performance boost that
    we do it anyway.

    More info: http://www.sqlite.org/pragma.html#pragma_synchronous """
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA synchronous=OFF;')

from django.db.backends.signals import connection_created
connection_created.connect(activate_foreign_keys)
connection_created.connect(set_asynchronous_for_sqlite)
Beispiel #51
0
def app_options():  # 配置数据容器
    '''
    系统全局配置参数
    '''
    from base.options import  SYSPARAM, PERSONAL
    import dict4ini # 读取配置文件appconfig.ini
    appconf=dict4ini.DictIni(settings.APP_HOME+"/appconfig.ini")
    language=appconf["language"]["language"]        # 设置语言
    
    return (
        #参数名称, 参数默认值,参数显示名称,解释,参数类别,是否可见
        ('date_format', '%Y-%m-%d', u"%s" % _(u'日期格式'), '', PERSONAL, True),
        ('time_format', '%H:%M:%S', u"%s" % _(u'时间格式'), '', PERSONAL, True),
        ('datetime_format', '%Y-%m-%d %H:%M:%S', u"%s" % _(u'时间日期格式'), '', PERSONAL, True),
        ('shortdate_format', '%y-%m-%d', u"%s" % _(u'短日期格式'), '', PERSONAL, True),
        ('shortdatetime_format', '%y-%m-%d %H:%M', u"%s" % _(u'短日期时间格式'), '', PERSONAL, True),
        ('language', language, u'语言', '', PERSONAL, True),
        ('base_default_page', 'data/auth/User/', u"%s" % _(u'系统默认页面'), '', PERSONAL, False),
        ('site_default_page', 'data/worktable/', u"%s" % _(u'整个系统默认页面'), "", PERSONAL, False),
        ('backup_sched', '', u'备份时间', "", SYSPARAM, True),
    )


def database_init(sender, **kwargs):
    from django.db import connection
    if 'mysql' in connection.__module__:    #设置mysql数据库的提交属性
        connection.cursor().execute('set autocommit=1')
     
from django.db.backends.signals import connection_created
connection_created.connect(database_init)   # 加入 connection_created 信号处理函数
Beispiel #52
0
    sender=Product,
    dispatch_uid="product:bump_product_cache"
)
post_save.connect(
    handle_shop_product_post_save,
    sender=ShopProduct,
    dispatch_uid="shop_product:bump_shop_product_cache"
)

# connect signals to bump caches on Supplier change
post_save.connect(
    handle_supplier_post_save,
    sender=Supplier,
    dispatch_uid="supplier:bump_supplier_cache"
)

# connect signals to bump price caches on Tax and TaxClass change
post_save.connect(handle_post_save_bump_all_prices_caches, sender=Tax, dispatch_uid="tax_class:bump_prices_cache")
post_save.connect(handle_post_save_bump_all_prices_caches, sender=TaxClass, dispatch_uid="tax_class:bump_prices_cache")

# connect signals to bump context cache internal cache for contacts
post_save.connect(handle_contact_post_save, sender=PersonContact, dispatch_uid="person_contact:bump_context_cache")
post_save.connect(handle_contact_post_save, sender=CompanyContact, dispatch_uid="company_contact:bump_context_cache")
m2m_changed.connect(
    handle_contact_post_save,
    sender=ContactGroup.members.through,
    dispatch_uid="contact_group:change_members"
)

connection_created.connect(extend_sqlite_functions)
Beispiel #53
0
from django.db.backends.signals import connection_created


def activate_foreign_keys(sender, connection, **kwargs):
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA foreign_keys = ON;')


connection_created.connect(activate_foreign_keys)
Beispiel #54
0
        if len(self.unique_handlers) > 0:
            handlers.update(self.unique_handlers)
            self.unique_handlers = []

        handlers.update(self.generic_handlers)

        # List comprension is used instead of for statement
        # only for performance.
        [x(connection) for x in handlers]

    def attach_handler(self, func, vendor=None, unique=False):
        if unique:
            self.unique_handlers.append(func)
        else:
            self.generic_handlers.append(func)


connection_handler = ConnectionCreateHandler()
connection_created.connect(connection_handler, dispatch_uid="_connection_create_handler")


def register_hstore_handler(connection, **kwargs):
    if not connection.settings_dict.get('HAS_HSTORE', True):
        return

    if sys.version_info[0] < 3:
        register_hstore(connection.connection, globally=True, unicode=True)
    else:
        register_hstore(connection.connection, globally=True)

connection_handler.attach_handler(register_hstore_handler, vendor="postgresql", unique=True)
Beispiel #55
0
 def ready(self):
     connection_created.connect(activate_foreign_keys)
Beispiel #56
0
def setup():
    connection_created.connect(sqlite_set_pragma)