Skip to content

service

dev_tool.services.django.service

log = logging.getLogger(__name__) module-attribute

DjangoService

Bases: BaseService

A service class for Django-related operations.

This class provides static methods for various Django management commands and operations.

Source code in dev_tool/services/django/service.py
def __init__(self) -> None:
    super().__init__()

run_django_create_test_user

A method that creates a normal Django user account.

Source code in dev_tool/services/django/service.py
@is_django_environment_variables
def run_django_create_test_user(self) -> None:
    """A method that creates a normal Django user account."""

    users = [
        {
            'username': 'test',
            'first_name': 'Bobert',
            'last_name': 'Bobertson',
            'email': '[email protected]',
            'password': 'test',
        },
    ]

    for user_data in users:
        username = user_data['username']
        first_name = user_data['first_name']
        last_name = user_data['last_name']

        script = self._load_python_template(
            'create_user.py',
            username=username,
            first_name=first_name,
            last_name=last_name,
            email=user_data['email'],
            password=user_data['password']
        )

        command = [
            VENV_PYTHON,
            BASE / 'manage.py',
            'shell',
            '-c',
            script
        ]

        try:
            subprocess.run(command, check=True)

            message = f'User "{username}" created successfully.'
            CONTEXT.notification.normal_text(message)

            log.debug(message)
        except subprocess.CalledProcessError:
            message = f'Failed to create user "{username}"'
            log.exception(message)

            raise DjangoCommandError(message) from None

run_django_create_superuser

A method that creates default Django superuser accounts.

This method requires Django environment variables to be properly set.

Source code in dev_tool/services/django/service.py
@is_django_environment_variables
def run_django_create_superuser(self) -> None:
    """
    A method that creates default Django superuser accounts.

    This method requires Django environment variables to be properly set.
    """

    superusers = [
        {
            'username': 'stratus',
            'email': '[email protected]',
            'password': 'stratus',
            'first_name': 'Stratus',
            'last_name': 'Adv'
        },
    ]

    for superuser in superusers:
        username = superuser['username']
        email = superuser['email']
        password = superuser['password']

        first_name = superuser.get('first_name', '')
        last_name = superuser.get('last_name', '')

        script = self._load_python_template(
            'is_user.py',
            username=username
        )

        is_user = [
            VENV_PYTHON,
            BASE / 'manage.py',
            'shell',
            '-c',
            script
        ]

        try:
            result = subprocess.run(is_user, check=False)
        except Exception:
            message = f'Failed to check if superuser "{username}" exists'
            log.exception(message)

            raise DjangoSuperuserError(message) from None

        if result.returncode == 0:
            message = f'Superuser "{username}" already exists. Skipping...'
            CONTEXT.notification.warning_text(message)

            log.exception(message)

            continue

        message = f'Superuser "{username}" not found. Creating...'
        CONTEXT.notification.normal_text(message)

        log.debug(message)

        env = os.environ.copy()
        env['DJANGO_SUPERUSER_USERNAME'] = username
        env['DJANGO_SUPERUSER_EMAIL'] = email
        env['DJANGO_SUPERUSER_PASSWORD'] = password

        command = [
            VENV_PYTHON,
            BASE / 'manage.py',
            'createsuperuser',
            '--noinput',
        ]

        try:
            subprocess.run(command, check=True, env=env)
            message = f'Superuser "{username}" created successfully.'
            CONTEXT.notification.normal_text(message)

            log.debug(message)
        except subprocess.CalledProcessError:
            message = f'Failed to create superuser "{username}"'
            log.debug(message)

            raise DjangoSuperuserError(message) from None
        except Exception:
            message = f'Unexpected error creating superuser "{username}"'
            log.exception(message)

            raise DjangoSuperuserError(message) from None

        script = self._load_python_template(
            'update_user.py',
            username=username,
            first_name=first_name,
            last_name=last_name
        )

        command = [
            VENV_PYTHON,
            BASE / 'manage.py',
            'shell',
            '-c',
            script
        ]

        try:
            subprocess.run(command, check=True)

            message = f"Superuser '{username}' updated with additional information."
            CONTEXT.notification.normal_text(message)

            log.debug(message)
        except subprocess.CalledProcessError:
            message = f'Failed to update superuser "{username}" information'
            log.exception(message)

            raise DjangoSuperuserError(message) from None
        except Exception:
            message = f'Unexpected error updating superuser "{username}"'
            log.exception(message)

            raise DjangoSuperuserError(message) from None

run_django_create_user

A method that creates superusers and test users

Source code in dev_tool/services/django/service.py
def run_django_create_user(self) -> None:
    """A method that creates superusers and test users"""

    self.run_django_create_superuser()
    self.run_django_create_test_user()

run_django_management_command staticmethod

A method that runs a Django management command.

Parameters:

  • args (list[str]) –

    The arguments for the Django management command.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_management_command(args: list[str]) -> None:
    """
    A method that runs a Django management command.

    :param args: The arguments for the Django management command.
    """

    command = [
        VENV_PYTHON,
        BASE / 'manage.py',
        *args
    ]

    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError:
        message = f'Django management command failed: {" ".join(args)}'
        log.exception(message)

        raise DjangoCommandError(message) from None
    except Exception:
        message = f'Unexpected error running Django command: {" ".join(args)}'
        log.exception(message)

        raise DjangoCommandError(message) from None

run_django_manage_tool staticmethod

A method that provides an interactive interface for Django management commands.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_manage_tool() -> None:
    """A method that provides an interactive interface for Django management commands."""

    user_input = input('Enter your Django command: ').strip()
    args = user_input.split()

    if not args:
        message = 'No command entered. Please try again.'
        CONTEXT.notification.warning_text(message)

        log.debug(message)
        return

    DjangoService.run_django_management_command(args)

run_django_make_migrations staticmethod

A method that creates new Django migrations.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_make_migrations() -> None:
    """A method that creates new Django migrations."""

    command = ['makemigrations']

    try:
        DjangoService.run_django_management_command(command)
    except DjangoCommandError:
        message = 'Failed to create Django migrations'
        raise DjangoMigrationError(message) from None

run_django_migrate staticmethod

A method that applies Django migrations.

Parameters:

  • apps (str) –

    The specific apps to migrate, or empty string for all apps.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_migrate(apps: str) -> None:
    """
    A method that applies Django migrations.

    :param apps: The specific apps to migrate, or empty string for all apps.
    """

    command = ['migrate']

    if apps:
        message = f'Running migrations for {apps}'
        CONTEXT.notification.normal_text(message)

        log.debug(message)

        command.append(apps)
    else:
        message = 'Running migrations for default database.'
        CONTEXT.notification.normal_text(message)

        log.debug(message)

    try:
        DjangoService.run_django_management_command(command)
    except DjangoCommandError:
        apps = apps if apps else 'all apps'

        message = f'Failed to run Django migrations for {apps}'
        log.exception(message)

        raise DjangoMigrationError(message) from None

run_django_server staticmethod

A method that starts a Django development server.

Parameters:

  • ip_address (str) –

    The IP address to bind the server to.

  • port (int) –

    The port number to bind the server to.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_server(ip_address: str, port: int) -> None:
    """
    A method that starts a Django development server.

    :param ip_address: The IP address to bind the server to.
    :param port: The port number to bind the server to.
    """

    socket_address = f'{ip_address}:{port}'
    server = DjangoServerRunner(socket_address=socket_address)

    try:
        server.run()
    except Exception:
        message = f'Failed to start Django server on {socket_address}'
        log.exception(message)

        raise DjangoServerError(message) from None

run_django_seeding staticmethod

A method that runs database seeding for Django.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_seeding() -> None:
    """A method that runs database seeding for Django."""

    seed_script = BASE / 'seed.py'

    if seed_script.exists():
        message = 'Running seed script...'
        CONTEXT.notification.normal_text(message)

        log.debug(message)

        command = [
            VENV_PYTHON,
            seed_script
        ]

        try:
            subprocess.run(command, check=True)
        except subprocess.CalledProcessError:
            message = 'Django seeding script failed'
            log.exception(message)

            raise DjangoSeedError(message) from None
        except Exception:
            message = 'Unexpected error running Django seeding'
            log.exception(message)

            raise DjangoSeedError(message) from None
    else:
        message = 'No seed script found.'
        log.exception(message)

run_django_flush staticmethod

A method that flushes the Django database.

Source code in dev_tool/services/django/service.py
@staticmethod
@is_django_environment_variables
def run_django_flush() -> None:
    """A method that flushes the Django database."""

    message = 'Flushing the database...'
    CONTEXT.notification.normal_text(message)

    log.debug(message)

    command = [
        VENV_PYTHON,
        BASE / 'manage.py',
        'flush',
        '--no-input'
    ]

    try:
        subprocess.run(command, check=True)
    except subprocess.CalledProcessError:
        message = 'Failed to flush Django database'
        log.exception(message)

        raise DjangoCommandError(message) from None
    except Exception:
        message = 'Unexpected error flushing Django database'
        log.exception(message)

        raise DjangoCommandError(message) from None