mirror of
https://github.com/jazzband/django-configurations.git
synced 2026-03-16 22:20:27 +00:00
add support to load .env file into os.environ
This commit is contained in:
parent
8a8f99ab68
commit
5279ae4ace
4 changed files with 49 additions and 0 deletions
|
|
@ -41,6 +41,39 @@ class ConfigurationBase(type):
|
|||
return "<Configuration '{0}.{1}'>".format(self.__module__,
|
||||
self.__name__)
|
||||
|
||||
@staticmethod
|
||||
def read_env(env_file='.env', **overrides):
|
||||
"""
|
||||
Pulled from Honcho code with minor updates, reads local default
|
||||
environment variables from a .env file located in the project root
|
||||
directory.
|
||||
|
||||
http://www.wellfireinteractive.com/blog/easier-12-factor-django/
|
||||
https://gist.github.com/bennylope/2999704
|
||||
"""
|
||||
import re
|
||||
import os
|
||||
|
||||
with open(env_file) as f:
|
||||
content = f.read()
|
||||
|
||||
for line in content.splitlines():
|
||||
m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line)
|
||||
if not m1:
|
||||
continue
|
||||
key, val = m1.group(1), m1.group(2)
|
||||
m2 = re.match(r"\A'(.*)'\Z", val)
|
||||
if m2:
|
||||
val = m2.group(1)
|
||||
m3 = re.match(r'\A"(.*)"\Z', val)
|
||||
if m3:
|
||||
val = re.sub(r'\\(.)', r'\1', m3.group(1))
|
||||
os.environ.setdefault(key, val)
|
||||
|
||||
# set defaults
|
||||
for key, value in overrides.items():
|
||||
os.environ.setdefault(key, value)
|
||||
|
||||
|
||||
class Configuration(six.with_metaclass(ConfigurationBase)):
|
||||
"""
|
||||
|
|
|
|||
1
test_project/.env
Normal file
1
test_project/.env
Normal file
|
|
@ -0,0 +1 @@
|
|||
DJANGO_ENV_LOADED=True
|
||||
|
|
@ -3,9 +3,13 @@ import uuid
|
|||
import django
|
||||
|
||||
from configurations import Configuration, pristinemethod
|
||||
from configurations.values import BooleanValue
|
||||
|
||||
|
||||
class Test(Configuration):
|
||||
|
||||
ENV_LOADED = BooleanValue(False)
|
||||
|
||||
DEBUG = True
|
||||
|
||||
SITE_ID = 1
|
||||
|
|
@ -60,6 +64,7 @@ class Test(Configuration):
|
|||
@classmethod
|
||||
def pre_setup(cls):
|
||||
cls.PRE_SETUP_TEST_SETTING = 6
|
||||
cls.read_env('test_project/.env')
|
||||
|
||||
@classmethod
|
||||
def post_setup(cls):
|
||||
|
|
|
|||
10
tests/test_env.py
Normal file
10
tests/test_env.py
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import os
|
||||
from django.test import TestCase
|
||||
from configurations.values import BooleanValue
|
||||
from mock import patch
|
||||
|
||||
class EnvValueTests(TestCase):
|
||||
|
||||
def test_env_loaded(self):
|
||||
check_value = BooleanValue(False)
|
||||
self.assertEqual(check_value.setup('ENV_LOADED'), True)
|
||||
Loading…
Reference in a new issue