Skip to content

Commit

Permalink
Set undefined env variables using CLI arguments
Browse files Browse the repository at this point in the history
Both `DJANGO_SETTINGS_MODULE` and `DJANGO_CONFIGURATION` are required for `django.configurations.importer` to install, else it throws an exception.
If the `importer` is not installed, `django.setup()` fails on `configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)` when trying to access uninitialized settings.

fixes pylint-dev#309 (pylint-dev#309 (comment))
fixes pylint-dev#325
might relate to pylint-dev#362
  • Loading branch information
TheAfroOfDoom committed Jun 4, 2022
1 parent 6c1e67e commit 8196b1f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@
* [naquiroz](https://github.com/naquiroz)
* [john-sandall](https://github.com/john-sandall)
* [dineshtrivedi](https://github.com/dineshtrivedi)
* [TheAfroOfDoom](https://github.com/TheAfroOfDoom)
38 changes: 38 additions & 0 deletions pylint_django/checkers/foreign_key_strings.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from __future__ import absolute_import

import os

import astroid
from configurations import importer
from pylint.checkers import BaseChecker
from pylint.checkers.utils import check_messages
from pylint.interfaces import IAstroidChecker
Expand Down Expand Up @@ -41,6 +44,15 @@ class ForeignKeyStringsChecker(BaseChecker):
"help": "A module containing Django settings to be used while linting.",
},
),
(
"django-configuration",
{
"default": None,
"type": "string",
"metavar": "<django configuration>",
"help": "The configuration for Django to use while linting.",
},
),
)

msgs = {
Expand Down Expand Up @@ -89,6 +101,32 @@ def open(self):
try:
import django # pylint: disable=import-outside-toplevel

if (
os.environ.get("DJANGO_SETTINGS_MODULE") is None
or os.environ.get("DJANGO_CONFIGURATION") is None
):
try:
os.environ.setdefault(
"DJANGO_SETTINGS_MODULE",
os.environ.get("DJANGO_SETTINGS_MODULE")
or self.config.django_settings_module,
)
os.environ.setdefault(
"DJANGO_CONFIGURATION",
os.environ.get("DJANGO_CONFIGURATION")
or self.config.django_configuration,
)
except TypeError as ex:
missing_module = ""
if self.config.django_settings_module is None:
missing_module = "DJANGO_SETTINGS_MODULE"
else:
missing_module = "DJANGO_CONFIGURATION"
raise RuntimeError(
f"{missing_module} required to initialize Django project settings"
) from ex
importer.install()

django.setup()
from django.apps import ( # noqa pylint: disable=import-outside-toplevel,unused-import
apps,
Expand Down

0 comments on commit 8196b1f

Please sign in to comment.