Python django.setup() Examples
The following are 30
code examples of django.setup().
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: ex4_delete_devices.py From pynet with Apache License 2.0 | 6 votes |
def main(): ''' Remove the two objects created in exercise #3 from the database. ''' django.setup() try: test_rtr1 = NetworkDevice.objects.get(device_name='test-rtr1') test_rtr2 = NetworkDevice.objects.get(device_name='test-rtr2') test_rtr1.delete() test_rtr2.delete() except NetworkDevice.DoesNotExist: pass # Verify devices that currently exist print devices = NetworkDevice.objects.all() for a_device in devices: print a_device print
Example #2
Source File: test_models.py From scale with Apache License 2.0 | 6 votes |
def setUp(self): django.setup() self.job_exe_1 = job_test_utils.create_job_exe() self.job_type_1_id = self.job_exe_1.job.job_type.id self.job_exe_2 = job_test_utils.create_job_exe() self.job_type_2_id = self.job_exe_2.job.job_type.id self.product_1 = prod_test_utils.create_product() self.product_2 = prod_test_utils.create_product(has_been_published=True) self.product_3 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True) time.sleep(0.001) self.last_modified_start = now() self.product_4 = prod_test_utils.create_product() self.product_5 = prod_test_utils.create_product(self.job_exe_2) self.product_6 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True) time.sleep(0.001) self.product_7 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True) time.sleep(0.001) self.product_8 = prod_test_utils.create_product(has_been_published=True) self.last_modified_end = now()
Example #3
Source File: tests.py From botbuilder-python with MIT License | 6 votes |
def test_log_info(self): """Tests an info trace telemetry is properly sent""" django.setup() logger = logging.getLogger(__name__) msg = "An info message" logger.info(msg) event = self.get_events(1) data = event["data"]["baseData"] props = data["properties"] self.assertEqual( event["name"], "Microsoft.ApplicationInsights.Message", "Event type" ) self.assertEqual(event["iKey"], TEST_IKEY) self.assertEqual(data["message"], msg, "Log message") self.assertEqual(data["severityLevel"], 1, "Severity level") self.assertEqual(props["fileName"], "tests.py", "Filename property") self.assertEqual(props["level"], "INFO", "Level property") self.assertEqual(props["module"], "tests", "Module property")
Example #4
Source File: tests.py From botbuilder-python with MIT License | 6 votes |
def test_log_error(self): """Tests an error trace telemetry is properly sent""" django.setup() logger = logging.getLogger(__name__) msg = "An error log message" logger.error(msg) event = self.get_events(1) data = event["data"]["baseData"] props = data["properties"] self.assertEqual( event["name"], "Microsoft.ApplicationInsights.Message", "Event type" ) self.assertEqual(event["iKey"], TEST_IKEY) self.assertEqual(data["message"], msg, "Log message") self.assertEqual(data["severityLevel"], 3, "Severity level") self.assertEqual(props["fileName"], "tests.py", "Filename property") self.assertEqual(props["level"], "ERROR", "Level property") self.assertEqual(props["module"], "tests", "Module property")
Example #5
Source File: __init__.py From py2swagger with MIT License | 6 votes |
def run(self, arguments, *args, **kwargs): try: os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', arguments.django_settings) import django if hasattr(django, 'setup'): django.setup() except ImportError: raise Py2SwaggerPluginException('Invalid django settings module') from .introspectors.api import ApiIntrospector from .urlparser import UrlParser # Patch Djago REST Framework, to make inspection process slightly easier from . import injection apis = UrlParser().get_apis(filter_path=arguments.filter) a = ApiIntrospector(apis) return a.inspect()
Example #6
Source File: runtests.py From pinax-documents with MIT License | 6 votes |
def runtests(*test_args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) # Compatibility with Django 1.7's stricter initialization if hasattr(django, "setup"): django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) try: from django.test.runner import DiscoverRunner runner_class = DiscoverRunner test_args = ["pinax.documents.tests"] except ImportError: from django.test.simple import DjangoTestSuiteRunner runner_class = DjangoTestSuiteRunner test_args = ["tests"] failures = runner_class(verbosity=1, interactive=True, failfast=False).run_tests(test_args) sys.exit(failures)
Example #7
Source File: quicktest.py From django-classified with MIT License | 6 votes |
def _tests(self): settings.configure( DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(self.DIRNAME, 'database.db'), } }, INSTALLED_APPS=self.INSTALLED_APPS + self.apps, MIDDLEWARE=self.MIDDLEWARE, ROOT_URLCONF='django_classified.tests.urls', STATIC_URL='/static/', TEMPLATES=self.TEMPLATES, SITE_ID=1 ) from django.test.runner import DiscoverRunner test_runner = DiscoverRunner() django.setup() failures = test_runner.run_tests(self.apps) if failures: sys.exit(failures)
Example #8
Source File: conf.py From django-ftpserver with MIT License | 6 votes |
def setup_django(): import django from django.conf import settings if not settings.configured: settings.configure( DEBUG=True, DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django_ftpserver', ) ) django.setup() from django.apps import apps if not apps.ready: apps.populate()
Example #9
Source File: runtests.py From django-taxii-services with BSD 3-Clause "New" or "Revised" License | 6 votes |
def runtests(): os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() # By default, run all of the tests tests = ['tests'] # Allow running a subset of tests via the command line. if len(sys.argv) > 1: tests = sys.argv[1:] failures = test_runner.run_tests(tests, verbosity=3) if failures: sys.exit(failures)
Example #10
Source File: generate_integration_bots_avatars.py From zulip with Apache License 2.0 | 6 votes |
def generate_integration_bots_avatars(check_missing: bool=False) -> None: missing = set() for webhook in WEBHOOK_INTEGRATIONS: if not webhook.logo_path: continue bot_avatar_path = webhook.get_bot_avatar_path() if bot_avatar_path is None: continue bot_avatar_path = os.path.join(ZULIP_PATH, 'static', bot_avatar_path) if check_missing: if not os.path.isfile(bot_avatar_path): missing.add(webhook.name) else: create_integration_bot_avatar(static_path(webhook.logo_path), bot_avatar_path) if missing: print('ERROR: Bot avatars are missing for these webhooks: {}.\n' 'ERROR: Run ./tools/setup/generate_integration_bots_avatars.py ' 'to generate them.\nERROR: Commit the newly generated avatars to ' 'the repository.'.format(', '.join(missing))) sys.exit(1)
Example #11
Source File: runtests.py From django-cassandra-engine with BSD 2-Clause "Simplified" License | 6 votes |
def main(): default_cass = import_module('settings.default_cassandra') default_only_cass = import_module('settings.default_only_cassandra') secondary_cassandra = import_module('settings.secondary_cassandra') multi_cassandra = import_module('settings.multi_cassandra') metadata_disabled = import_module('settings.metadata_disabled') django.setup() run_tests(default_cass) run_tests(default_only_cass) run_tests(secondary_cassandra) run_tests(multi_cassandra) run_tests(metadata_disabled) sys.exit(0)
Example #12
Source File: setup.py From django-cryptography with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #13
Source File: runtests.py From django-rest-framework-docs with BSD 2-Clause "Simplified" License | 6 votes |
def run_tests_coverage(): if __name__ == "__main__": os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() # Setup Coverage cov = coverage(source=["rest_framework_docs"], omit=["rest_framework_docs/__init__.py"]) cov.start() failures = test_runner.run_tests(["tests"]) if bool(failures): cov.erase() sys.exit("Tests Failed. Coverage Cancelled.") # If success show coverage results cov.stop() cov.save() cov.report() cov.html_report(directory='covhtml')
Example #14
Source File: runtests.py From pwned-passwords-django with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #15
Source File: ex1b_link_credentials.py From pynet with Apache License 2.0 | 6 votes |
def main(): """Link credentials to devices""" django.setup() net_devices = NetworkDevice.objects.all() creds = Credentials.objects.all() std_creds = creds[0] arista_creds = creds[1] for a_device in net_devices: if 'arista' in a_device.device_type: a_device.credentials = arista_creds else: a_device.credentials = std_creds a_device.save() for a_device in net_devices: print a_device, a_device.credentials
Example #16
Source File: ex6_threads_show_ver.py From pynet with Apache License 2.0 | 6 votes |
def main(): ''' Use threads and Netmiko to connect to each of the devices in the database. Execute 'show version' on each device. Record the amount of time required to do this. ''' django.setup() start_time = datetime.now() devices = NetworkDevice.objects.all() for a_device in devices: my_thread = threading.Thread(target=show_version, args=(a_device,)) my_thread.start() main_thread = threading.currentThread() for some_thread in threading.enumerate(): if some_thread != main_thread: print some_thread some_thread.join() print "\nElapsed time: " + str(datetime.now() - start_time)
Example #17
Source File: ex2_vendor_field.py From pynet with Apache License 2.0 | 6 votes |
def main(): ''' Set the vendor field for each NetworkDevice to the appropriate vendor. Save this field to the database. ''' django.setup() devices = NetworkDevice.objects.all() for a_device in devices: if 'cisco' in a_device.device_type: a_device.vendor = 'Cisco' elif 'juniper' in a_device.device_type: a_device.vendor = 'Juniper' elif 'arista' in a_device.device_type: a_device.vendor = 'Arista' a_device.save() for a_device in devices: print a_device, a_device.vendor
Example #18
Source File: runtests.py From stream-django with BSD 3-Clause "New" or "Revised" License | 5 votes |
def runtests(): import django # django 1.6 breaks if hasattr(django, 'setup'): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=True) failures = test_runner.run_tests(['test_app']) sys.exit(bool(failures))
Example #19
Source File: tests.py From thirtylol with MIT License | 5 votes |
def setUpClass(cls): django.setup()
Example #20
Source File: conftest.py From fossevents.in with MIT License | 5 votes |
def pytest_configure(config): django.setup()
Example #21
Source File: provision_inner.py From zulip with Apache License 2.0 | 5 votes |
def setup_bash_profile() -> None: """Select a bash profile file to add setup code to.""" BASH_PROFILES = [ os.path.expanduser(p) for p in ("~/.bash_profile", "~/.bash_login", "~/.profile") ] def clear_old_profile() -> None: # An earlier version of this script would output a fresh .bash_profile # even though a .profile existed in the image used. As a convenience to # existing developers (and, perhaps, future developers git-bisecting the # provisioning scripts), check for this situation, and blow away the # created .bash_profile if one is found. BASH_PROFILE = BASH_PROFILES[0] DOT_PROFILE = BASH_PROFILES[2] OLD_PROFILE_TEXT = "source /srv/zulip-py3-venv/bin/activate\n" + \ "cd /srv/zulip\n" if os.path.exists(DOT_PROFILE): try: with open(BASH_PROFILE) as f: profile_contents = f.read() if profile_contents == OLD_PROFILE_TEXT: os.unlink(BASH_PROFILE) except FileNotFoundError: pass clear_old_profile() for candidate_profile in BASH_PROFILES: if os.path.exists(candidate_profile): setup_shell_profile(candidate_profile) break else: # no existing bash profile found; claim .bash_profile setup_shell_profile(BASH_PROFILES[0])
Example #22
Source File: setup.py From django-livefield with MIT License | 5 votes |
def run_tests(self): from django.conf import settings db_engine = os.environ.get('DJANGO_DB_ENGINE', 'sqlite') if db_engine == 'mysql': db_settings = { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DJANGO_DB_NAME'], 'USER': os.environ['DJANGO_DB_USER'], } elif db_engine == 'postgres': db_settings = { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['DJANGO_DB_NAME'], 'USER': os.environ['DJANGO_DB_USER'], } elif db_engine == 'sqlite': db_settings = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(self.DIRNAME, 'database.db'), } else: raise ValueError("Unknown DB engine: %s" % db_engine) # Common settings. settings.configure( DEBUG=True, DATABASES={'default': db_settings}, CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}, INSTALLED_APPS=self.APPS) import django import pytest django.setup() sys.exit(pytest.main(["tests/"]))
Example #23
Source File: makemessages.py From django-private-storage with Apache License 2.0 | 5 votes |
def main(): if not settings.configured: module_root = path.dirname(path.realpath(__file__)) settings.configure( DEBUG=False, INSTALLED_APPS=( 'private_storage', ), ) django.setup() makemessages()
Example #24
Source File: conftest.py From django-klingon with GNU Lesser General Public License v3.0 | 5 votes |
def pytest_configure(): from django.conf import settings if not settings.configured: settings.configure( DEBUG_PROPAGATE_EXCEPTIONS=True, DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, INSTALLED_APPS=( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'autoslug', 'klingon', 'tests', 'tests.testapp', ), SITE_ID=1, SECRET_KEY='this-is-just-for-tests-so-not-that-secret', LANGUAGES = ( ('en', 'English'), ('pt_br', 'Brazilian Portuguese'), ('es', 'Spanish'), ), MIDDLEWARE_CLASSES=(), ) try: import django django.setup() except AttributeError: pass
Example #25
Source File: conf.py From tom_base with GNU General Public License v3.0 | 5 votes |
def setup(app): app.add_source_suffix('.md', 'markdown') app.add_source_parser(CommonMarkParser)
Example #26
Source File: net_main.py From pynet with Apache License 2.0 | 5 votes |
def main(): ''' Network management system class #9 ''' django.setup() verbose = True time.sleep(3) print while True: if verbose: print "### Gather inventory from devices ###" inventory_dispatcher() if verbose: print "\n### Retrieve config from devices ###" retrieve_config() if verbose: print "Sleeping for {} seconds".format(LOOP_DELAY) time.sleep(LOOP_DELAY)
Example #27
Source File: load_devices.py From pynet with Apache License 2.0 | 5 votes |
def main(): django.setup() management_ip = raw_input("Please enter IP address: ") my_switches = (('pynet-sw1', 8222, '10.220.88.28'), ('pynet-sw2', 8322, '10.220.88.29'), ('pynet-sw3', 8422, '10.220.88.30'), ('pynet-sw4', 8522, '10.220.88.31')) passwd = getpass() # Create Arista inventory group arista_group = InventoryGroup.objects.get_or_create(group_name='arista') print arista_group # Create credential object arista_creds = Credentials.objects.get_or_create( username='admin1', password=passwd, description='Arista credentials' ) print arista_creds # Create four switch objects for switch_name, ssh_port, ip_addr in my_switches: switch_obj = NetworkSwitch.objects.get_or_create( device_name=switch_name, device_type='arista_eos', ip_address=ip_addr, management_ip=management_ip, port=ssh_port, group_name=arista_group[0], credentials = arista_creds[0], ) print switch_obj
Example #28
Source File: test_models.py From scale with Apache License 2.0 | 5 votes |
def setUp(self): django.setup() self.src_file_1 = source_test_utils.create_source() self.src_file_2 = source_test_utils.create_source() self.src_file_3 = source_test_utils.create_source() self.src_file_4 = source_test_utils.create_source() self.job_exe_1 = job_test_utils.create_job_exe() self.recipe_job_1 = recipe_test_utils.create_recipe_job(job=self.job_exe_1.job) self.product_1 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True) self.product_2 = prod_test_utils.create_product(self.job_exe_1, has_been_published=True) FileAncestryLink.objects.create(ancestor=self.src_file_1, descendant=self.product_1, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_1, descendant=self.product_2, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_2, descendant=self.product_1, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_2, descendant=self.product_2, job_exe=self.job_exe_1, job=self.job_exe_1.job, recipe=self.recipe_job_1.recipe) self.job_exe_2 = job_test_utils.create_job_exe() self.recipe_job_2 = recipe_test_utils.create_recipe_job(job=self.job_exe_2.job) self.product_3 = prod_test_utils.create_product(self.job_exe_2, has_been_published=True) FileAncestryLink.objects.create(ancestor=self.src_file_3, descendant=self.product_3, job_exe=self.job_exe_2, job=self.job_exe_2.job, recipe=self.recipe_job_2.recipe) FileAncestryLink.objects.create(ancestor=self.src_file_4, descendant=self.product_3, job_exe=self.job_exe_2, job=self.job_exe_2.job, recipe=self.recipe_job_2.recipe)
Example #29
Source File: makemigrations.py From pinax-documents with MIT License | 5 votes |
def run(*args): if not settings.configured: settings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) django.core.management.call_command( "makemigrations", "documents", *args )
Example #30
Source File: grpc_server.py From xos with Apache License 2.0 | 5 votes |
def init_django(self): try: import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xos.settings") django.setup() from django.apps import apps self.django_apps = apps self.django_initialized = True except BaseException: log.exception("Failed to initialize django")