Here are the examples of the python api django.conf taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
137 Examples
3
Example 1
Project: django-webtest Source File: tests.py
def test_auth_is_enabled(self):
from django.conf import settings
auth_middleware = 'django_webtest.middleware.WebtestUserMiddleware'
assert auth_middleware in self.settings_middleware
assert 'django_webtest.backends.WebtestUserBackend' in settings.AUTHENTICATION_BACKENDS
dependency_index = self.settings_middleware.index(
'django.contrib.auth.middleware.AuthenticationMiddleware')
self.assertEqual(
self.settings_middleware.index(auth_middleware),
dependency_index + 1,
)
3
Example 2
Project: django_coverage_plugin Source File: plugin.py
def read_template_source(filename):
"""Read the source of a Django template, returning the Unicode text."""
# Import this late to be sure we don't trigger settings machinery too
# early.
from django.conf import settings
if not settings.configured:
settings.configure()
with open(filename, "rb") as f:
text = f.read().decode(settings.FILE_CHARSET)
return text
3
Example 3
Project: django-allauth Source File: app_settings.py
@property
def EMAIL_CONFIRMATION_EXPIRE_DAYS(self):
"""
Determines the expiration date of e-mail confirmation mails (#
of days)
"""
from django.conf import settings
return self._setting("EMAIL_CONFIRMATION_EXPIRE_DAYS",
getattr(settings, "EMAIL_CONFIRMATION_DAYS", 3))
3
Example 4
def teardown(state):
from django.conf import settings
# Removing the temporary TEMP_DIR. Ensure we pass in unicode
# so that it will successfully remove temp trees containing
# non-ASCII filenames on Windows. (We're assuming the temp dir
# name itself does not contain non-ASCII characters.)
shutil.rmtree(unicode(TEMP_DIR))
# Restore the old settings.
for key, value in state.items():
setattr(settings, key, value)
3
Example 5
Project: django-calaccess-campaign-browser Source File: setup.py
def run(self):
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'
}
},
INSTALLED_APPS=('calaccess_campaign_browser',),
MIDDLEWARE_CLASSES=()
)
from django.core.management import call_command
import django
if django.VERSION[:2] >= (1, 7):
django.setup()
call_command('test', 'calaccess_campaign_browser')
3
Example 6
Project: pytest-services Source File: django_settings.py
def clean_django_settings():
"""Clean current django settings."""
from django.conf import settings as django_settings
del os.environ['DJANGO_SETTINGS_MODULE']
django_settings._wrapped = None
3
Example 7
Project: shuup Source File: conf.py
def initialize_django():
os.environ['DJANGO_SETTINGS_MODULE'] = 'shuup_workbench.settings'
from django.conf import settings
# Set USE_I18N=False to avoid warnings from import-time ugettext calls
settings.USE_I18N = False
django.setup()
3
Example 8
Project: nose-performance Source File: plugin.py
def patch_interfaces(self):
self._calls = []
try:
from django.conf import settings
if not settings.configured:
raise ImportError
except ImportError:
pass
else:
self.patch_django_interfaces()
try:
__import__('redis')
except ImportError:
pass
else:
self.patch_redis_interfaces()
3
Example 9
Project: openode Source File: __init__.py
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
3
Example 10
Project: django-allauth Source File: app_settings.py
@property
def EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL(self):
"""
The URL to redirect to after a successful e-mail confirmation, in
case no user is logged in
"""
from django.conf import settings
return self._setting("EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL",
settings.LOGIN_URL)
3
Example 11
def run_tests():
if not os.environ.get("DJANGO_SETTINGS_MODULE", False):
setup_django_settings()
import django
from django.conf import settings
from django.test.utils import get_runner
if django.VERSION[1] >= 7: # Django 1.7.x or above
django.setup()
runner = get_runner(settings,"django.test.runner.DiscoverRunner")
else:
runner = get_runner(settings,"django.test.simple.DjangoTestSuiteRunner")
test_suite = runner(verbosity=2, interactive=True, failfast=False)
return test_suite.run_tests(["django_comments_xtd"])
3
Example 12
def syncdb(self, interactive=True):
from django.conf import settings
from django.db.utils import DEFAULT_DB_ALIAS
dbconf = settings.DATABASES[DEFAULT_DB_ALIAS]
if dbconf['ENGINE'] == 'django.db.backends.sqlite3':
if Path(dbconf['NAME']).absolute().exists():
return
gp, getpass.getpass = getpass.getpass, getpass.fallback_getpass
try:
self.management.call_command('syncdb', interactive=interactive)
finally:
getpass.getpass = gp
3
Example 13
Project: lettuce Source File: basehttp.py
def __init__(self, application, media_dir=None):
from django.conf import settings
self.application = application
if not media_dir:
import django
self.media_dir = \
os.path.join(django.__path__[0], 'contrib', 'admin', 'media')
else:
self.media_dir = media_dir
self.media_url = settings.ADMIN_MEDIA_PREFIX
3
Example 14
Project: django-compositepks Source File: basehttp.py
def __init__(self, *args, **kwargs):
from django.conf import settings
self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
# We set self.path to avoid crashes in log_message() on unsupported
# requests (like "OPTIONS").
self.path = ''
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
3
Example 15
Project: pytest-services Source File: django_settings.py
def setup_django_settings(test_settings):
"""Override the enviroment variable and call the _setup method of the settings object to reload them."""
os.environ['DJANGO_SETTINGS_MODULE'] = test_settings
from django.conf import settings as django_settings
# (re)setup django settings
django_settings._setup()
# reload settings
reload_settings(django_settings)
3
Example 16
def _load_settings(self):
from feincms import default_settings
from django.conf import settings as django_settings
for key in dir(default_settings):
if not key.startswith('FEINCMS_'):
continue
value = getattr(default_settings, key)
value = getattr(django_settings, key, value)
setattr(self, key, value)
3
Example 17
Project: django-webtest Source File: tests.py
def test_sessions_disabled(self):
from django.conf import settings
apps = list(settings.INSTALLED_APPS)
apps.remove("django.contrib.sessions")
settings.INSTALLED_APPS= apps
response = self.app.get('/')
self.assertEqual(response.status_int, 200)
self.assertEqual({}, self.app.session)
3
Example 18
Project: django-robots Source File: runtests.py
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)
3
Example 19
Project: django-mini Source File: tests.py
@patch(url_import_patch)
@patch('django.core.management.execute_from_command_line')
def test_main_admin2(self, execute_from_command_line, import_module):
# main() calls Django's execute_from_command_line() to do the work.
from django.conf import settings
argv = 'django-mini --admin runserver'.split()
djangomini.main(argv)
execute_from_command_line.assert_called_once_with(['django-mini', 'runserver'])
3
Example 20
def run_tests():
setup()
from django.conf import settings
from django.test.utils import get_runner
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.run_tests(
['nested_formset'],
)
sys.exit(failures)
3
Example 21
Project: django-rest-marshmallow Source File: conftest.py
def pytest_configure():
from django.conf import settings
settings.configure()
try:
import django
django.setup()
except AttributeError:
pass
3
Example 22
Project: django-jsonfield Source File: setup.py
def run(self):
from django.conf import settings
settings.configure(
DATABASES={'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'}},
INSTALLED_APPS=('jsonfield',)
)
from django.core.management import call_command
import django
if django.VERSION[:2] >= (1, 7):
django.setup()
call_command('test', 'jsonfield')
3
Example 23
Project: django-jinja Source File: tests.py
def test_get_default_none(self):
from django.conf import global_settings
from django_jinja.backend import Jinja2
with self.settings(TEMPLATES=global_settings.TEMPLATES):
with self.assertRaisesRegexp(ImproperlyConfigured, r'No Jinja2 backend is configured'):
Jinja2.get_default()
3
Example 24
def configure(self):
from django.conf import settings
from cyme import settings as default_settings
from cyme.utils import imerge_settings
mod = os.environ.setdefault('DJANGO_SETTINGS_MODULE',
default_settings.__name__)
if not settings.configured:
if django.VERSION < (1, 4):
self.management.setup_environ(import_module(mod))
else:
imerge_settings(settings, default_settings)
if self.instance_dir:
settings.CYME_INSTANCE_DIR = self.instance_dir
3
Example 25
Project: talk.org Source File: basehttp.py
def __init__(self, application, media_dir=None):
from django.conf import settings
self.application = application
if not media_dir:
import django
self.media_dir = django.__path__[0] + '/contrib/admin/media'
else:
self.media_dir = media_dir
self.media_url = settings.ADMIN_MEDIA_PREFIX
3
Example 26
Project: biggraphite Source File: test_utils.py
def prepare_graphite():
"""Make sure that we have a working Graphite environment."""
# Setup sys.path
prepare_graphite_imports()
os.environ['DJANGO_SETTINGS_MODULE'] = 'graphite.settings'
# Redirect logs somewhere writable
from django.conf import settings
settings.LOG_DIR = tempfile.gettempdir()
# Setup Django
import django
django.setup()
3
Example 27
Project: django-nonrel Source File: basehttp.py
def __init__(self, *args, **kwargs):
from django.conf import settings
self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
# We set self.path to avoid crashes in log_message() on unsupported
# requests (like "OPTIONS").
self.path = ''
self.style = color_style()
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
3
Example 28
Project: lino Source File: __init__.py
def site_startup():
"""Called from `lino.models` before Django 1.7"""
# print "site_startup"
from django.conf import settings
if False:
settings.SITE.startup()
else:
try:
settings.SITE.startup()
except ImportError as e:
import traceback
# traceback.print_exc(e)
# sys.exit(-1)
raise Exception("ImportError during startup:\n" +
traceback.format_exc(e))
3
Example 29
Project: django-yamlfield Source File: setup.py
def run(self):
from django.conf import settings
settings.configure(
DATABASES={
'default': {
'NAME': ':memory:',
'ENGINE': 'django.db.backends.sqlite3'
}
},
MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=('yamlfield',)
)
from django.core.management import call_command
import django
django.setup()
call_command('test', 'yamlfield')
3
Example 30
def django_tests(verbosity, interactive, failfast, test_labels):
from django.conf import settings
state = setup(verbosity, test_labels)
extra_tests = []
# Run the test suite, including the extra validation tests.
from django.test.utils import get_runner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
failfast=failfast)
failures = test_runner.run_tests(test_labels or get_test_modules(), extra_tests=extra_tests)
teardown(state)
return failures
3
Example 31
def _setting(self, name, dflt):
from django.conf import settings
getter = getattr(settings,
'ALLAUTH_SETTING_GETTER',
lambda name, dflt: getattr(settings, name, dflt))
return getter(self.prefix + name, dflt)
3
Example 32
Project: GAE-Bulk-Mailer Source File: basehttp.py
def __init__(self, *args, **kwargs):
from django.conf import settings
self.admin_static_prefix = urljoin(settings.STATIC_URL, 'admin/')
# We set self.path to avoid crashes in log_message() on unsupported
# requests (like "OPTIONS").
self.path = ''
self.style = color_style()
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
3
Example 33
Project: django-allauth Source File: app_settings.py
@property
def AUTHENTICATION_METHOD(self):
from django.conf import settings
if hasattr(settings, "ACCOUNT_EMAIL_AUTHENTICATION"):
import warnings
warnings.warn("ACCOUNT_EMAIL_AUTHENTICATION is deprecated,"
" use ACCOUNT_AUTHENTICATION_METHOD",
DeprecationWarning)
if getattr(settings, "ACCOUNT_EMAIL_AUTHENTICATION"):
ret = self.AuthenticationMethod.EMAIL
else:
ret = self.AuthenticationMethod.USERNAME
else:
ret = self._setting("AUTHENTICATION_METHOD",
self.AuthenticationMethod.USERNAME)
return ret
3
Example 34
Project: django-nonrel Source File: basehttp.py
def get_base_url(self):
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
if not settings.ADMIN_MEDIA_PREFIX:
raise ImproperlyConfigured(
"The ADMIN_MEDIA_PREFIX setting can't be empty "
"when using the AdminMediaHandler, e.g. with runserver.")
return settings.ADMIN_MEDIA_PREFIX
2
Example 35
def setUp(self):
import django.conf
self._original_settings = django.conf.settings
django.conf.settings = django.conf.LazySettings()
2
Example 36
def _django_setup():
"""Imports and configures Django.
This can be overridden by defining a function named
webapp_django_setup() in the app's appengine_config.py file (see
lib_config docs). Such a function should import and configure
Django.
In the Python 2.5 runtime, you can also just configure the Django version to
be used by setting webapp_django_version in that file.
Finally, calling use_library('django', <version>) in that file
should also work:
# Example taken from from
# https://developers.google.com/appengine/docs/python/tools/libraries#Django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')
In the Python 2.7 runtime, the Django version is specified in you app.yaml
file and use_library is not supported.
If your application also imports Django directly it should ensure
that the same code is executed before your app imports Django
(directly or indirectly). Perhaps the simplest way to ensure that
is to include the following in your main.py (and in each alternate
main script):
from google.appengine.ext.webapp import template
import django
This will ensure that whatever Django setup code you have included
in appengine_config.py is executed, as a side effect of importing
the webapp.template module.
"""
if os.environ.get('APPENGINE_RUNTIME') != 'python27':
__django_version_setup()
import django
import django.conf
try:
getattr(django.conf.settings, 'FAKE_ATTR', None)
except (ImportError, EnvironmentError), e:
if os.getenv(django.conf.ENVIRONMENT_VARIABLE):
logging.warning(e)
try:
django.conf.settings.configure(
DEBUG=False,
TEMPLATE_DEBUG=False,
TEMPLATE_LOADERS=(
'django.template.loaders.filesystem.load_template_source',
),
)
except (EnvironmentError, RuntimeError):
pass
2
Example 37
Project: importd Source File: __init__.py
def _configure_django(self, **kw):
"""Auto-Configure Django using arguments."""
from django.conf import settings, global_settings
self.settings = settings
if settings.configured:
return
self.APP_DIR, app_filename = os.path.split(
os.path.realpath(inspect.stack()[2][1])
)
DEBUG = kw.get("DEBUG", False)
md = {}
dp = {}
for k, v in kw.items():
if isinstance(v, E):
md[k] = v.value
setattr(global_esettings, k, v.value)
if isinstance(v, DSetting):
dp[k] = v
for k, v in md.items():
kw[k] = v
for k, v in dp.items():
if DEBUG:
if v.dvalue is not NotSet:
kw[k] = v.dvalue
else:
if v.pvalue is not NotSet:
kw[k] = v.pvalue
del md
del dp
def do_dp(key):
if key not in kw:
return
old = kw[key]
kw[key] = []
for value in old:
if DEBUG:
if value.startswith("prod:"):
continue
kw[key].append(value.replace("debug:", ""))
else:
if value.startswith("debug:"):
continue
kw[key].append(value.replace("prod:", ""))
s_found = 0
sd = {}
for k, v in kw.items():
if isinstance(v, MirrorSetting):
s_found += 1
if s_found > MirrorSetting.count:
raise ImproperlyConfiguredError
sd[k] = v
if MirrorSetting.count > s_found:
raise ImproperlyConfiguredError
for k, v in sd.items():
kw[k] = kw[v.name]
del sd
del s_found
do_dp("MIDDLEWARE_CLASSES")
do_dp("INSTALLED_APPS")
do_dp("TEMPLATE_CONTEXT_PROCESSORS")
if "debug" in kw:
db = kw.pop("debug")
if DEBUG:
kw.update(db)
if "regexers" in kw:
self.update_regexers(kw.pop("regexers"))
self.mounts = kw.pop("mounts", {})
if not kw.get("dont_configure", False):
kw["ROOT_URLCONF"] = kw.get("ROOT_URLCONF", "importd.urlconf")
if "TEMPLATE_DIRS" not in kw:
kw["TEMPLATE_DIRS"] = (self.dotslash("templates"), )
if "STATIC_URL" not in kw:
kw["STATIC_URL"] = "/static/"
if "STATIC_ROOT" not in kw:
kw["STATIC_ROOT"] = self.dotslash("staticfiles")
if "STATICFILES_DIRS" not in kw:
kw["STATICFILES_DIRS"] = [self.dotslash("static")]
if "MEDIA_URL" not in kw:
kw["MEDIA_URL"] = "/static/media/"
if "lr" in kw:
self.lr = kw.pop("lr")
if "db" in kw:
if isinstance(kw["db"], basestring):
kw["DATABASES"] = {
"default": dj_database_url.parse(kw.pop("db"))
}
else:
db = kw.pop("db")
default = dj_database_url.parse(db[0])
default.update(db[1])
kw["DATABASES"] = dict(default=default)
if "DATABASES" not in kw:
kw["DATABASES"] = {
"default": {
'ENGINE': "django.db.backends.sqlite3",
'NAME': self.dotslash("db.sqlite")
}
}
self.smart_return = False
if kw.pop("SMART_RETURN", True):
self.smart_return = True
if "MIDDLEWARE_CLASSES" not in kw:
kw["MIDDLEWARE_CLASSES"] = (
global_settings.MIDDLEWARE_CLASSES
)
kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
kw["MIDDLEWARE_CLASSES"].append(
"importd.SmartReturnMiddleware"
)
installed = list(kw.setdefault("INSTALLED_APPS", []))
admin_url = kw.pop("admin", "^admin/")
if admin_url:
if "django.contrib.auth" not in installed:
installed.append("django.contrib.auth")
if "django.contrib.contenttypes" not in installed:
installed.append("django.contrib.contenttypes")
if "django.contrib.auth" not in installed:
installed.append("django.contrib.auth")
if "django.contrib.messages" not in installed:
installed.append("django.contrib.messages")
if "django.contrib.sessions" not in installed:
installed.append("django.contrib.sessions")
# check session middleware installed
# https://docs.djangoproject.com/en/1.7/topics/http/sessions/#enabling-sessions
last_position = len(kw["MIDDLEWARE_CLASSES"])
kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
kw["MIDDLEWARE_CLASSES"].insert(
last_position,
"django.contrib.sessions.middleware.SessionMiddleware"
)
if "django.contrib.admin" not in installed:
installed.append("django.contrib.admin")
kw["MIDDLEWARE_CLASSES"].append(
"django.contrib.auth.middleware"
".AuthenticationMiddleware"
)
if "django.contrib.humanize" not in installed:
installed.append("django.contrib.humanize")
if "django.contrib.staticfiles" not in installed:
installed.append("django.contrib.staticfiles")
if "debug_toolbar" not in installed and debug_toolbar:
installed.append("debug_toolbar")
if 'INTERNAL_IPS' not in kw:
kw['INTERNAL_IPS'] = ('127.0.0.1', '0.0.0.0')
kw['MIDDLEWARE_CLASSES'].insert(
1,
'debug_toolbar.middleware.DebugToolbarMiddleware')
kw['DEBUG_TOOLBAR_PANELS'] = (
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
)
# This one gives 500 if its Enabled without previous syncdb
# 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',
kw['INSTALLED_APPS'] = installed
if "DEBUG" not in kw:
kw["DEBUG"] = kw["TEMPLATE_DEBUG"] = True
if "APP_DIR" not in kw:
kw["APP_DIR"] = self.APP_DIR
if "SECRET_KEY" not in kw:
kw["SECRET_KEY"] = self.get_secret_key()
# admins and managers
if "ADMINS" not in kw:
kw["ADMINS"] = kw["MANAGERS"] = ((getuser(), ""), )
autoimport = kw.pop("autoimport", True)
kw["SETTINGS_MODULE"] = kw.get("SETTINGS_MODULE", "importd")
settings.configure(**kw)
if hasattr(django, "setup"):
django.setup()
self._import_django()
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = self.get_urlpatterns()
urlpatterns += staticfiles_urlpatterns()
if autoimport:
# django depends on INSTALLED_APPS's model
for app in settings.INSTALLED_APPS:
self._import_app_module("{}.admin", app)
self._import_app_module("{}.models", app)
if admin_url:
from django.contrib import admin
try:
from django.conf.urls import include
except ImportError:
from django.conf.urls.defaults import include # lint:ok
admin.autodiscover()
self.add_view(admin_url, include(admin.site.urls))
if autoimport:
# import .views and .forms for each installed app
for app in settings.INSTALLED_APPS:
self._import_app_module("{}.forms", app)
self._import_app_module("{}.views", app)
self._import_app_module("{}.signals", app)
# import blueprints from config
self.blueprints = kw.pop("blueprints", {})
for namespace, meta in self.blueprints.items():
if isinstance(meta, basestring):
meta = {"blueprint": meta}
mod_path, bp_name = meta["blueprint"].rsplit(".", 1)
mod = importlib.import_module(mod_path)
bp = getattr(mod, bp_name)
self.register_blueprint(
bp, url_prefix=meta.get("url_prefix", namespace + "/"),
namespace=namespace, app_name=meta.get("app_name", ""))
self._configured = True
2
Example 38
Project: zulip Source File: runtornado.py
def handle(self, addrport, **options):
# type: (str, **bool) -> None
interactive_debug_listen()
import django
from tornado import httpserver, web
try:
addr, port = addrport.split(':')
except ValueError:
addr, port = '', addrport
if not addr:
addr = '127.0.0.1'
if not port.isdigit():
raise CommandError("%r is not a valid port number." % (port,))
xheaders = options.get('xheaders', True)
no_keep_alive = options.get('no_keep_alive', False)
quit_command = 'CTRL-C'
if settings.DEBUG:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(levelname)-8s %(message)s')
def inner_run():
# type: () -> None
from django.conf import settings
from django.utils import translation
translation.activate(settings.LANGUAGE_CODE)
print("Validating Django models.py...")
self.validate(display_num_errors=True)
print("\nDjango version %s" % (django.get_version()))
print("Tornado server is running at http://%s:%s/" % (addr, port))
print("Quit the server with %s." % (quit_command,))
if settings.USING_RABBITMQ:
queue_client = get_queue_client()
# Process notifications received via RabbitMQ
queue_client.register_json_consumer('notify_tornado', process_notification)
queue_client.register_json_consumer('tornado_return', respond_send_message)
try:
urls = (r"/notify_tornado",
r"/json/events",
r"/api/v1/events",
)
# Application is an instance of Django's standard wsgi handler.
application = web.Application([(url, AsyncDjangoHandler) for url in urls]
+ get_sockjs_router().urls,
debug=django.conf.settings.DEBUG,
# Disable Tornado's own request logging, since we have our own
log_function=lambda x: None)
# start tornado web server in single-threaded mode
http_server = httpserver.HTTPServer(application,
xheaders=xheaders,
no_keep_alive=no_keep_alive)
http_server.listen(int(port), address=addr)
setup_event_queue()
add_client_gc_hook(missedmessage_hook)
setup_tornado_rabbitmq()
instance = ioloop.IOLoop.instance()
if django.conf.settings.DEBUG:
instance.set_blocking_log_threshold(5)
instance.handle_callback_exception=handle_callback_exception
instance.start()
except KeyboardInterrupt:
sys.exit(0)
inner_run()
0
Example 39
Project: PyClassLessons Source File: base.py
def execute(self, *args, **options):
"""
Try to execute this command, performing system checks if needed (as
controlled by attributes ``self.requires_system_checks`` and
``self.requires_model_validation``, except if force-skipped).
"""
self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
if options.get('no_color'):
self.style = no_style()
self.stderr = OutputWrapper(options.get('stderr', sys.stderr))
os.environ[str("DJANGO_COLORS")] = str("nocolor")
else:
self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)
if self.can_import_settings:
from django.conf import settings # NOQA
saved_locale = None
if not self.leave_locale_alone:
# Only mess with locales if we can assume we have a working
# settings file, because django.utils.translation requires settings
# (The final saying about whether the i18n machinery is active will be
# found in the value of the USE_I18N setting)
if not self.can_import_settings:
raise CommandError("Incompatible values of 'leave_locale_alone' "
"(%s) and 'can_import_settings' (%s) command "
"options." % (self.leave_locale_alone,
self.can_import_settings))
# Switch to US English, because django-admin.py creates database
# content like permissions, and those shouldn't contain any
# translations.
from django.utils import translation
saved_locale = translation.get_language()
translation.activate('en-us')
try:
if (self.requires_system_checks and
not options.get('skip_validation') and # This will be removed at the end of deprecation process for `skip_validation`.
not options.get('skip_checks')):
self.check()
output = self.handle(*args, **options)
if output:
if self.output_transaction:
# This needs to be imported here, because it relies on
# settings.
from django.db import connections, DEFAULT_DB_ALIAS
connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
if connection.ops.start_transaction_sql():
self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()))
finally:
if saved_locale is not None:
translation.activate(saved_locale)
0
Example 40
def execute_tests():
"""
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/
"""
import django
sys.exc_clear()
os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings"
from django.conf import global_settings
global_settings.INSTALLED_APPS = ()
global_settings.MIDDLEWARE_CLASSES = ()
global_settings.SECRET_KEY = "not-very-secret"
global_settings.DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
# http://django.readthedocs.org/en/latest/releases/1.7.html#standalone-scripts
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(['s3cache'])
sys.exit(failures)
0
Example 41
def __getattr__(self, item):
from django.conf import settings
return getattr(settings, item)
0
Example 42
Project: GAE-Bulk-Mailer Source File: makemessages.py
def make_messages(locale=None, domain='django', verbosity=1, all=False,
extensions=None, symlinks=False, ignore_patterns=None, no_wrap=False,
no_location=False, no_obsolete=False, stdout=sys.stdout):
"""
Uses the ``locale/`` directory from the Django Git tree or an
application/project to process all files with translatable literals for
the :param domain: domain and :param locale: locale.
"""
# Need to ensure that the i18n framework is enabled
from django.conf import settings
if settings.configured:
settings.USE_I18N = True
else:
settings.configure(USE_I18N = True)
if ignore_patterns is None:
ignore_patterns = []
invoked_for_django = False
if os.path.isdir(os.path.join('conf', 'locale')):
localedir = os.path.abspath(os.path.join('conf', 'locale'))
invoked_for_django = True
# Ignoring all contrib apps
ignore_patterns += ['contrib/*']
elif os.path.isdir('locale'):
localedir = os.path.abspath('locale')
else:
raise CommandError("This script should be run from the Django Git "
"tree or your project or app tree. If you did indeed run it "
"from the Git checkout or your project or application, "
"maybe you are just missing the conf/locale (in the django "
"tree) or locale (for project and application) directory? It "
"is not created automatically, you have to create it by hand "
"if you want to enable i18n for your project or application.")
if domain not in ('django', 'djangojs'):
raise CommandError("currently makemessages only supports domains 'django' and 'djangojs'")
if (locale is None and not all) or domain is None:
message = "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1])
raise CommandError(message)
# We require gettext version 0.15 or newer.
output, errors, status = _popen('xgettext --version')
if status != STATUS_OK:
raise CommandError("Error running xgettext. Note that Django "
"internationalization requires GNU gettext 0.15 or newer.")
match = re.search(r'(?P<major>\d+)\.(?P<minor>\d+)', output)
if match:
xversion = (int(match.group('major')), int(match.group('minor')))
if xversion < (0, 15):
raise CommandError("Django internationalization requires GNU "
"gettext 0.15 or newer. You are using version %s, please "
"upgrade your gettext toolset." % match.group())
locales = []
if locale is not None:
locales.append(str(locale))
elif all:
locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
locales = [os.path.basename(l) for l in locale_dirs]
wrap = '--no-wrap' if no_wrap else ''
location = '--no-location' if no_location else ''
for locale in locales:
if verbosity > 0:
stdout.write("processing language %s\n" % locale)
basedir = os.path.join(localedir, locale, 'LC_MESSAGES')
if not os.path.isdir(basedir):
os.makedirs(basedir)
pofile = os.path.join(basedir, '%s.po' % str(domain))
potfile = os.path.join(basedir, '%s.pot' % str(domain))
if os.path.exists(potfile):
os.unlink(potfile)
for dirpath, file in find_files(".", ignore_patterns, verbosity,
stdout, symlinks=symlinks):
process_file(file, dirpath, potfile, domain, verbosity, extensions,
wrap, location, stdout)
if os.path.exists(potfile):
write_po_file(pofile, potfile, domain, locale, verbosity, stdout,
not invoked_for_django, wrap, location, no_obsolete)
0
Example 43
Project: talk.org Source File: basehttp.py
def __init__(self, *args, **kwargs):
from django.conf import settings
self.admin_media_prefix = settings.ADMIN_MEDIA_PREFIX
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
0
Example 44
Project: GAE-Bulk-Mailer Source File: templates.py
def handle(self, app_or_project, name, target=None, **options):
self.app_or_project = app_or_project
self.paths_to_remove = []
self.verbosity = int(options.get('verbosity'))
# If it's not a valid directory name.
if not re.search(r'^[_a-zA-Z]\w*$', name):
# Provide a smart error message, depending on the error.
if not re.search(r'^[_a-zA-Z]', name):
message = ('make sure the name begins '
'with a letter or underscore')
else:
message = 'use only numbers, letters and underscores'
raise CommandError("%r is not a valid %s name. Please %s." %
(name, app_or_project, message))
# if some directory is given, make sure it's nicely expanded
if target is None:
top_dir = path.join(os.getcwd(), name)
try:
os.makedirs(top_dir)
except OSError as e:
if e.errno == errno.EEXIST:
message = "'%s' already exists" % top_dir
else:
message = e
raise CommandError(message)
else:
top_dir = os.path.abspath(path.expanduser(target))
if not os.path.exists(top_dir):
raise CommandError("Destination directory '%s' does not "
"exist, please create it first." % top_dir)
extensions = tuple(
handle_extensions(options.get('extensions'), ignored=()))
extra_files = []
for file in options.get('files'):
extra_files.extend(map(lambda x: x.strip(), file.split(',')))
if self.verbosity >= 2:
self.stdout.write("Rendering %s template files with "
"extensions: %s\n" %
(app_or_project, ', '.join(extensions)))
self.stdout.write("Rendering %s template files with "
"filenames: %s\n" %
(app_or_project, ', '.join(extra_files)))
base_name = '%s_name' % app_or_project
base_subdir = '%s_template' % app_or_project
base_directory = '%s_directory' % app_or_project
context = Context(dict(options, **{
base_name: name,
base_directory: top_dir,
}), autoescape=False)
# Setup a stub settings environment for template rendering
from django.conf import settings
if not settings.configured:
settings.configure()
template_dir = self.handle_template(options.get('template'),
base_subdir)
prefix_length = len(template_dir) + 1
for root, dirs, files in os.walk(template_dir):
path_rest = root[prefix_length:]
relative_dir = path_rest.replace(base_name, name)
if relative_dir:
target_dir = path.join(top_dir, relative_dir)
if not path.exists(target_dir):
os.mkdir(target_dir)
for dirname in dirs[:]:
if dirname.startswith('.') or dirname == '__pycache__':
dirs.remove(dirname)
for filename in files:
if filename.endswith(('.pyo', '.pyc', '.py.class')):
# Ignore some files as they cause various breakages.
continue
old_path = path.join(root, filename)
new_path = path.join(top_dir, relative_dir,
filename.replace(base_name, name))
if path.exists(new_path):
raise CommandError("%s already exists, overlaying a "
"project or app into an existing "
"directory won't replace conflicting "
"files" % new_path)
# Only render the Python files, as we don't want to
# accidentally render Django templates files
with open(old_path, 'rb') as template_file:
content = template_file.read()
if filename.endswith(extensions) or filename in extra_files:
content = content.decode('utf-8')
template = Template(content)
content = template.render(context)
content = content.encode('utf-8')
with open(new_path, 'wb') as new_file:
new_file.write(content)
if self.verbosity >= 2:
self.stdout.write("Creating %s\n" % new_path)
try:
shutil.copymode(old_path, new_path)
self.make_writeable(new_path)
except OSError:
self.stderr.write(
"Notice: Couldn't set permission bits on %s. You're "
"probably using an uncommon filesystem setup. No "
"problem." % new_path, self.style.NOTICE)
if self.paths_to_remove:
if self.verbosity >= 2:
self.stdout.write("Cleaning up temporary files.\n")
for path_to_remove in self.paths_to_remove:
if path.isfile(path_to_remove):
os.remove(path_to_remove)
else:
shutil.rmtree(path_to_remove,
onerror=rmtree_errorhandler)
0
Example 45
Project: Cactus_Refactored Source File: site.py
def build_static(self, dist=False):
"""
Copy static files to build folder.
"""
from django.conf import settings
buildpath = self.paths["dist" if dist else "build"]
s = os.path.join(buildpath, settings.STATIC_URL_REL)
# If there is a folder, replace it with a symlink
if os.path.exists(s):
shutil.rmtree(s)
def ignore_special(src, names):
bn = os.path.basename(src)
if bn == settings.STATIC_URL_NAME:
return self.config.get('build', {}).get('discard_static', [])
return []
shutil.copytree(
self.paths['static'],
s,
ignore=ignore_special
)
0
Example 46
def get_internal_wsgi_application():
"""
Loads and returns the WSGI application as configured by the user in
``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
this will be the ``application`` object in ``projectname/wsgi.py``.
This function, and the ``WSGI_APPLICATION`` setting itself, are only useful
for Django's internal servers (runserver, runfcgi); external WSGI servers
should just be configured to point to the correct application object
directly.
If settings.WSGI_APPLICATION is not set (is ``None``), we just return
whatever ``django.core.wsgi.get_wsgi_application`` returns.
"""
from django.conf import settings
app_path = getattr(settings, 'WSGI_APPLICATION')
if app_path is None:
return get_wsgi_application()
module_name, attr = app_path.rsplit('.', 1)
try:
mod = import_module(module_name)
except ImportError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"could not import module '%s': %s" % (app_path, module_name, e))
try:
app = getattr(mod, attr)
except AttributeError as e:
raise ImproperlyConfigured(
"WSGI application '%s' could not be loaded; "
"can't find '%s' in module '%s': %s"
% (app_path, attr, module_name, e))
return app
0
Example 47
Project: djangae Source File: indexing.py
def add_special_index(model_class, field_name, indexer, operator, value=None):
from djangae.utils import in_testing
from django.conf import settings
index_type = indexer.prepare_index_type(operator, value)
field_name = field_name.encode("utf-8") # Make sure we are working with strings
load_special_indexes()
if special_index_exists(model_class, field_name, index_type):
return
if environment.is_production_environment() or (
in_testing() and not getattr(settings, "GENERATE_SPECIAL_INDEXES_DURING_TESTING", False)
):
raise RuntimeError(
"There is a missing index in your djangaeidx.yaml - \n\n{0}:\n\t{1}: [{2}]".format(
_get_table_from_model(model_class), field_name, index_type
)
)
_project_special_indexes.setdefault(
_get_table_from_model(model_class), {}
).setdefault(field_name, []).append(str(index_type))
write_special_indexes()
0
Example 48
def get_commands(load_user_commands=True, project_directory=None):
"""
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
startproject command will be disabled, and the startapp command
will be modified to use the directory in which that module appears.
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.
"""
global _commands
if _commands is None:
_commands = dict([(name, 'django.core') for name in find_commands(__path__[0])])
if load_user_commands:
# Get commands from all installed apps.
from django.conf import settings
for app_name in settings.INSTALLED_APPS:
try:
path = find_management_module(app_name)
_commands.update(dict([(name, app_name) for name in find_commands(path)]))
except ImportError:
pass # No management module -- ignore this app.
if project_directory:
# Remove the "startproject" command from self.commands, because
# that's a django-admin.py command, not a manage.py command.
del _commands['startproject']
# Override the startapp command so that it always uses the
# project_directory, not the current working directory
# (which is default).
from django.core.management.commands.startapp import ProjectCommand
_commands['startapp'] = ProjectCommand(project_directory)
return _commands
0
Example 49
Project: django-object-tools Source File: __init__.py
def old_autodiscover():
"""
Auto-discover INSTALLED_APPS tools.py modules and fail silently when
not present. This forces an import on them to register any object
tools they may want.
"""
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's tools module.
try:
import_module('%s.tools' % app)
except:
# Decide whether to bubble up this error. If the app just
# doesn't have an tools module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'tools'):
raise
0
Example 50
Project: django-setuptest Source File: setuptest.py
def configure(self):
"""
Configures Django settings.
"""
import django
from django.conf import settings
try:
from django.utils.importlib import import_module
except ImportError:
from importlib import import_module
try:
test_settings = import_module('test_settings')
except ImportError as e:
log.info('ImportError: Unable to import test settings: %s' % e)
sys.exit(1)
setting_attrs = {}
for attr in dir(test_settings):
if '__' not in attr:
setting_attrs[attr] = getattr(test_settings, attr)
if not settings.configured:
settings.configure(**setting_attrs)
if hasattr(django, 'setup'):
django.setup()