Python django.core() Examples

The following are 11 code examples of django.core(). 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 django , or try the search function .
Example #1
Source File: runtests.py    From pinax-starter-app with MIT License 6 votes vote down vote up
def runtests(*test_args):
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pinax.{{ app_name }}.tests.settings")
    django.setup()

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    from django.core import checks

    try:
        from django.test.runner import DiscoverRunner
        runner_class = DiscoverRunner
        if not test_args:
            test_args = ["pinax.{{ app_name }}.tests"]
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        runner_class = DjangoTestSuiteRunner
        test_args = ["tests"]

    checks = checks.run_checks()
    if checks:
        sys.exit(checks)
    failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures) 
Example #2
Source File: django_micro.py    From django-micro with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run():
    if not settings.configured:
        raise ImproperlyConfigured("You should call configure() after configuration define.")

    if _parent_module.__name__ == '__main__':
        from django.core.management import execute_from_command_line
        execute_from_command_line(sys.argv)
    else:
        from django.core.wsgi import get_wsgi_application
        return get_wsgi_application() 
Example #3
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_commands():
    """
    Returns a dictionary mapping command names to their callback applications.

    This works by looking for a management.commands package in django.core, and
    in each installed application -- if a commands package exists, all commands
    in that package are registered.

    Core commands are always included. If a settings module has been
    specified, user-defined commands will also be included.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(upath(__path__[0]))}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example #4
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def main_help_text(self, commands_only=False):
        """
        Returns the script's main help text, as a string.
        """
        if commands_only:
            usage = sorted(get_commands().keys())
        else:
            usage = [
                "",
                "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
                "",
                "Available subcommands:",
            ]
            commands_dict = collections.defaultdict(lambda: [])
            for name, app in six.iteritems(get_commands()):
                if app == 'django.core':
                    app = 'django'
                else:
                    app = app.rpartition('.')[-1]
                commands_dict[app].append(name)
            style = color_style()
            for app in sorted(commands_dict.keys()):
                usage.append("")
                usage.append(style.NOTICE("[%s]" % app))
                for name in sorted(commands_dict[app]):
                    usage.append("    %s" % name)
            # Output an extra note if settings are not properly configured
            if self.settings_exception is not None:
                usage.append(style.NOTICE(
                    "Note that only Django core commands are listed "
                    "as settings are not properly configured (error: %s)."
                    % self.settings_exception))

        return '\n'.join(usage) 
Example #5
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

    Core commands are always included. If a settings module has been
    specified, also include user-defined commands.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__path__[0])}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example #6
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def main_help_text(self, commands_only=False):
        """Return the script's main help text, as a string."""
        if commands_only:
            usage = sorted(get_commands())
        else:
            usage = [
                "",
                "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
                "",
                "Available subcommands:",
            ]
            commands_dict = defaultdict(lambda: [])
            for name, app in get_commands().items():
                if app == 'django.core':
                    app = 'django'
                else:
                    app = app.rpartition('.')[-1]
                commands_dict[app].append(name)
            style = color_style()
            for app in sorted(commands_dict):
                usage.append("")
                usage.append(style.NOTICE("[%s]" % app))
                for name in sorted(commands_dict[app]):
                    usage.append("    %s" % name)
            # Output an extra note if settings are not properly configured
            if self.settings_exception is not None:
                usage.append(style.NOTICE(
                    "Note that only Django core commands are listed "
                    "as settings are not properly configured (error: %s)."
                    % self.settings_exception))

        return '\n'.join(usage) 
Example #7
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application -- if a commands package exists, register all
    commands in that package.

    Core commands are always included. If a settings module has been
    specified, also include user-defined commands.

    The dictionary is in the format {command_name: app_name}. Key-value
    pairs from this dictionary can then be used in calls to
    load_command_class(app_name, command_name)

    If a specific version of a command must be loaded (e.g., with the
    startapp command), the instantiated module can be placed in the
    dictionary in place of the application name.

    The dictionary is cached on the first call and reused on subsequent
    calls.
    """
    commands = {name: 'django.core' for name in find_commands(__path__[0])}

    if not settings.configured:
        return commands

    for app_config in reversed(list(apps.get_app_configs())):
        path = os.path.join(app_config.path, 'management')
        commands.update({name: app_config.name for name in find_commands(path)})

    return commands 
Example #8
Source File: __init__.py    From DeerU with GNU General Public License v3.0 5 votes vote down vote up
def main_help_text(self, commands_only=False):
        """Return the script's main help text, as a string."""
        if commands_only:
            usage = sorted(get_commands())
        else:
            usage = [
                "",
                "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,
                "",
                "Available subcommands:",
            ]
            commands_dict = defaultdict(lambda: [])
            for name, app in get_commands().items():
                if app == 'django.core':
                    app = 'django'
                else:
                    app = app.rpartition('.')[-1]
                commands_dict[app].append(name)
            style = color_style()
            for app in sorted(commands_dict):
                usage.append("")
                usage.append(style.NOTICE("[%s]" % app))
                for name in sorted(commands_dict[app]):
                    usage.append("    %s" % name)
            # Output an extra note if settings are not properly configured
            if self.settings_exception is not None:
                usage.append(style.NOTICE(
                    "Note that only Django core commands are listed "
                    "as settings are not properly configured (error: %s)."
                    % self.settings_exception))

        return '\n'.join(usage) 
Example #9
Source File: migrate.py    From django-subscriptions with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def migrate(name):
    from django.conf import settings

    settings.configure(**SETTINGS_DICT)
    import django

    django.setup()

    from django.core import management

    management.call_command("makemigrations", "subscriptions", name=name) 
Example #10
Source File: setup.py    From byro with Apache License 2.0 5 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 #11
Source File: database.py    From django-cloud-deploy with Apache License 2.0 4 votes vote down vote up
def with_cloud_sql_proxy(self,
                             project_id: str,
                             instance_name: str,
                             cloud_sql_proxy_path: Optional[str] = None,
                             region: str = 'us-west1',
                             port: int = 5432):
        """A context manager to run and kill cloud sql proxy subprocesses.

        Used to provides secure access to your Cloud SQL Second Generation
        instances without having to whitelist IP addresses or configure SSL.
        For more information:
        https://cloud.google.com/sql/docs/postgres/sql-proxy

        Args:
            project_id: GCP project id.
            instance_name: Name of the Cloud SQL instance cloud sql proxy
                targets at.
            cloud_sql_proxy_path: The command to run your cloud sql proxy.
            region: Where the Cloud SQL instance is in.
            port: The port your Postgres database is using. By default it is
                5432.

        Yields:
            None

        Raises:
            DatabaseError: If cloud sql proxy failed to start after 5 seconds.
        """
        try:
            db.close_old_connections()
        except django.core.exceptions.ImproperlyConfigured:
            # The Django environment is not correctly setup. This might be
            # because we are calling Django management commands with subprocess
            # calls. In this case the subprocess we are calling will handle
            # closing of old connections.
            pass
        instance_connection_string = '{0}:{1}:{2}'.format(
            project_id, region, instance_name)
        instance_flag = '-instances={}=tcp:{}'.format(
            instance_connection_string, port)
        if cloud_sql_proxy_path is None:
            cloud_sql_proxy_path = shutil.which('cloud_sql_proxy')
            assert cloud_sql_proxy_path, 'could not find cloud_sql_proxy_path'
        process = popen_spawn.PopenSpawn([cloud_sql_proxy_path, instance_flag])
        try:
            # Make sure cloud sql proxy is started before doing the real work
            process.expect('Ready for new connections', timeout=60)
            yield
        except pexpect.exceptions.TIMEOUT:
            raise DatabaseError(
                ('Cloud SQL Proxy was unable to start after 60 seconds. Output '
                 'of cloud_sql_proxy: \n{}').format(process.before))
        except pexpect.exceptions.EOF:
            raise DatabaseError(
                ('Cloud SQL Proxy exited unexpectedly. Output of '
                 'cloud_sql_proxy: \n{}').format(process.before))
        finally:
            process.kill(signal.SIGTERM)