我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用django.conf()。
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))
def run(self): from django.conf import settings settings.configure( INSTALLED_APPS=('collectionfield.tests',), SECRET_KEY='AAA', DATABASES={ 'default': { 'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3' } }, MIDDLEWARE_CLASSES = () ) from django.core.management import call_command import django django.setup() call_command('test', 'collectionfield')
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()
def run(self): from django.conf import settings settings.configure( DATABASES={ 'default': { 'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3' } }, INSTALLED_APPS=('calaccess_processed',), MIDDLEWARE_CLASSES=() ) from django.core.management import call_command import django django.setup() call_command('test', 'calaccess_processed')
def get_sanic_application(): """ Sets up django and returns a Sanic application """ if sys.version_info < (3, 5): raise RuntimeError("The SanicDjango Adaptor may only be used with python 3.5 and above.") django.setup() from django.conf import settings DEBUG = getattr(settings, 'DEBUG', False) INSTALLED_APPS = getattr(settings, 'INSTALLED_APPS', []) do_static = DEBUG and 'django.contrib.staticfiles' in INSTALLED_APPS app = Sanic(__name__) if do_static: static_url = getattr(settings, 'STATIC_URL', "/static/") static_root = getattr(settings, 'STATIC_ROOT', "./static") app.static(static_url, static_root) app.handle_request = SanicHandler(app) # patch the app to use the django adaptor handler return app
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
def setUpClass(cls): from django.test.utils import setup_test_environment from django.core.management import call_command from django.conf import settings settings.configure( INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'lifter.contrib.django', ], DATABASES={ 'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'} }, ) django.setup() setup_test_environment() super(DjangoTestCase, cls).setUpClass() call_command('migrate')
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))
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
def get_idp_sso_supported_bindings(idp_entity_id=None, config=None): """Returns the list of bindings supported by an IDP This is not clear in the pysaml2 code, so wrapping it in a util""" if config is None: # avoid circular import from djangosaml2.conf import get_config config = get_config() # load metadata store from config meta = getattr(config, 'metadata', {}) # if idp is None, assume only one exists so just use that if idp_entity_id is None: # .keys() returns dict_keys in python3.5+ try: idp_entity_id = list(available_idps(config).keys())[0] except IndexError: raise ImproperlyConfigured("No IdP configured!") try: return meta.service(idp_entity_id, 'idpsso_descriptor', 'single_sign_on_service').keys() except UnknownSystemEntity: return []
def run_tests(base_dir=None, apps=None, verbosity=1, interavtive=False): base_dir = base_dir or os.path.dirname(__file__) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' sys.path.insert(0, os.path.join(base_dir, 'src')) sys.path.insert(0, os.path.join(base_dir, 'tests')) import django if django.VERSION >= (1,7): django.setup() from django.conf import settings from django.test.utils import get_runner TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=verbosity, interavtive=interavtive, failfast=False) if apps: app_tests = [x.strip() for x in apps if x] else: app_tests = [ 'notification' ] failures = test_runner.run_tests(app_tests) sys.exit(bool(failures))
def runtests(args=None): test_dir = os.path.dirname(__file__) sys.path.insert(0, test_dir) os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' import django from django.test.utils import get_runner from django.conf import settings django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) args = args or ['.'] failures = test_runner.run_tests(args) sys.exit(failures)
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
def dump_rsyncd(self): lines = [] if self.runs_pubd: lines.extend(( "# Automatically generated, do not edit", "port = %d" % self.rsync_port, "address = %s" % self.hostname, "log file = rsyncd.log", "read only = yes", "use chroot = no", "[rpki]", "path = %s" % self.publication_base_directory, "comment = RPKI test")) if self.is_root: assert self.runs_pubd lines.extend(( "[root]", "path = %s" % self.publication_root_directory, "comment = RPKI test root")) if lines: with open(self.path("rsyncd.conf"), "w") as f: if not quiet: print "Writing", f.name f.writelines(line + "\n" for line in lines)
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(['registration.tests']) sys.exit(bool(failures))
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))
def run_tests(): settings_mod = os.environ.get('DJANGO_SETTINGS_MODULE', 'test_settings') os.environ['DJANGO_SETTINGS_MODULE'] = settings_mod import django django.setup() from django.test.utils import get_runner from django.conf import settings test_filter = os.environ.get('TEST_FILTER') test_labels = [test_filter] if test_filter else [] test_runner = get_runner(settings) failures = test_runner( pattern='test_*.py', verbosity=1, interactive=True ).run_tests(test_labels) sys.exit(failures)
def import_chromosome_names(): """ Parse GCA accession XML to import chromosome name and chromosome types into genseq table. """ import django from django.conf import settings django.setup() from rfam_schemas.RfamLive.models import Genome, Genseq for genome in Genome.objects.exclude(assembly_acc__isnull=True).all(): print genome.assembly_acc if 'GCF' in genome.assembly_acc: continue data = fetch_gca_data(genome.upid, genome.assembly_acc, 'kingdom') if 'fields' in data and 'chromosomes' in data and data['fields']['chromosomes']: for chromosome in data['fields']['chromosomes']: genseq = Genseq.objects.filter(rfamseq_acc=chromosome['accession'], upid=genome.upid).first() if genseq: genseq.chromosome_type = chromosome['type'] genseq.chromosome_name = chromosome['name'] genseq.save() # -----------------------------------------------------------------------------
def run_protractor(): """Start Protractor with the MAAS JS E2E testing configuration. 1. Start regiond. 2. Start rackd. 3. Start xvfb. 4. Start chromium webdriver. 5. Run protractor. 6. Stop chromium webdriver. 7. Stop xvfb. 8. Stop rackd. 9. Stop regiond. """ with MAASRegionServiceFixture(), MAASClusterServiceFixture(): with DisplayFixture(), ChromiumWebDriverFixture(): protractor = Popen(( "bin/protractor", "src/maastesting/protractor/protractor.conf.js")) protractor_exit = protractor.wait() sys.exit(protractor_exit)
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))