Skip to content

Commit

Permalink
Remove "filthy magic stack backtracking" in favor of BASE_DIR
Browse files Browse the repository at this point in the history
The read_env documentation currently states:

> If not given a path to a dotenv path, does filthy magic stack
> backtracking to find manage.py and then find the dotenv.

Based on joke2k#88, it appears that this behavior is
rather fragile.

To improve this, I think the package should document that read_env
expects you to provide a path. If one is not provided, it will
attempt to use the BASE_DIR constant from the django settings
module. If an ImportError is encountered while it attempts to do this,
read_env will assume there's no .env file to be found, log an info
message to that effect, and continue on.

fixes: joke2k#88
  • Loading branch information
birdcar committed Mar 19, 2020
1 parent dc2d281 commit b9a9dc2
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions environ/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,18 +625,21 @@ def search_url_config(cls, url, engine=None):
def read_env(cls, env_file=None, **overrides):
"""Read a .env file into os.environ.
If not given a path to a dotenv path, does filthy magic stack backtracking
to find manage.py and then find the dotenv.
http://www.wellfireinteractive.com/blog/easier-12-factor-django/
https://gist.github.com/bennylope/2999704
:param env_file: The path to the `.env` file your application should
use. If a path is not provided, `read_env` will attempt to import
the Django settings module and use the BASE_DIR constant to find
the .env file. Failing that, it will create an INFO-level log
message that no `.env` file was found and continue on.
:param **overrides: Any additional keyword arguments provided directly
to read_env will be added to the environment. If the key matches an
existing environment variable, the value will be overridden.
"""
if env_file is None:
frame = sys._getframe()
env_file = os.path.join(os.path.dirname(frame.f_back.f_code.co_filename), '.env')
if not os.path.exists(env_file):
warnings.warn(
try:
from django.conf import settings
env_file = os.path.join(settings.BASE_DIR, '.env')
except ImportError:
logger.info(
"%s doesn't exist - if you're not configuring your "
"environment separately, create one." % env_file)
return
Expand Down Expand Up @@ -669,6 +672,7 @@ def read_env(cls, env_file=None, **overrides):
cls.ENVIRON.setdefault(key, value)



class Path(object):

"""Inspired to Django Two-scoops, handling File Paths in Settings.
Expand Down

0 comments on commit b9a9dc2

Please sign in to comment.