def handle_noargs(self, **options): if "conf_setting" in connection.introspection.table_names(): raise CommandError("Database already created, you probably " "want the migrate command") migrate.Command().execute(**options) self.verbosity = int(options.get("verbosity", 0)) self.interactive = int(options.get("interactive", 0)) self.no_data = int(options.get("nodata", 0)) mapping = [ [self.create_site, ["django.contrib.sites"]], [self.create_user, ["django.contrib.auth"]], [self.translation_fields, ["modeltranslation"]], [ self.create_pages, [ "mezzanine.pages", "mezzanine.forms", "mezzanine.blog", "mezzanine.galleries" ] ], [self.create_shop, ["cartridge.shop"]], [self.fake_migrations, ["south"]], ] for func, apps in mapping: if set(apps).issubset(set(settings.INSTALLED_APPS)): func()
def sync_apps(self, app_labels, app_name_to_app_map, options): if DJANGO_17: from django.db.migrations.executor import MigrationExecutor from django.core.management.commands import migrate apps_to_sync = [] for app_label in app_labels: app_label = app_name_to_app_map[ app_label].label if app_label in app_name_to_app_map else app_label apps_to_sync.append(app_label) connection = connections[options.get('database', 'default')] cmd = migrate.Command() cmd.stdout = self.stdout cmd.stderr = self.stderr cmd.run_syncdb = True cmd.verbosity = int(options.get('verbosity')) cmd.interactive = options.get('interactive') cmd.show_traceback = options.get('traceback') cmd.load_initial_data = options.get('load_initial_data') cmd.test_database = options.get('test_database', False) cmd.sync_apps(connection, apps_to_sync) else: old_installed, settings.INSTALLED_APPS = settings.INSTALLED_APPS, app_labels old_app_store, cache.app_store = cache.app_store, SortedDict([ (k, v) for (k, v) in cache.app_store.items() if get_app_label(k) in app_labels ]) # OK, run the actual syncdb syncdb.Command().execute(**options) settings.INSTALLED_APPS = old_installed cache.app_store = old_app_store
def handle(self, *args, **options): installed_version = models.KegbotSite.get_installed_version() app_version = get_version_object() force = options.get("force") if installed_version is None: print("Kegbot is not installed; run setup-kegbot.py first.") sys.exit(1) if installed_version == app_version and not force: print("Version {} already installed.".format(installed_version)) return if installed_version > app_version: print( "Installed version {} is newer than app version {}".format( installed_version, app_version ) ) sys.exit(1) if installed_version < MINIMUM_INSTALLED_VERSION: print("") print("ERROR: This version of Kegbot can only upgrade systems running on version") print( "v{} or newer. Please install Kegbot v{} and run `kegbot upgrade` again.".format( MINIMUM_INSTALLED_VERSION, MINIMUM_INSTALLED_VERSION ) ) print("(Existing version: {})".format(installed_version)) print("") print("More help: https://github.com/Kegbot/kegbot-server/wiki/Upgrading-Old-Versions") print("") sys.exit(1) print("Upgrading from {} to {}".format(installed_version, app_version)) self.do_version_upgrades(installed_version) run(migrate.Command(), args=["--noinput", "-v", "0"]) if not options.get("skip_stats"): run(regen_stats.Command()) if not options.get("skip_static"): run(collectstatic.Command(), args=["--noinput"]) site = models.KegbotSite.get() site.server_version = str(app_version) site.save() # Refresh any news (since we have a new version). try: checkin.checkin(timeout=5.0, quiet=True) except (checkin.CheckinError, Exception): pass print("") print("Upgrade complete!")
def fake_migrations(self): try: from south.management.commands import migrate except ImportError: return fake_migrations = self.confirm("\nSouth is installed for this project." "\nWould you like to fake initial " "migrations? (yes/no): ") if fake_migrations: if self.verbosity >= 1: print("\nFaking initial migrations ...\n") migrate.Command().execute(fake=True)
def run_migrate(): """ Run the equivalent of ./manage.py migrate """ migrate_cmd = migrate.Command() args = () options = { 'verbosity': 3, 'interactive': False, 'database': DEFAULT_DB_ALIAS, 'run_syncdb': True, 'app_label': None, 'plan': None, 'fake': False, 'fake_initial': False, } migrate_cmd.handle(*args, **options)
def handle(self, *args, **options): connection = psycopg2.connect( user=settings.DATABASES['default']['USER'], password=settings.DATABASES['default']['PASSWORD'], host=settings.DATABASES['default']['HOST'], port=settings.DATABASES['default']['PORT'], database='template1') connection.set_isolation_level(0) cursor = connection.cursor() print('Dropping database...') cursor.execute('DROP DATABASE "%s"' % settings.DATABASES['default']['NAME']) print('Creating database...') cursor.execute( 'CREATE DATABASE "%s" WITH OWNER = "%s" ENCODING = "UTF8"' % (settings.DATABASES['default']['NAME'], settings.DATABASES['default']['USER'])) cursor.close() migrate.Command().run_from_argv(sys.argv)
#!/usr/bin/env python import os import sys import django if __name__ == '__main__': os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' # TODO: need to move tracker into a subfolder so this isn't necessary sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) django.setup() from django.core import management from django.core.management.commands import migrate from django.core.management.commands import makemigrations management.call_command(migrate.Command()) management.call_command(makemigrations.Command(), check=True, dry_run=True)
from django.core.management import call_command from django.core.management.commands import migrate from django.db import transaction from django.test import override_settings # Force bogus values into required environment variables. os.environ["AWS_ACCESS_KEY_ID"] = "nope" os.environ["AWS_SECRET_ACCESS_KEY"] = "nope" os.environ["AWS_DEFAULT_REGION"] = "nope" os.environ["AWS_SQS_ACCESS_KEY_ID"] = "nope" os.environ["AWS_SQS_SECRET_ACCESS_KEY"] = "nope" # Force this script to always use the test settings. # This has the benefit of using the sqlite DB which should always be empty. os.environ["DJANGO_SETTINGS_MODULE"] = "config.settings.test" # However, this means we also need to apply migrations for that DB. migrate_cmd = migrate.Command() call_command(migrate_cmd, verbosity=0, interactive=False) # Run setup only *after* applying migrations. django.setup() # All other app-related imports must come *after* Django setup since this is # a standalone script. from django.contrib.auth.models import User from django.conf import settings from api import models from api.tests import helper as api_helper from api.util import calculate_max_concurrent_usage, normalize_runs from util import filters from util.misc import get_now from util.tests import helper as util_helper
def handle(self, *args, **options): # initialize database user = options['user'] pwd = options['password'] email = options['email'] tester = options['tester'] tester_config = options['config_file'] create_tester_config = options['create_tester_config'] # Create tester config will return immediately without init db if create_tester_config: with open(tester_config, 'wt') as f: f.write( os.linesep.join([ '# Tester configurations (tester is set in settings.py).', '# Update me before run auto-unittests.', '# Unittest will select the configured MQ to perform tests on.' ])) for section, confs in ConfKeys.items(): for k, v in confs.items(): f.write('%s= %s' % (v, os.linesep)) return 'Tester configuration file is created at %s' % tester_config # init db & migrate print('Initialize Database ...') call_command(makemigrations.Command(), 'pyqueuer') call_command(migrate.Command()) # create admin print('Creating admin user "%s" ...' % user) try: if pwd: call_command(createsuperuser.Command(), '--noinput', username=user, email=email) u = User.objects.get(username__exact=user) u.set_password(raw_password=pwd) u.save() else: call_command(createsuperuser.Command(), username=user, email=email) except IntegrityError: sys.stderr.write(' Admin with same name is already existed.' + os.linesep) else: print(' Admin user "%s" created. Email is "%s"' % (user, email)) # create tester if tester: name = pwd = settings.TESTER print('Creating test user "%s"...' % name) try: u = User.objects.create(username=name) u.email = email u.set_password(raw_password=pwd) u.is_active = True u.save() except IntegrityError: sys.stderr.write(' Tester is already existed.' + os.linesep) else: print( ' Tester is created. Username and password are both "%s".' % name) # load tester configurations from tester json # Use "manage.py config --import my_config.ini" to import config only. if tester_config: print('Load config for tester.') options = { "import": tester_config, "config_file": tester_config, "user": settings.TESTER, "password": settings.TESTER } call_command('config', **options) # with open(tester_config, 'rt') as f: # tester_dict = json.load(f) # # user = authenticate(username=name, password=pwd) # ucf = UserConf(user=user) # for k, v in tester_dict['test_user_config'].items(): # ucf.set(k, v) # return 'Tester configuration loaded from json %s' % tester_config return
def __init__(self, stdout=None, stderr=None, no_color=False): self.migrate_command = migrate.Command() super().__init__(stdout, stderr, no_color)