当前位置: 首页>>代码示例>>Python>>正文


Python management.call_command方法代码示例

本文整理汇总了Python中django.core.management.call_command方法的典型用法代码示例。如果您正苦于以下问题:Python management.call_command方法的具体用法?Python management.call_command怎么用?Python management.call_command使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.management的用法示例。


在下文中一共展示了management.call_command方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: call_command

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def call_command():
    from django.core.management import call_command

    class CallCommand(object):
        def __init__(self):
            self.io = BytesIO()

        def __call__(self, *args, **kwargs):
            self.io = BytesIO()
            stdout = sys.stdout
            try:
                sys.stdout = self.io
                call_command(*args, **kwargs)
            finally:
                sys.stdout = stdout
            return self

        @property
        def stdout(self):
            return self.io.getvalue()

    return CallCommand() 
开发者ID:GaretJax,项目名称:django-click,代码行数:24,代码来源:conftest.py

示例2: reset_db

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def reset_db():
    """
    Reset database to a blank state by removing all the tables and recreating them.
    """
    with connection.cursor() as cursor:
        cursor.execute("select tablename from pg_tables where schemaname = 'public'")
        tables = [row[0] for row in cursor.fetchall()]

        # Can't use query parameters here as they'll add single quotes which are not
        # supported by postgres
        for table in tables:
            cursor.execute('drop table "' + table + '" cascade')

    # Call migrate so that post-migrate hooks such as generating a default Site object
    # are run
    management.call_command("migrate", "--noinput", stdout=StringIO()) 
开发者ID:liip,项目名称:django-template,代码行数:18,代码来源:fixturize.py

示例3: get_sql

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def get_sql(self, app_label, migration_name):
        logger.info(
            "Calling sqlmigrate command {} {}".format(app_label, migration_name)
        )
        dev_null = open(os.devnull, "w")
        try:
            sql_statement = call_command(
                "sqlmigrate",
                app_label,
                migration_name,
                database=self.database,
                stdout=dev_null,
            )
        except (ValueError, ProgrammingError):
            logger.warning(
                (
                    "Error while executing sqlmigrate on (%s, %s). "
                    "Continuing execution with empty SQL."
                ),
                app_label,
                migration_name,
            )
            sql_statement = ""
        return sql_statement.splitlines() 
开发者ID:3YOURMIND,项目名称:django-migration-linter,代码行数:26,代码来源:migration_linter.py

示例4: test_v3migration_001_create_v3_data_dir

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_v3migration_001_create_v3_data_dir(self):
        """Test the creation of a v3data directory within an existing package."""

        if os.path.isdir(self.pkg):
            shutil.rmtree(self.pkg)

        # make some of the standard v4 package directory structure
        # these are used later, but may as well be created here
        os.mkdir(self.pkg)
        os.mkdir(os.path.join(self.pkg, "reference_data"))

        management.call_command("v3", "start-migration", target=self.pkg, overwrite=True)

        self.assertTrue(os.path.isdir(os.path.join(self.pkg, "v3data", "business_data")))
        self.assertTrue(os.path.isdir(os.path.join(self.pkg, "v3data", "graph_data")))
        self.assertTrue(os.path.isdir(os.path.join(self.pkg, "v3data", "reference_data")))
        self.assertTrue(os.path.isfile(os.path.join(self.pkg, "reference_data", "v3topconcept_lookup.json")))

        # now that its existence is tested, update the topconcept lookup
        # file with the real one, whose contents is expected later
        fixture_lookup = os.path.join(self.pkg_fixture, "reference_data", "v3topconcept_lookup.json")
        shutil.copyfile(fixture_lookup, os.path.join(self.pkg, "reference_data", "v3topconcept_lookup.json")) 
开发者ID:archesproject,项目名称:arches,代码行数:24,代码来源:v3_migration_cli_tests.py

示例5: test_v3migration_002_generate_rm_configs

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_v3migration_002_generate_rm_configs(self):
        """Test the generation of resource model config file."""

        # copy in the resource model files, to mimic a user creating and
        # then exporting them into this package.
        shutil.copytree(os.path.join(self.pkg_fixture, "graphs", "resource_models"), os.path.join(self.pkg, "graphs", "resource_models"))

        # now run the management command
        management.call_command("v3", "generate-rm-configs", target=self.pkg)

        # test that the file has been created, and that it has the correct
        # number of entries to match the number of resource models.
        self.assertTrue(os.path.isfile(os.path.join(self.pkg, "v3data", "rm_configs.json")))
        num_rms = len(glob(os.path.join(self.pkg, "graphs", "resource_models", "*.json")))
        with open(os.path.join(self.pkg, "v3data", "rm_configs.json"), "rb") as conf:
            data = json.loads(conf.read())
            self.assertEqual(num_rms, len(list(data.keys()))) 
开发者ID:archesproject,项目名称:arches,代码行数:19,代码来源:v3_migration_cli_tests.py

示例6: test_inherit_perms

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_inherit_perms(self):
        out, err = StringIO(), StringIO()

        with self.settings(
            FLOW_PROCESSES_DIRS=[os.path.join(PROCESSES_DIR, "first_version")]
        ):
            call_command("register", stdout=out, stderr=err)

        process = Process.objects.latest()
        assign_perm("view_process", self.user, process)

        out, err = StringIO(), StringIO()

        with self.settings(
            FLOW_PROCESSES_DIRS=[os.path.join(PROCESSES_DIR, "second_version")]
        ):
            call_command("register", stdout=out, stderr=err)

        process = Process.objects.latest()

        self.assertEqual(UserObjectPermission.objects.filter(user=self.user).count(), 2)
        self.assertTrue(self.user.has_perm("flow.view_process", process)) 
开发者ID:genialis,项目名称:resolwe,代码行数:24,代码来源:test_commands.py

示例7: test_inactive_user_cleanup

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_inactive_user_cleanup(self):
        def create_users(kind):
            logintime = timezone.now() + timezone.timedelta(seconds=5)
            kwargs_list = [
                dict(email=f'user1+{kind}@example.com', is_active=False, last_login=None),
                dict(email=f'user2+{kind}@example.com', is_active=True, last_login=None),
                dict(email=f'user3+{kind}@example.com', is_active=False, last_login=logintime),
                dict(email=f'user4+{kind}@example.com', is_active=True, last_login=logintime),
            ]
            return (User.objects.create(**kwargs) for kwargs in kwargs_list)

        # Old users
        faketime = timezone.now() - settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE - timezone.timedelta(seconds=1)
        with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
            expired_user, _, _, _ = create_users('old')

        # New users
        create_users('new')

        all_users = set(User.objects.all())

        management.call_command('chores')
        # Check that only the expired user was deleted
        self.assertEqual(all_users - set(User.objects.all()), {expired_user}) 
开发者ID:desec-io,项目名称:desec-stack,代码行数:26,代码来源:test_chores.py

示例8: test_management_command

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_management_command(self):
        """
        The ``cleanupregistration`` management command properly
        deletes expired accounts.
        
        """
        new_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                    **self.user_info)
        expired_user = RegistrationProfile.objects.create_inactive_user(site=Site.objects.get_current(),
                                                                        username='bob',
                                                                        password='secret',
                                                                        email='bob@example.com')
        expired_user.date_joined -= datetime.timedelta(days=settings.ACCOUNT_ACTIVATION_DAYS + 1)
        expired_user.save()

        management.call_command('cleanupregistration')
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertRaises(User.DoesNotExist, User.objects.get, username='bob') 
开发者ID:znick,项目名称:anytask,代码行数:20,代码来源:models.py

示例9: handle

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def handle(self, *args, **options):
        self.type = options['type']
        self.name = options['name']
        management.call_command('startapp', self.name)
        dir_name = ['management', Path('management/commands')]
        self.mk_dir(dir_name)

        if self.type == 'theme':
            dir_name = ['static', Path('static/' + self.name), 'templates', Path('templates/' + self.name)]
            self.mk_dir(dir_name)

        context = Context({
            'app_name': self.name,
            'app_camel_name': self.name[0].upper() + self.name[1:],
            'app_upper_name': self.name.upper(),
            'deeru_type': self.type
        }, autoescape=False)

        for template_name, new_file in self.get_app_templates():
            template = Engine().from_string(self.get_template_str(template_name))
            content = template.render(context)
            new_file.write_text(content) 
开发者ID:gojuukaze,项目名称:DeerU,代码行数:24,代码来源:start.py

示例10: load_test_data

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def load_test_data(request, db, django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        call_command('loaddata', 'test_dump.json')
        self = request.cls
        self.i = Institution.objects.get(name='ENS')
        self.d = Department.objects.get(name='Chemistry dept')
        self.di = Department.objects.get(name='Comp sci dept')

        self.r1 = get_researcher_by_name('Isabelle', 'Aujard')
        self.r2 = get_researcher_by_name('Ludovic', 'Jullien')
        self.r3 = get_researcher_by_name('Antoine', 'Amarilli')
        self.r4 = get_researcher_by_name('Antonin', 'Delpeuch')
        self.r5 = get_researcher_by_name('Terence', 'Tao')
        self.hal = OaiSource.objects.get(identifier='hal')
        self.arxiv = OaiSource.objects.get(identifier='arxiv')
        self.lncs = Journal.objects.get(issn='0302-9743')
        self.acm = Journal.objects.get(issn='1529-3785').publisher 
开发者ID:dissemin,项目名称:dissemin,代码行数:19,代码来源:conftest.py

示例11: test_dump_latest

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_dump_latest(self):
        out = StringIO()
        management.call_command("dump_latest", stdout=out)
        self.assertIn("Dumping 0 events", out.getvalue())

        ev = utils.create_event()
        management.call_command("dump_latest", stdout=out)
        self.assertIn("Dumping 1 events", out.getvalue())

        with open("out.json", "r") as f:
            data = f.read()
        out = json.loads(data)
        count = 0
        for entry in out:
            if entry["model"] == "ci.event":
                self.assertEqual(ev.pk, entry["pk"])
                count = 1
        self.assertEqual(count, 1) 
开发者ID:idaholab,项目名称:civet,代码行数:20,代码来源:test_commands.py

示例12: test_user_access

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def test_user_access(self, mock_get):
        out = StringIO()
        mock_get.return_value = utils.Response(status_code=404)
        with self.assertRaises(CommandError):
            management.call_command("user_access", stdout=out)
        with self.assertRaises(models.GitUser.DoesNotExist):
            management.call_command("user_access", "--master", "nobody", stdout=out)
        with self.assertRaises(CommandError):
            management.call_command("user_access", "--master", self.owner.name, stdout=out)

        out = StringIO()
        management.call_command("user_access", "--master", self.build_user.name, stdout=out)

        repo1 = {'name': 'repo1', 'owner': {'login': 'owner'} }
        repo2 = {'name': 'repo2', 'owner': {'login': 'owner'} }
        mock_get.side_effect = [utils.Response([repo1]), utils.Response([repo2])]

        out = StringIO()
        management.call_command("user_access", "--master", self.build_user.name, "--user", "owner", stdout=out) 
开发者ID:idaholab,项目名称:civet,代码行数:21,代码来源:test_commands.py

示例13: backup_palanaeum

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def backup_palanaeum():
    """
    Create a ZIP package containing result of dumpdata command and the `media` folder.
    """
    # TODO lock the site while the backup is running
    logger.info("Starting backup process.")
    with tempfile.TemporaryDirectory() as d:
        dump_path = os.path.join(d, 'dump.json')
        logger.info("Starting data dump...")
        management.call_command('dumpdata', natural_foreign=True, output=dump_path)
        logger.info("Data dumped.")
        logger.info("Copying MEDIA_ROOT to %s...", os.path.join(d, 'media'))
        shutil.copytree(settings.MEDIA_ROOT, os.path.join(d, 'media'))
        logger.info('Copy done.')
        backup_path = os.path.join(settings.BACKUP_DIR, datetime.date.today().strftime("%Y-%m-%d.zip"))
        with zipfile.ZipFile(backup_path, mode='w') as backup_zip:
            for root, dirs, files in os.walk(d):
                for file in files:
                    filepath = os.path.join(root, file)
                    logger.info("Compressing {}...".format(filepath))
                    backup_zip.write(filepath,
                                     arcname=os.path.relpath(filepath, d))
            logger.info("{} created.".format(backup_path)) 
开发者ID:Palanaeum,项目名称:palanaeum,代码行数:25,代码来源:tasks.py

示例14: before_scenario

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def before_scenario(context, scenario):
    management.call_command('flush', interactive=False) 
开发者ID:javrasya,项目名称:django-river,代码行数:4,代码来源:environment.py

示例15: import_business_data

# 需要导入模块: from django.core import management [as 别名]
# 或者: from django.core.management import call_command [as 别名]
def import_business_data(self, data_source="", overwrite="", bulk_load=False, create_concepts=False, create_collections=False):
    management.call_command("packages", operation="import_business_data", source=data_source, overwrite=True) 
开发者ID:archesproject,项目名称:arches,代码行数:4,代码来源:tasks.py


注:本文中的django.core.management.call_command方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。