Python django.conf() Examples

The following are code examples for showing how to use django.conf(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-yandex-cash-register   Author: bzzzzzz   File: runtests.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings
    settings.configure(**SETTINGS_DICT)

    # Then, call django.setup() to initialize the application cache
    # and other bits:
    import django
    if hasattr(django, 'setup'):
        django.setup()

    # Now we instantiate a test runner...
    from django.test.utils import get_runner
    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['yandex_cash_register.tests'])
    sys.exit(bool(failures)) 
Example 2
Project: django-irs-filings   Author: sahilchinoy   File: setup.py    MIT License 6 votes vote down vote up
def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={
                'default': {
                    'NAME': ':memory:',
                    'ENGINE': 'django.db.backends.sqlite3'
                }
            },
            INSTALLED_APPS=('irs',)
        )
        from django.core.management import call_command
        from django.conf import settings
        import django
        if django.VERSION[:2] >= (1, 7):
            django.setup()
            settings.BASE_DIR = os.path.dirname(__file__)
        call_command('test', 'irs') 
Example 3
Project: munch-core   Author: crunchmail   File: run.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def worker(**options):
    "Run background worker instance."
    from django.conf import settings
    if hasattr(settings, 'CELERY_ALWAYS_EAGER') and \
            settings.CELERY_ALWAYS_EAGER:
        raise click.ClickException(
            'Disable CELERY_ALWAYS_EAGER in your '
            'settings file to spawn workers.')

    from munch.core.celery import app
    os.environ['WORKER_TYPE'] = ','.join(options.pop('worker_type')).lower()
    pool_cls = options.pop('pool')
    worker = app.Worker(
        pool_cls=pool_cls, queues=settings.CELERY_DEFAULT_QUEUE, **options)
    worker.start()
    try:
        sys.exit(worker.exitcode)
    except AttributeError:
        # `worker.exitcode` was added in a newer version of Celery:
        # https://github.com/celery/celery/commit/dc28e8a5
        # so this is an attempt to be forwards compatible
        pass 
Example 4
Project: GTDWeb   Author: lanbing510   File: templates.py    GNU General Public License v2.0 6 votes vote down vote up
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
Example 5
Project: django-cryptography   Author: georgemarshall   File: setup.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests(self):
        import django
        django.setup()

        from django.conf import settings
        from django.test.utils import get_runner

        TestRunner = get_runner(settings, self.testrunner)

        test_runner = TestRunner(
            pattern=self.pattern,
            top_level=self.top_level_directory,
            verbosity=self.verbose,
            interactive=(not self.noinput),
            failfast=self.failfast,
            keepdb=self.keepdb,
            reverse=self.reverse,
            debug_sql=self.debug_sql,
            output_dir=self.output_dir)
        failures = test_runner.run_tests(self.test_labels)

        sys.exit(bool(failures)) 
Example 6
Project: cerberus-core   Author: ovh   File: initdb.py    GNU General Public License v3.0 6 votes vote down vote up
def initdb(settings):

    config_file = settings or os.getenv("APP_SETTINGS")
    environment = os.getenv("APP_ENV", "dev")

    config = read_config(config_file)

    import django
    from django.conf import settings

    if not settings.configured:
        settings.configure(**config["DJANGO"])
        django.setup()

    call_command(
        *("migrate", "--run-syncdb"), verbosity=0, interactive=False, out="/dev/null"
    )

    call_command(*("loaddata", "abuse/tests/fixtures.yaml"))

    create_app(environment=environment) 
Example 7
Project: pwned-passwords-django   Author: ubernostrum   File: runtests.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # Making Django run this way is a two-step process. First, call
    # settings.configure() to give Django settings to work with:
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)

    # Then, call django.setup() to initialize the application registry
    # and other bits:
    import django

    django.setup()

    # Now we instantiate a test runner...
    from django.test.utils import get_runner

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 8
Project: django-ads-txt   Author: flyingelephantlab   File: runtests.py    MIT License 6 votes vote down vote up
def runtests():
    import django
    from django.conf import settings

    # Compatibility with Django 1.7's stricter initialization
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)
    if hasattr(django, 'setup'):
        django.setup()

    from django.test.runner import DiscoverRunner
    test_args = ['tests']
    failures = DiscoverRunner(
            verbosity=1, interactive=True, failfast=False
    ).run_tests(test_args)
    sys.exit(failures) 
Example 9
Project: django-variantmpl   Author: tell-k   File: setup.py    MIT License 6 votes vote down vote up
def run_tests(self):
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings')

        test_dir = os.path.dirname(__file__)
        sys.path.insert(0, test_dir)
        import django
        from django.test.utils import get_runner
        from django.conf import settings
        django.setup()

        runner = get_runner(settings)(
            verbosity=1,
            interactive=False, failfast=False
        )
        errno = runner.run_tests(['tests'])
        sys.exit(errno) 
Example 10
Project: openode   Author: JvGinkel   File: __init__.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_database_engine_name():
    """returns name of the database engine,
    independently of the version of django
    - for django >=1.2 looks into ``settings.DATABASES['default']``,
    (i.e. assumes that openode uses database named 'default')
    , and for django 1.1 and below returns settings.DATABASE_ENGINE
    """
    import django
    from django.conf import settings as django_settings
    major_version = django.VERSION[0]
    minor_version = django.VERSION[1]
    if major_version == 1:
        if minor_version > 1:
            return django_settings.DATABASES['default']['ENGINE']
        else:
            return django_settings.DATABASE_ENGINE 
Example 11
Project: django_ai_arena   Author: YukkuriC   File: match_monitor.py    GNU General Public License v3.0 6 votes vote down vote up
def init_db(check=False):
    '''
    创建或打开监控进程使用的数据库
    返回其连接
    '''
    from django.conf import settings
    conn = connect(settings.MONITOR_DB_PATH)

    # 检查版本是否对应
    query = "select name from sqlite_master where name='%s' and type='table'" % settings.MONITOR_DB_VERSION

    if len(conn.execute(query).fetchall()) == 0:  # 非当前版本
        print('NEW DATABASE <%s>' % settings.MONITOR_DB_VERSION)

        # 非当前版本爆破重建
        q_tables = "select name from sqlite_master where type='table' and name<>'sqlite_sequence'"
        for table in conn.execute(q_tables).fetchall():
            conn.execute('drop table %s' % table)
        for query in settings.MONITOR_DB_TABLES:
            conn.execute(query)

    return conn 
Example 12
Project: spinach   Author: NicolasLM   File: test_django.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_django_app(capsys):
    django.conf.settings.configure(
        LOGGING_CONFIG=None,
        INSTALLED_APPS=('spinach.contrib.spinachd',),
        EMAIL_BACKEND='spinach.contrib.spinachd.mail.BackgroundEmailBackend',
        SPINACH_BROKER=MemoryBroker(),
        SPINACH_ACTUAL_EMAIL_BACKEND='django.core.mail.backends.'
                                     'console.EmailBackend'
    )
    django.setup()

    from spinach.contrib.spinachd import spin
    spin.schedule('spinachd:clear_expired_sessions')
    send_mail('Subject', 'Hello from email', '[email protected]',
              ['[email protected]'])

    call_command('spinach', '--stop-when-queue-empty')

    captured = capsys.readouterr()
    assert 'Hello from email' in captured.out 
Example 13
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: server.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_initial_setup(self):
        """
        This is triggered by the amp protocol when the connection
        to the portal has been established.
        This attempts to run the initial_setup script of the server.
        It returns if this is not the first time the server starts.
        Once finished the last_initial_setup_step is set to -1.
        """
        global INFO_DICT
        last_initial_setup_step = ServerConfig.objects.conf('last_initial_setup_step')
        if not last_initial_setup_step:
            # None is only returned if the config does not exist,
            # i.e. this is an empty DB that needs populating.
            INFO_DICT['info'] = ' Server started for the first time. Setting defaults.'
            initial_setup.handle_setup(0)
        elif int(last_initial_setup_step) >= 0:
            # a positive value means the setup crashed on one of its
            # modules and setup will resume from this step, retrying
            # the last failed module. When all are finished, the step
            # is set to -1 to show it does not need to be run again.
            INFO_DICT['info'] = ' Resuming initial setup from step {last}.'.format(
                  last=last_initial_setup_step)
            initial_setup.handle_setup(int(last_initial_setup_step)) 
Example 14
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: evennia_launcher.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_gamedir(path):
    """
    Set GAMEDIR based on path, by figuring out where the setting file
    is inside the directory tree. This allows for running the launcher
    from elsewhere than the top of the gamedir folder.

    """
    global GAMEDIR

    Ndepth = 10
    settings_path = os.path.join("server", "conf", "settings.py")
    os.chdir(GAMEDIR)
    for i in range(Ndepth):
        gpath = os.getcwd()
        if "server" in os.listdir(gpath):
            if os.path.isfile(settings_path):
                GAMEDIR = gpath
                return
        os.chdir(os.pardir)
    print(ERROR_NO_GAMEDIR)
    sys.exit() 
Example 15
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: evennia_launcher.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_dummyrunner(number_of_dummies):
    """
    Start an instance of the dummyrunner

    Args:
        number_of_dummies (int): The number of dummy accounts to start.

    Notes:
        The dummy accounts' behavior can be customized by adding a
        `dummyrunner_settings.py` config file in the game's conf/
        directory.

    """
    number_of_dummies = str(int(number_of_dummies)) if number_of_dummies else 1
    cmdstr = [sys.executable, EVENNIA_DUMMYRUNNER, "-N", number_of_dummies]
    config_file = os.path.join(SETTINGS_PATH, "dummyrunner_settings.py")
    if os.path.exists(config_file):
        cmdstr.extend(["--config", config_file])
    try:
        call(cmdstr, env=getenv())
    except KeyboardInterrupt:
        # this signals the dummyrunner to stop cleanly and should
        # not lead to a traceback here.
        pass 
Example 16
Project: encarnia   Author: whitehorse-io   File: server.py    MIT License 6 votes vote down vote up
def run_initial_setup(self):
        """
        This attempts to run the initial_setup script of the server.
        It returns if this is not the first time the server starts.
        Once finished the last_initial_setup_step is set to -1.
        """
        last_initial_setup_step = ServerConfig.objects.conf('last_initial_setup_step')
        if not last_initial_setup_step:
            # None is only returned if the config does not exist,
            # i.e. this is an empty DB that needs populating.
            print(' Server started for the first time. Setting defaults.')
            initial_setup.handle_setup(0)
            print('-' * 50)
        elif int(last_initial_setup_step) >= 0:
            # a positive value means the setup crashed on one of its
            # modules and setup will resume from this step, retrying
            # the last failed module. When all are finished, the step
            # is set to -1 to show it does not need to be run again.
            print(' Resuming initial setup from step %(last)s.' % \
                {'last': last_initial_setup_step})
            initial_setup.handle_setup(int(last_initial_setup_step))
            print('-' * 50) 
Example 17
Project: encarnia   Author: whitehorse-io   File: server.py    MIT License 6 votes vote down vote up
def at_post_portal_sync(self):
        """
        This is called just after the portal has finished syncing back data to the server
        after reconnecting.
        """
        # one of reload, reset or shutdown
        mode = self.getset_restart_mode()

        from evennia.scripts.monitorhandler import MONITOR_HANDLER
        MONITOR_HANDLER.restore(mode == 'reload')

        from evennia.scripts.tickerhandler import TICKER_HANDLER
        TICKER_HANDLER.restore(mode == 'reload')

        # after sync is complete we force-validate all scripts
        # (this also starts any that didn't yet start)
        ScriptDB.objects.validate(init_mode=mode)

        # delete the temporary setting
        ServerConfig.objects.conf("server_restart_mode", delete=True) 
Example 18
Project: encarnia   Author: whitehorse-io   File: evennia_launcher.py    MIT License 6 votes vote down vote up
def set_gamedir(path):
    """
    Set GAMEDIR based on path, by figuring out where the setting file
    is inside the directory tree.

    """
    global GAMEDIR

    Ndepth = 10
    settings_path = os.path.join("server", "conf", "settings.py")
    for i in range(Ndepth):
        gpath = os.getcwd()
        if "server" in os.listdir(gpath):
            if os.path.isfile(settings_path):
                GAMEDIR = gpath
                return
        os.chdir(os.pardir)
    print(ERROR_NO_GAMEDIR)
    sys.exit() 
Example 19
Project: encarnia   Author: whitehorse-io   File: evennia_launcher.py    MIT License 6 votes vote down vote up
def run_dummyrunner(number_of_dummies):
    """
    Start an instance of the dummyrunner

    Args:
        number_of_dummies (int): The number of dummy players to start.

    Notes:
        The dummy players' behavior can be customized by adding a
        `dummyrunner_settings.py` config file in the game's conf/
        directory.

    """
    number_of_dummies = str(int(number_of_dummies)) if number_of_dummies else 1
    cmdstr = [sys.executable, EVENNIA_DUMMYRUNNER, "-N", number_of_dummies]
    config_file = os.path.join(SETTINGS_PATH, "dummyrunner_settings.py")
    if os.path.exists(config_file):
        cmdstr.extend(["--config", config_file])
    try:
        call(cmdstr, env=getenv())
    except KeyboardInterrupt:
        # this signals the dummyrunner to stop cleanly and should
        # not lead to a traceback here.
        pass 
Example 20
Project: django-gstorage   Author: fyndiq   File: conftest.py    MIT License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': ':memory:'}},
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        INSTALLED_APPS=(
            'gstorage.apps.GStorageTestConfig',
        ),
    )

    try:
        import django
        django.setup()
    except AttributeError:
        pass 
Example 21
Project: homepage   Author: ianlewis   File: tests.py    MIT License 6 votes vote down vote up
def main():
    sys.exc_clear()

    os.environ['DJANGO_SETTINGS_MODULE'] = 'homepage.settings'
    os.environ['ENABLE_LOGGING'] = 'False'
    os.environ['DEBUG'] = 'True'

    import django
    from django.test.utils import get_runner
    from django.conf import settings

    django.setup()

    # TODO: settings
    test_runner = get_runner(settings)

    test_runner = test_runner()
    failures = test_runner.run_tests(None)

    sys.exit(failures) 
Example 22
Project: django-subscriptions   Author: kogan   File: runtests.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_tests():
    # First configure settings, then call django.setup() to initialise
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)
    import django

    django.setup()

    # Now create the test runner
    from django.test.utils import get_runner

    TestRunner = get_runner(settings)

    # And then we run tests and return the results.
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(["tests"])
    sys.exit(failures) 
Example 23
Project: winter   Author: mofr   File: conftest.py    MIT License 6 votes vote down vote up
def pytest_configure():
    from django.conf import settings
    settings.configure(
        ROOT_URLCONF='tests.urls',
        REST_FRAMEWORK={
            'DEFAULT_RENDERER_CLASSES': ('winter.json_renderer.JSONRenderer',),
            'UNAUTHENTICATED_USER': Guest,
        },
        TEMPLATES=[
            {
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'APP_DIRS': True,
                'OPTIONS': {
                    'debug': True,  # We want template errors to raise
                },
            },
        ],
        INSTALLED_APPS=(
            'tests',
        ),
    )
    django.setup() 
Example 24
Project: mos-horizon   Author: Mirantis   File: helpers.py    Apache License 2.0 6 votes vote down vote up
def tearDown(self):
        super(PluginTestCase, self).tearDown()
        conf.HORIZON_CONFIG = self.old_horizon_config
        # Destroy our singleton and re-create it.
        base.HorizonSite._instance = None
        del base.Horizon
        base.Horizon = base.HorizonSite()
        # Reload the convenience references to Horizon stored in __init__
        moves.reload_module(import_module("horizon"))
        # Re-register our original dashboards and panels.
        # This is necessary because autodiscovery only works on the first
        # import, and calling reload introduces innumerable additional
        # problems. Manual re-registration is the only good way for testing.
        for dash in self._discovered_dashboards:
            base.Horizon.register(dash)
            for panel in self._discovered_panels[dash]:
                dash.register(panel)
        self._reload_urls() 
Example 25
Project: byro   Author: byro   File: setup.py    Apache License 2.0 6 votes vote down vote up
def run(self):
        environ.setdefault("DJANGO_SETTINGS_MODULE", "byro.settings")
        try:
            import django
        except ImportError:  # Move to ModuleNotFoundError once we drop Python 3.5
            return
        django.setup()
        from django.conf import settings
        from django.core import management

        settings.COMPRESS_ENABLED = True
        settings.COMPRESS_OFFLINE = True

        management.call_command("compilemessages", verbosity=1)
        management.call_command("collectstatic", verbosity=1, interactive=False)
        management.call_command("compress", verbosity=1)
        build.run(self) 
Example 26
Project: elasticsearch-engine   Author: theofilis   File: fields.py    GNU General Public License v2.0 6 votes vote down vote up
def autofield_get_prep_value(self, value):
        if value is None:
            return None
        return unicode(value)


# def pre_init_mongodb_signal(sender, args, **kwargs):
#     if sender._meta.abstract:
#         return
#
#     from django.conf import settings
#
#     database = settings.DATABASES[sender.objects.db]
#     if 'elasticsearch' not in database['ENGINE']:
#         return
#
#     if not hasattr(django, 'MODIFIED') and isinstance(sender._meta.pk, DJAutoField):
#         pk = sender._meta.pk
#         setattr(pk, "to_python", autofield_to_python)
#         setattr(pk, "get_prep_value", autofield_get_prep_value) 
Example 27
Project: django-elephant   Author: jairhenrique   File: conftest.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pytest_configure():
    """ pytest setup. """

    import django
    from django.conf import settings

    settings.configure(
        DEBUG=False,
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:'
            }
        },
        SECRET_KEY='fake',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
            'django.middleware.csrf.CsrfViewMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
        ),
        CACHES={
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'
            }
        }
    )

    if django.get_version() >= '1.7':
        django.setup() 
Example 28
Project: munch-core   Author: crunchmail   File: run.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def cron(**options):
    "Run periodic task dispatcher."
    from django.conf import settings
    if hasattr(settings, 'CELERY_ALWAYS_EAGER') and \
            settings.CELERY_ALWAYS_EAGER:
        raise click.ClickException(
            'Disable CELERY_ALWAYS_EAGER in your '
            'settings file to spawn workers.')

    from munch.core.celery import app
    app.Beat(**options).run() 
Example 29
Project: django-rest-framework-core-filters   Author: eofs   File: conftest.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def pytest_configure():
    from django.conf import settings

    settings.configure(
        DEBUG_PROPAGATE_EXCEPTIONS=True,
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3',
                               'NAME': ':memory:'}},
        SITE_ID=1,
        SECRET_KEY='not very secret in tests',
        USE_I18N=True,
        USE_L10N=True,
        STATIC_URL='/static/',
        ROOT_URLCONF='tests.urls',
        TEMPLATE_LOADERS=(
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ),
        MIDDLEWARE_CLASSES=(
            'django.middleware.common.CommonMiddleware',
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.contrib.messages.middleware.MessageMiddleware',
        ),
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.sites',
            'django.contrib.staticfiles',

            'core_filters',
            'tests',
        ),
    )

    try:
        import django
        django.setup()
    except AttributeError:
        pass 
Example 30
Project: ithz   Author: ergoithz   File: template.py    MIT License 5 votes vote down vote up
def _swap_settings(new):
  settings = django.conf.settings
  old = {}
  for key, value in new.iteritems():
    old[key] = getattr(settings, key, None)
    setattr(settings, key, value)
  return old 
Example 31
Project: GTDWeb   Author: lanbing510   File: makemessages.py    GNU General Public License v2.0 5 votes vote down vote up
def copy_plural_forms(self, msgs, locale):
        """
        Copies plural forms header contents from a Django catalog of locale to
        the msgs string, inserting it at the right place. msgs should be the
        contents of a newly created .po file.
        """
        django_dir = os.path.normpath(os.path.join(os.path.dirname(upath(django.__file__))))
        if self.domain == 'djangojs':
            domains = ('djangojs', 'django')
        else:
            domains = ('django',)
        for domain in domains:
            django_po = os.path.join(django_dir, 'conf', 'locale', locale, 'LC_MESSAGES', '%s.po' % domain)
            if os.path.exists(django_po):
                with io.open(django_po, 'r', encoding='utf-8') as fp:
                    m = plural_forms_re.search(fp.read())
                if m:
                    plural_form_line = force_str(m.group('value'))
                    if self.verbosity > 1:
                        self.stdout.write("copying plural forms: %s\n" % plural_form_line)
                    lines = []
                    found = False
                    for line in msgs.split('\n'):
                        if not found and (not line or plural_forms_re.search(line)):
                            line = '%s\n' % plural_form_line
                            found = True
                        lines.append(line)
                    msgs = '\n'.join(lines)
                    break
        return msgs 
Example 32
Project: django-cryptography   Author: georgemarshall   File: setup.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self):
        if self.verbosity > 0:
            # ensure that deprecation warnings are displayed during testing
            # the following state is assumed:
            # logging.capturewarnings is true
            # a "default" level warnings filter has been added for
            # DeprecationWarning. See django.conf.LazySettings._configure_logging
            logger = logging.getLogger('py.warnings')
            handler = logging.StreamHandler()
            logger.addHandler(handler)
        TestCommand.run(self)
        if self.verbosity > 0:
            # remove the testing-specific handler
            logger.removeHandler(handler) 
Example 33
Project: repomaker   Author: f-droid   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def execute(params):
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "repomaker.settings_desktop")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise

    # create DATA_DIR if it doesn't exist
    from django.conf import settings
    if not os.path.isdir(settings.DATA_DIR):
        os.makedirs(settings.DATA_DIR)

    if len(sys.argv) > 1 and sys.argv[1] == 'process_tasks':
        non_atomic_background_tasks()

    # execute pending command
    execute_from_command_line(params) 
Example 34
Project: django-uidfield   Author: ivelum   File: setup.py    MIT License 5 votes vote down vote up
def run(self):
        from django.conf import settings
        settings.configure(
            DATABASES={'default': {
                'NAME': ':memory:',
                'ENGINE': 'django.db.backends.sqlite3'}
            },
            INSTALLED_APPS=('django_uidfield', 'django.contrib.contenttypes')
        )
        from django.core.management import call_command
        import django

        django.setup()

        call_command('test', 'django_uidfield') 
Example 35
Project: cerberus-core   Author: ovh   File: test.py    GNU General Public License v3.0 5 votes vote down vote up
def run_tests(settings, pattern):

    config_file = (
        settings or os.getenv("APP_SETTINGS") or "abuse/tests/settings-test.yml"
    )
    config = read_config(config_file)
    pattern = pattern or "test*.py"

    try:
        if (
            not config["DJANGO"]["DEBUG"]
            or not config["DJANGO"]["DATABASES"]["default"].get("TEST")
            or not os.getenv("APP_ENV") == "test"
        ):
            print('\n/!\ Invalid tests settings "{}"\n'.format(config_file))
            sys.exit(1)
    except KeyError:
        print('\n/!\ Invalid test settings "{}"\n'.format(config_file))
        sys.exit(1)

    import django
    from django.conf import settings

    if not settings.configured:
        settings.configure(**config["DJANGO"])
        django.setup()

    call_command(
        *("migrate", "--run-syncdb"), verbosity=0, interactive=False, out="/dev/null"
    )

    app = create_app(environment="test")

    with app.app_context():
        call_command("test", "abuse.tests", "--pattern", pattern, interactive=False) 
Example 36
Project: cerberus-core   Author: ovh   File: test.py    GNU General Public License v3.0 5 votes vote down vote up
def read_config(config_file):
    # Locate the config file to use
    if not os.path.isfile(config_file):
        print("Missing configuration file")
        return {}

    # Open and read the config file
    with codecs.open(config_file, "r", "utf8") as file_handler:
        conf = yaml.load(file_handler)
    if conf is None:
        conf = {}
    return conf 
Example 37
Project: cerberus-core   Author: ovh   File: initdb.py    GNU General Public License v3.0 5 votes vote down vote up
def read_config(config_file):
    # Locate the config file to use
    if not os.path.isfile(config_file):
        print("Missing configuration file")
        return {}

    # Open and read the config file
    with codecs.open(config_file, "r", "utf8") as file_handler:
        conf = yaml.load(file_handler)
    if conf is None:
        conf = {}
    return conf 
Example 38
Project: cerberus-core   Author: ovh   File: config.py    GNU General Public License v3.0 5 votes vote down vote up
def read_config_from_file(settings_file):

    # Locate the config file to use
    if not os.path.isfile(settings_file):
        print("Missing configuration file")
        sys.exit(1)

    # Open and read the config file
    with codecs.open(settings_file, "r", "utf8") as file_handler:
        conf = yaml.load(file_handler)
    if conf is None:
        conf = {}
    return conf 
Example 39
Project: django-ical   Author: jazzband   File: tests.py    MIT License 5 votes vote down vote up
def main():
    """
    Standalone django model test with a 'memory-only-django-installation'.
    You can play with a django model without a complete django app installation.
    http://www.djangosnippets.org/snippets/1044/
    """
    os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
    from django.conf import global_settings

    global_settings.SECRET_KEY = "snakeoil"
    global_settings.TIME_ZONE = "UTC"

    global_settings.INSTALLED_APPS = ("django.contrib.contenttypes", "django_ical")
    global_settings.DATABASES = {
        "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
    }

    global_settings.MIDDLEWARE_CLASSES = (
        "django.middleware.common.CommonMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
    )

    if django.VERSION > (1, 7):
        django.setup()

    from django.test.utils import get_runner

    test_runner = get_runner(global_settings)

    test_runner = test_runner()
    failures = test_runner.run_tests(["django_ical"])
    sys.exit(failures) 
Example 40
Project: django-admin-rq   Author: Proper-Job   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url
        urls = super(JobAdminMixin, self).get_urls()
        info = self.model._meta.app_label, self.model._meta.model_name

        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)

            return update_wrapper(wrapper, view)

        job_urls = [
            url(
                r'^job/(?P<job_name>[a-zA-Z-_]+)/form/(?P<object_id>\d{1,10})?$',
                wrap(self.job_form),
                name='%s_%s_job_form' % info
            ),
            url(
                r'^job/(?P<job_name>[a-zA-Z-_]+)/(?P<view_name>(preview_run|main_run))/(?P<object_id>\d{1,10})?$',
                wrap(self.job_run),
                name='%s_%s_job_run' % info
            ),
            url(
                r'^job/(?P<job_name>[a-zA-Z-_]+)/complete/(?P<object_id>\d{1,10})?$',
                wrap(self.job_complete),
                name='%s_%s_job_complete' % info
            ),
        ]
        return job_urls + urls 
Example 41
Project: django-compiling-loader   Author: mhallin   File: run_benchmark.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def switch_loader_settings(new_param):
    from django.conf import settings
    from django.template import loader

    settings.TEMPLATE_LOADERS = new_param
    loader.template_source_loaders = None 
Example 42
Project: EvenniaPluginSampleProject   Author: castlelorestudios   File: server.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def at_post_portal_sync(self, mode):
        """
        This is called just after the portal has finished syncing back data to the server
        after reconnecting.

        Args:
            mode (str): One of reload, reset or shutdown.

        """

        from evennia.scripts.monitorhandler import MONITOR_HANDLER
        MONITOR_HANDLER.restore(mode == 'reload')

        from evennia.scripts.tickerhandler import TICKER_HANDLER
        TICKER_HANDLER.restore(mode == 'reload')

        # after sync is complete we force-validate all scripts
        # (this also starts any that didn't yet start)
        ScriptDB.objects.validate(init_mode=mode)

        # start the task handler
        from evennia.scripts.taskhandler import TASK_HANDLER
        TASK_HANDLER.load()
        TASK_HANDLER.create_delays()

        # delete the temporary setting
        ServerConfig.objects.conf("server_restart_mode", delete=True) 
Example 43
Project: django-horizon   Author: uncovertruth   File: runtests.py    MIT License 5 votes vote down vote up
def runtests():
    import django
    from django.conf import settings
    from django.test.utils import get_runner

    if hasattr(django, 'setup'):
        django.setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=2, interactive=True)
    failures = test_runner.run_tests(['tests'])
    sys.exit(bool(failures)) 
Example 44
Project: encarnia   Author: whitehorse-io   File: server.py    MIT License 5 votes vote down vote up
def _server_maintenance():
    """
    This maintenance function handles repeated checks and updates that
    the server needs to do. It is called every 5 minutes.
    """
    global EVENNIA, _MAINTENANCE_COUNT, _FLUSH_CACHE, _GAMETIME_MODULE
    if not _FLUSH_CACHE:
        from evennia.utils.idmapper.models import conditional_flush as _FLUSH_CACHE
    if not _GAMETIME_MODULE:
        from evennia.utils import gametime as _GAMETIME_MODULE

    _MAINTENANCE_COUNT += 1

    now = time.time()
    if _MAINTENANCE_COUNT == 1:
        # first call after a reload
        _GAMETIME_MODULE.SERVER_START_TIME = now
        _GAMETIME_MODULE.SERVER_RUNTIME = ServerConfig.objects.conf("runtime", default=0.0)
    else:
        _GAMETIME_MODULE.SERVER_RUNTIME += 60.0
    # update game time and save it across reloads
    _GAMETIME_MODULE.SERVER_RUNTIME_LAST_UPDATED = now
    ServerConfig.objects.conf("runtime", _GAMETIME_MODULE.SERVER_RUNTIME)

    if _MAINTENANCE_COUNT % 300 == 0:
        # check cache size every 5 minutes
        _FLUSH_CACHE(_IDMAPPER_CACHE_MAXSIZE)
    if _MAINTENANCE_COUNT % 3600 == 0:
        # validate scripts every hour
        evennia.ScriptDB.objects.validate()
    if _MAINTENANCE_COUNT % 3700 == 0:
        # validate channels off-sync with scripts
        evennia.CHANNEL_HANDLER.update()
    ## Commenting this out, it is probably not needed
    ## with CONN_MAX_AGE set. Keeping it as a reminder
    ## if database-gone-away errors appears again /Griatch
    #if _MAINTENANCE_COUNT % 18000 == 0:
    #    connection.close() 
Example 45
Project: django-lookup-extensions   Author: uncovertruth   File: runtests.py    MIT License 5 votes vote down vote up
def runtests():
    from django.conf import settings
    from django.test.utils import get_runner

    django.setup()

    from .monkey_patch import replace_managers

    replace_managers()

    TestRunner = get_runner(settings)
    test_runner = TestRunner(
        verbosity=2,
        interactive=False,
        keepdb=True,
        debug_sql=True,
    )
    if os.environ.get('TEST_WITH_REDSHIFT', None) == 'yes':
        test_runner.keepdb = True
    failures = test_runner.run_tests([
        'test_lookup',
        'test_or_lookups',
        'test_reverse_lookup',
        'test_string_lookup',
    ])
    sys.exit(bool(failures)) 
Example 46
Project: django-simple-url   Author: sjoerdjob   File: runtests.py    MIT License 5 votes vote down vote up
def main():
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))
    sys.path.append(os.path.abspath(os.path.join(BASE_DIR, '..')))

    django.conf.settings.configure()
    django.setup()
    arguments = list(sys.argv)
    arguments.insert(1, 'test')
    django.core.management.execute_from_command_line(arguments) 
Example 47
Project: oracle-json-field   Author: Exscientia   File: setup.py    MIT License 5 votes vote down vote up
def run(self):
        from django.conf import settings
        import os

        oracle_json_host = os.environ.get('ORACLE_JSON_HOST', 'localhost')
        oracle_json_port = os.environ.get('ORACLE_JSON_PORT', '1521')
        oracle_json_sid  = os.environ.get('ORACLE_JSON_SID', 'orcl')
        oracle_json_user = os.environ.get('ORACLE_JSON_USER', 'test_user')
        oracle_json_pass = os.environ.get('ORACLE_JSON_PASS', 'test_pass')

        settings.configure(
            DATABASES={"default": {
              "ENGINE": "django.db.backends.oracle",
              "OPTIONS": {
                "threaded": True
              },
              "HOST": oracle_json_host,
              "PORT": oracle_json_port,
              "NAME": oracle_json_sid,
              "USER": oracle_json_user,
              "PASSWORD": oracle_json_pass
            }},
            INSTALLED_APPS=('oracle_json_field', 'django.contrib.contenttypes')
        )
        from django.core.management import call_command
        import django

        django.setup()
        call_command('test', 'oracle_json_field') 
Example 48
Project: citation   Author: comses   File: run_tests.py    GNU General Public License v3.0 5 votes vote down vote up
def run_tests():
    from django.test.utils import get_runner
    from django.conf import settings
    from django.core.management import call_command

    call_command('makemigrations')
    call_command('migrate')

    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)

    failures = test_runner.run_tests(['tests'])

    sys.exit(bool(failures)) 
Example 49
Project: dynaconf   Author: rochacbruno   File: __init__.py    MIT License 5 votes vote down vote up
def __getattribute__(self, name):
        if name == "settings":
            return settings
        else:
            return getattr(conf, name)


# This implementation is recommended by Guido Van Rossum
# https://mail.python.org/pipermail/python-ideas/2012-May/014969.html 
Example 50
Project: django-easy-uploader   Author: naritotakizawa   File: setup.py    MIT License 5 votes vote down vote up
def run_tests(self):
        # import here, cause outside the eggs aren't loaded
        import django
        from django.conf import settings
        from django.test.utils import get_runner
        os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
        django.setup()
        TestRunner = get_runner(settings)
        test_runner = TestRunner()
        failures = test_runner.run_tests(['tests'])
        sys.exit(bool(failures))