Skip to content

Commit

Permalink
Reintroduce nautobot.setup() function (#5532)
Browse files Browse the repository at this point in the history
* Fix #5531 - reintroduce nautobot.setup() function

* Re-add sentinel against repeated initialization

* Eliminate duplicate pylint call
  • Loading branch information
glennmatthews committed Apr 8, 2024
1 parent 5622dbe commit a762466
Show file tree
Hide file tree
Showing 8 changed files with 55 additions and 41 deletions.
1 change: 1 addition & 0 deletions changes/5531.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Re-added `nautobot.setup()` function mistakenly removed in 2.2.0.
1 change: 1 addition & 0 deletions changes/5531.housekeeping
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Removed `nautobot-server pylint` management command from the `example_app`, as pylint can be invoked directly with an appropriate `--init-hook` instead.
Empty file.
Empty file.
23 changes: 0 additions & 23 deletions examples/example_app/example_app/management/commands/pylint.py

This file was deleted.

31 changes: 31 additions & 0 deletions nautobot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,35 @@
from importlib import metadata
import logging
import os

import django

# Primary package version
__version__ = metadata.version(__name__)

# Sentinel to make sure we only initialize once.
__initialized = False

logger = logging.getLogger(__name__)


def setup(config_path=None):
"""Similar to `django.setup()`, this configures Django with the appropriate Nautobot settings data."""
from nautobot.core.cli import get_config_path, load_settings

global __initialized

if __initialized:
return

if config_path is None:
config_path = get_config_path()

# Point Django to our 'nautobot_config' pseudo-module that we'll load from the provided config path
os.environ["DJANGO_SETTINGS_MODULE"] = "nautobot_config"

load_settings(config_path)
django.setup()

logger.info("Nautobot initialized!")
__initialized = True
29 changes: 18 additions & 11 deletions nautobot/core/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from django.core.management.utils import get_random_secret_key
from jinja2 import BaseLoader, Environment

from nautobot import __version__
from nautobot.core.settings_funcs import is_truthy
from nautobot.extras.plugins.utils import load_plugins

Expand Down Expand Up @@ -126,7 +125,7 @@ def _setting(name, default=None):
load_plugins(settings)


def _load_settings(config_path):
def load_settings(config_path):
"""Load nautobot_config.py or its equivalent into memory as a `nautobot_config` pseudo-module."""
if not os.path.exists(config_path):
raise FileNotFoundError(
Expand Down Expand Up @@ -154,6 +153,8 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def __call__(self, parser, namespace, values, option_string):
from nautobot import __version__

print(f"Nautobot version: {__version__}")
print(f"Django version: {django.__version__}")
print(f"Configuration file: {namespace.config_path}")
Expand Down Expand Up @@ -215,27 +216,33 @@ def _init_settings(args):
print(f"Configuration file created at {config_path}")


def main():
"""Run administrative tasks."""
# Point Django to our 'nautobot_config' pseudo-module that we'll load from the provided config path
os.environ["DJANGO_SETTINGS_MODULE"] = "nautobot_config"

# Default config path based on NAUTOBOT_CONFIG or NAUTOBOT_ROOT environment variables
config_path = os.getenv(
def get_config_path():
"""Get the default Nautobot config file path based on the NAUTOBOT_CONFIG or NAUTOBOT_ROOT environment variables."""
return os.getenv(
"NAUTOBOT_CONFIG",
os.path.join(
os.getenv("NAUTOBOT_ROOT", os.path.expanduser("~/.nautobot")),
"nautobot_config.py",
),
)


def main():
"""Run administrative tasks."""
# Point Django to our 'nautobot_config' pseudo-module that we'll load from the provided config path
os.environ["DJANGO_SETTINGS_MODULE"] = "nautobot_config"

default_config_path = get_config_path()

# Intercept certain CLI parameters and arguments before they reach Django
parser = CommandParser(
description=DESCRIPTION,
usage=USAGE,
formatter_class=_VerboseHelpFormatter,
)
parser.add_argument("-c", "--config-path", default=config_path, help="Path to the Nautobot configuration file")
parser.add_argument(
"-c", "--config-path", default=default_config_path, help="Path to the Nautobot configuration file"
)
parser.add_argument("--version", action=_VersionAction, help="Show version numbers and exit")

# Parse out the `--config` argument here and capture the rest of the CLI args
Expand Down Expand Up @@ -282,7 +289,7 @@ def main():
raise

# If we get here, it's a regular Django management command - so load in the nautobot_config.py then hand off
_load_settings(args.config_path)
load_settings(args.config_path)
execute_from_command_line([sys.argv[0], *unparsed_args])


Expand Down
11 changes: 4 additions & 7 deletions tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,18 +570,15 @@ def build_example_app_docs(context):
)
def pylint(context, target=None, recursive=False):
"""Perform static analysis of Nautobot code."""
base_command = 'pylint --verbose --init-hook "import nautobot; nautobot.setup()" '
if not target:
# Lint everything
# Lint the installed nautobot package and the file tasks.py in the current directory
command = "nautobot-server pylint nautobot tasks.py"
run_command(context, command)
# Lint Python files discovered recursively in the development/ and examples/ directories
command = "nautobot-server pylint --recursive development/ examples/"
command = base_command + "--recursive=y nautobot tasks.py development/ examples/"
run_command(context, command)
else:
command = "nautobot-server pylint "
command = base_command
if recursive:
command += "--recursive "
command += "--recursive=y "
command += " ".join(target)
run_command(context, command)

Expand Down

0 comments on commit a762466

Please sign in to comment.