Python源码示例:django.core()
示例1
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)
示例2
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)
示例3
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()
示例4
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
示例5
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)
示例6
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
示例7
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)
示例8
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
示例9
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)
示例10
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)
示例11
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)