def auth_params():
    """Return params required for authentication.

    ./envdir must exist with files named AUTHID and AUTHTOKEN
    that contain smartystreet issued credentials.
    https://smartystreets.com/
    """
    envdir.open(os.path.join(os.path.abspath(os.curdir), ENVDIR))
    auth_params = dict(zip(
        auth_keys, 
        [os.environ[key]
         for key in env_keys]
    ))
    return auth_params
Пример #2
0
def test_dict_like(tmpenvdir):
    tmpenvdir.join('ITER').write('test')
    env = envdir.open(str(tmpenvdir))
    assert list(env) == ['ITER']
    assert hasattr(env, '__iter__')

    assert [k for k in env] == ['ITER']
    assert list(env.values()) == ['test']
    assert list(env.items()) == [('ITER', 'test')]
    assert 'ITER' in os.environ
    env.clear()
    assert list(env.items()) == []
    assert 'ITER' not in os.environ

    with envdir.open(str(tmpenvdir)) as env:
        assert list(env.items()) == [('ITER', 'test')]
Пример #3
0
def test_write(tmpenvdir):
    env = envdir.open(str(tmpenvdir))
    env['WRITE'] = 'test'
    assert tmpenvdir.ensure('WRITE')
    assert tmpenvdir.join('WRITE').read() == 'test'
    envdir.read(str(tmpenvdir))
    assert os.environ['WRITE'] == 'test'
Пример #4
0
def test_write(tmpenvdir):
    env = envdir.open(str(tmpenvdir))
    env['WRITE'] = 'test'
    assert tmpenvdir.ensure('WRITE')
    assert tmpenvdir.join('WRITE').read() == 'test'
    envdir.read(str(tmpenvdir))
    assert os.environ['WRITE'] == 'test'
Пример #5
0
def test_dict_like(tmpenvdir):
    tmpenvdir.join('ITER').write('test')
    env = envdir.open(str(tmpenvdir))
    assert list(env) == ['ITER']
    assert hasattr(env, '__iter__')

    assert [k for k in env] == ['ITER']
    assert list(env.values()) == ['test']
    assert list(env.items()) == [('ITER', 'test')]
    assert 'ITER' in os.environ
    env.clear()
    assert list(env.items()) == []
    assert 'ITER' not in os.environ

    with envdir.open(str(tmpenvdir)) as env:
        assert list(env.items()) == [('ITER', 'test')]
Пример #6
0
def test_context_manager(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER').write('test')

    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER' in os.environ
    assert 'CONTEXT_MANAGER' not in os.environ
    assert repr(env) == "<envdir.Env '%s'>" % tmpenvdir
Пример #7
0
def test_write(tmpenvdir):
    env = envdir.open(str(tmpenvdir))
    env["WRITE"] = "test"
    assert tmpenvdir.ensure("WRITE")
    assert tmpenvdir.join("WRITE").read() == "test"
    envdir.read(str(tmpenvdir))
    assert os.environ["WRITE"] == "test"
Пример #8
0
def test_context_manager(tmpenvdir):
    tmpenvdir.join("CONTEXT_MANAGER").write("test")

    with envdir.open(str(tmpenvdir)) as env:
        assert "CONTEXT_MANAGER" in os.environ
    assert "CONTEXT_MANAGER" not in os.environ
    assert repr(env) == "<envdir.Env '%s'>" % tmpenvdir
Пример #9
0
def test_context_manager(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER').write('test')

    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER' in os.environ
    assert 'CONTEXT_MANAGER' not in os.environ
    assert repr(env) == "<envdir.Env '%s'>" % tmpenvdir
Пример #10
0
    def openenv(self, path=None):
        """
        Get environment variables.
        """
        if path:
            if not os.path.isabs(path):
                path = os.path.realpath(
                    os.path.join(
                        os.path.dirname(
                            os.path.realpath(inspect.stack()[-1][1])
                        ),
                        path
                    )
                )
        else:
            path = os.path.dirname(os.path.realpath(inspect.stack()[-1][1]))

        envdir.open(os.path.join(path, "envdir"))
        sys.path.extend(env("PYTHONPATH").split(os.pathsep))
Пример #11
0
def test_context_manager_reset(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER_RESET').write('test')
    # make the var exist in the enviroment
    os.environ['CONTEXT_MANAGER_RESET'] = 'moot'
    with envdir.open(str(tmpenvdir)) as env:
        assert os.environ['CONTEXT_MANAGER_RESET'] == 'test'
        env.clear()
        # because we reset the original value
        assert os.environ['CONTEXT_MANAGER_RESET'] == 'moot'
        assert 'CONTEXT_MANAGER_RESET' in os.environ
Пример #12
0
def test_context_manager_reset(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER_RESET').write('test')
    # make the var exist in the enviroment
    os.environ['CONTEXT_MANAGER_RESET'] = 'moot'
    with envdir.open(str(tmpenvdir)) as env:
        assert os.environ['CONTEXT_MANAGER_RESET'] == 'test'
        env.clear()
        # because we reset the original value
        assert os.environ['CONTEXT_MANAGER_RESET'] == 'moot'
        assert 'CONTEXT_MANAGER_RESET' in os.environ
Пример #13
0
def test_context_manager_reset(tmpenvdir):
    tmpenvdir.join("CONTEXT_MANAGER_RESET").write("test")
    # make the var exist in the enviroment
    os.environ["CONTEXT_MANAGER_RESET"] = "moot"
    with envdir.open(str(tmpenvdir)) as env:
        assert os.environ["CONTEXT_MANAGER_RESET"] == "test"
        env.clear()
        # because we reset the original value
        assert os.environ["CONTEXT_MANAGER_RESET"] == "moot"
        assert "CONTEXT_MANAGER_RESET" in os.environ
Пример #14
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    with envdir.open(os.environ.get('ENVDIR')) as env:
        for key in env:
            app.config[key] = env[key]

    setup_cache(app)
    api = Api(app)
    api.add_resource(Scraper, '/scraper')
    return app
Пример #15
0
def test_dict_like(tmpenvdir):
    tmpenvdir.join('ITER').write('test')
    env = envdir.open(str(tmpenvdir))
    assert list(env) == ['ITER']
    assert hasattr(env, '__iter__')

    assert [k for k in env] == ['ITER']
    assert list(env.values()) == ['test']
    assert list(env.items()) == [('ITER', 'test')]
    assert 'ITER' in os.environ
    env.clear()
    assert list(env.items()) == []
    assert 'ITER' not in os.environ
    with pytest.raises(KeyError):
        env['DOESNOTEXISTS']
    default = object()
    assert env.get('DOESNOTEXISTS', default) is default

    with envdir.open(str(tmpenvdir)) as env:
        assert list(env.items()) == [('ITER', 'test')]
Пример #16
0
def test_dict_like(tmpenvdir):
    tmpenvdir.join("ITER").write("test")
    env = envdir.open(str(tmpenvdir))
    assert list(env) == ["ITER"]
    assert hasattr(env, "__iter__")

    assert [k for k in env] == ["ITER"]
    assert list(env.values()) == ["test"]
    assert list(env.items()) == [("ITER", "test")]
    assert "ITER" in os.environ
    env.clear()
    assert list(env.items()) == []
    assert "ITER" not in os.environ
    with pytest.raises(KeyError):
        env["DOESNOTEXISTS"]
    default = object()
    assert env.get("DOESNOTEXISTS", default) is default

    with envdir.open(str(tmpenvdir)) as env:
        assert list(env.items()) == [("ITER", "test")]
Пример #17
0
def test_context_manager_item(tmpenvdir):
    tmpenvdir.join("CONTEXT_MANAGER_ITEM").write("test")

    with envdir.open(str(tmpenvdir)) as env:
        assert "CONTEXT_MANAGER_ITEM" in os.environ
        # the variable is in the env, but not in the env
        assert env["CONTEXT_MANAGER_ITEM"] == "test"
        del env["CONTEXT_MANAGER_ITEM"]
        assert "CONTEXT_MANAGER_ITEM" not in os.environ
        assert "CONTEXT_MANAGER_ITEM" not in env

        env["CONTEXT_MANAGER_ITEM_SET"] = "test"
        assert "CONTEXT_MANAGER_ITEM_SET" in os.environ
        assert tmpenvdir.join("CONTEXT_MANAGER_ITEM_SET").check()
        del env["CONTEXT_MANAGER_ITEM_SET"]
        assert "CONTEXT_MANAGER_ITEM_SET" not in os.environ
        assert not tmpenvdir.join("CONTEXT_MANAGER_ITEM_SET").check()
    assert tmpenvdir.ensure("CONTEXT_MANAGER_ITEM_SET")
    assert "CONTEXT_MANAGER_ITEM_SET" not in os.environ
Пример #18
0
def test_context_manager_item(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER_ITEM').write('test')

    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER_ITEM' in os.environ
        # the variable is in the env, but not in the env
        assert env['CONTEXT_MANAGER_ITEM'] == 'test'
        del env['CONTEXT_MANAGER_ITEM']
        assert 'CONTEXT_MANAGER_ITEM' not in os.environ
        assert 'CONTEXT_MANAGER_ITEM' not in env

        env['CONTEXT_MANAGER_ITEM_SET'] = 'test'
        assert 'CONTEXT_MANAGER_ITEM_SET' in os.environ
        assert tmpenvdir.join('CONTEXT_MANAGER_ITEM_SET').check()
        del env['CONTEXT_MANAGER_ITEM_SET']
        assert 'CONTEXT_MANAGER_ITEM_SET' not in os.environ
        assert not tmpenvdir.join('CONTEXT_MANAGER_ITEM_SET').check()
    assert tmpenvdir.ensure('CONTEXT_MANAGER_ITEM_SET')
    assert 'CONTEXT_MANAGER_ITEM_SET' not in os.environ
Пример #19
0
def test_context_manager_item(tmpenvdir):
    tmpenvdir.join('CONTEXT_MANAGER_ITEM').write('test')

    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER_ITEM' in os.environ
        # the variable is in the env, but not in the env
        assert env['CONTEXT_MANAGER_ITEM'] == 'test'
        del env['CONTEXT_MANAGER_ITEM']
        assert 'CONTEXT_MANAGER_ITEM' not in os.environ
        assert 'CONTEXT_MANAGER_ITEM' not in env

        env['CONTEXT_MANAGER_ITEM_SET'] = 'test'
        assert 'CONTEXT_MANAGER_ITEM_SET' in os.environ
        assert tmpenvdir.join('CONTEXT_MANAGER_ITEM_SET').check()
        del env['CONTEXT_MANAGER_ITEM_SET']
        assert 'CONTEXT_MANAGER_ITEM_SET' not in os.environ
        assert not tmpenvdir.join('CONTEXT_MANAGER_ITEM_SET').check()
    assert tmpenvdir.ensure('CONTEXT_MANAGER_ITEM_SET')
    assert 'CONTEXT_MANAGER_ITEM_SET' not in os.environ
Пример #20
0
# Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE

import os
import envdir

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promgen.settings')
os.environ.setdefault('CONFIG_DIR', os.path.expanduser('~/.config/promgen'))
default_app_config = 'promgen.apps.PromgenConfig'

if os.path.exists(os.environ['CONFIG_DIR']):
    envdir.open(os.environ['CONFIG_DIR'])
Пример #21
0
def test_context_manager_write(tmpenvdir):
    with envdir.open(str(tmpenvdir)) as env:
        assert "CONTEXT_MANAGER_WRITE" not in os.environ
        env["CONTEXT_MANAGER_WRITE"] = "test"
        assert "CONTEXT_MANAGER_WRITE" in os.environ
    assert "CONTEXT_MANAGER_WRITE" not in os.environ
Пример #22
0
def test_context_manager_write(tmpenvdir):
    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER_WRITE' not in os.environ
        env['CONTEXT_MANAGER_WRITE'] = 'test'
        assert 'CONTEXT_MANAGER_WRITE' in os.environ
    assert 'CONTEXT_MANAGER_WRITE' not in os.environ
Пример #23
0
import os
import envdir

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pomodoro.standalone.settings")
os.environ.setdefault("ENVDIR", os.path.expanduser("~/.config/pomodoro"))

if os.path.exists(os.environ["ENVDIR"]):
    envdir.open(os.environ["ENVDIR"])

# Preload Celery App
from pomodoro.standalone.celery import app as celery_app  # noqa
Пример #24
0
"""Configure WSGI app"""

import envdir

from pactf.constants import ENVDIR_PATH

envdir.open(ENVDIR_PATH)

from configurations.wsgi import get_wsgi_application

application = get_wsgi_application()
Пример #25
0
#!/usr/bin/env python
import os
import sys

import envdir

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dreams.settings')

    envdir.open()

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)
Пример #26
0
# Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE

import os
import pathlib

# Django environment defaults
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "promgen.settings")
default_app_config = "promgen.apps.PromgenConfig"

# Promgen environment defaults
PROMGEN_CONFIG_DIR = pathlib.Path(
    os.environ.setdefault("PROMGEN_CONFIG_DIR",
                          os.path.expanduser("~/.config/promgen")))

PROMGEN_CONFIG_FILE = pathlib.Path(
    os.environ.get("PROMGEN_CONFIG", str(PROMGEN_CONFIG_DIR / "promgen.yml")))

if PROMGEN_CONFIG_DIR.exists():
    import envdir

    envdir.open(PROMGEN_CONFIG_DIR)

if "SECRET_KEY" not in os.environ:
    from django.utils.crypto import get_random_string
    import warnings

    warnings.warn("Unset SECRET_KEY setting to random for now")
    os.environ["SECRET_KEY"] = get_random_string(
        50, "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)")
Пример #27
0
def test_context_manager_write(tmpenvdir):
    with envdir.open(str(tmpenvdir)) as env:
        assert 'CONTEXT_MANAGER_WRITE' not in os.environ
        env['CONTEXT_MANAGER_WRITE'] = 'test'
        assert 'CONTEXT_MANAGER_WRITE' in os.environ
    assert 'CONTEXT_MANAGER_WRITE' not in os.environ
Пример #28
0
# Copyright (c) 2017 LINE Corporation
# These sources are released under the terms of the MIT license: see LICENSE

import os
import envdir

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'promgen.settings')
os.environ.setdefault('PROMGEN_CONFIG_DIR',
                      os.path.expanduser('~/.config/promgen'))
default_app_config = 'promgen.apps.PromgenConfig'

if os.path.exists(os.environ['PROMGEN_CONFIG_DIR']):
    envdir.open(os.environ['PROMGEN_CONFIG_DIR'])
Пример #29
0
import logging
import os
import string

import envdir


logger = logging.getLogger(__name__)


ENV_LOCATION = os.environ.get('ENV_LOCATION')
if ENV_LOCATION:
    envdir.open(ENV_LOCATION)


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']

DEBUG = os.environ.get('DEBUG', 'False') == 'True'

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')


# Application definition

INSTALLED_APPS = (
Пример #30
0
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os
import envdir
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

env = envdir.open(os.path.join(BASE_DIR, 'vars'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'rzx!$o0350s4a%bgis*k959h%h_2r70zcc8%pz!wjrgi&0+&3m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
Пример #31
0
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "precious.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?")
        raise

    try:
        import envdir
        envdir.open()
    except:
        pass

    execute_from_command_line(sys.argv)
Пример #32
0
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
import os
import envdir
import warnings
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
from photologue import PHOTOLOGUE_APP_DIR

ENVDIR_PATH = os.environ.get('ENVDIR_PATH')
if ENVDIR_PATH and os.path.isdir(ENVDIR_PATH):
    envdir.open(ENVDIR_PATH)
else:
    warnings.warn('Unable to find ENVDIR_PATH: {0}'.format(ENVDIR_PATH))

APP_ENV = os.environ.get('APP_ENV', 'local')
PROJECT_ROOT = os.environ.get('PROJECT_ROOT', None)
if PROJECT_ROOT is None:
    PROJECT_ROOT = PROJECT_DIR = os.path.dirname(os.path.dirname(__file__))
else:
    PROJECT_ROOT = os.path.abspath(PROJECT_ROOT)
    PROJECT_DIR = os.path.join(PROJECT_ROOT, 'app')
DB_ROOT = os.path.join(PROJECT_ROOT, 'db')
GOOGLE_SITE_VERIFICATION = os.environ.get('GOOGLE_SITE_VERIFICATION', '')

SECRET_KEY = os.environ.get('SECRET_KEY', APP_ENV)
Пример #33
0
import os

import envdir
import redis

from flask import Flask
from flask_mail import Mail
from werkzeug.utils import import_string

this_dir = os.path.dirname(__file__)

envs = os.path.abspath(os.path.join(this_dir, os.pardir, os.pardir, 'envs'))
if os.path.isdir(envs):
    envdir.open(envs)

app = Flask(__name__, static_folder='../../web/static')
config_class = import_string('config.%s' %
                             os.environ.get('FLASK_CONFIG', 'DevConfig'))
config_obj = config_class()
app.config.from_object(config_obj)

mail = Mail(app)

redisdb = redis.Redis.from_url(app.config['REDIS_URL'])

from plexlib import views
Пример #34
0
    def _configure_django(self, **kw):
        """Auto-Configure Django using arguments."""
        from django.conf import settings, global_settings
        self.settings = settings
        if settings.configured:
            return

        self.APP_DIR, app_filename = os.path.split(
            os.path.realpath(inspect.stack()[2][1])
        )

        DEBUG = kw.get("DEBUG", False)
        ENVDIR = kw.get("ENVDIR", env("ENVDIR", ""))
        if ENVDIR:
            envdir.open(ENVDIR)
            if env("PYTHONPATH"):
                sys.path.extend(env("PYTHONPATH").split(os.pathsep))

        md = {}
        dp = {}

        for k, v in kw.items():
            if isinstance(v, E):
                md[k] = v.value
                setattr(global_esettings, k, v.value)
            if isinstance(v, DSetting):
                dp[k] = v

        for k, v in md.items():
            kw[k] = v

        for k, v in dp.items():
            if DEBUG:
                if v.dvalue is not NotSet:
                    kw[k] = v.dvalue
            else:
                if v.pvalue is not NotSet:
                    kw[k] = v.pvalue

        del md
        del dp

        def do_dp(key):
            if key not in kw:
                return
            old = kw[key]
            kw[key] = []
            for value in old:
                if DEBUG:
                    if value.startswith("prod:"):
                        continue
                    kw[key].append(value.replace("debug:", ""))
                else:
                    if value.startswith("debug:"):
                        continue
                    kw[key].append(value.replace("prod:", ""))

        do_dp("MIDDLEWARE_CLASSES")
        do_dp("INSTALLED_APPS")
        do_dp("TEMPLATE_CONTEXT_PROCESSORS")

        if "debug" in kw:
            db = kw.pop("debug")
            if DEBUG:
                kw.update(db)

        if "regexers" in kw:
            self.update_regexers(kw.pop("regexers"))

        self.mounts = kw.pop("mounts", {})

        if not kw.get("dont_configure", False):
            kw["ROOT_URLCONF"] = kw.get("ROOT_URLCONF", "importd.urlconf")
            if "TEMPLATE_DIRS" not in kw:
                kw["TEMPLATE_DIRS"] = (self.dotslash("templates"), )
            if "STATIC_URL" not in kw:
                kw["STATIC_URL"] = "/static/"
            if "STATIC_ROOT" not in kw:
                kw["STATIC_ROOT"] = self.dotslash("staticfiles")
            if "STATICFILES_DIRS" not in kw:
                kw["STATICFILES_DIRS"] = [self.dotslash("static")]
            if "MEDIA_URL" not in kw:
                kw["MEDIA_URL"] = "/static/media/"
            if "lr" in kw:
                self.lr = kw.pop("lr")
            if "db" in kw:
                if isinstance(kw["db"], basestring):
                    kw["DATABASES"] = {
                        "default": dj_database_url.parse(kw.pop("db"))
                    }
                else:
                    db = kw.pop("db")
                    default = dj_database_url.parse(db[0])
                    default.update(db[1])
                    kw["DATABASES"] = dict(default=default)
            if "DATABASES" not in kw:
                kw["DATABASES"] = {
                    "default": {
                        'ENGINE': "django.db.backends.sqlite3",
                        'NAME': self.dotslash("db.sqlite")
                    }
                }

            self.smart_return = False
            if kw.pop("SMART_RETURN", True):
                self.smart_return = True
                if "MIDDLEWARE_CLASSES" not in kw:
                    kw["MIDDLEWARE_CLASSES"] = (
                        global_settings.MIDDLEWARE_CLASSES
                    )
                kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
                kw["MIDDLEWARE_CLASSES"].append(
                    "importd.SmartReturnMiddleware"
                )

            installed = list(kw.setdefault("INSTALLED_APPS", []))

            admin_url = kw.pop("admin", "^admin/")

            if admin_url:
                if "django.contrib.auth" not in installed:
                    installed.append("django.contrib.auth")
                if "django.contrib.contenttypes" not in installed:
                    installed.append("django.contrib.contenttypes")
                if "django.contrib.auth" not in installed:
                    installed.append("django.contrib.auth")
                if "django.contrib.messages" not in installed:
                    installed.append("django.contrib.messages")
                if "django.contrib.sessions" not in installed:
                    installed.append("django.contrib.sessions")
                    # check session middleware installed
                    # https://docs.djangoproject.com/en/1.7/topics/http/sessions/#enabling-sessions
                    last_position = len(kw["MIDDLEWARE_CLASSES"])
                    kw["MIDDLEWARE_CLASSES"] = list(kw["MIDDLEWARE_CLASSES"])
                    kw["MIDDLEWARE_CLASSES"].insert(
                        last_position,
                        "django.contrib.sessions.middleware.SessionMiddleware"
                    )
                if "django.contrib.admin" not in installed:
                    installed.append("django.contrib.admin")
                    kw["MIDDLEWARE_CLASSES"].append(
                        "django.contrib.auth.middleware"
                        ".AuthenticationMiddleware"
                    )
                if "django.contrib.humanize" not in installed:
                    installed.append("django.contrib.humanize")
                if "django.contrib.staticfiles" not in installed:
                    installed.append("django.contrib.staticfiles")
                if "debug_toolbar" not in installed and debug_toolbar:
                    installed.append("debug_toolbar")
                    if 'INTERNAL_IPS' not in kw:
                        kw['INTERNAL_IPS'] = ('127.0.0.1', '0.0.0.0')
                    kw['MIDDLEWARE_CLASSES'].insert(
                        1,
                        'debug_toolbar.middleware.DebugToolbarMiddleware')
                    kw['DEBUG_TOOLBAR_PANELS'] = (
                        'debug_toolbar.panels.versions.VersionsPanel',
                        'debug_toolbar.panels.timer.TimerPanel',
                        'debug_toolbar.panels.settings.SettingsPanel',
                        'debug_toolbar.panels.headers.HeadersPanel',
                        'debug_toolbar.panels.request.RequestPanel',
                        'debug_toolbar.panels.sql.SQLPanel',
                        'debug_toolbar.panels.staticfiles.StaticFilesPanel',
                        'debug_toolbar.panels.templates.TemplatesPanel',
                        'debug_toolbar.panels.cache.CachePanel',
                        'debug_toolbar.panels.signals.SignalsPanel',
                        'debug_toolbar.panels.logging.LoggingPanel',
                        'debug_toolbar.panels.redirects.RedirectsPanel',
                    )
                    # This one gives 500 if its Enabled without previous syncdb
                    # 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel',

            if django_extensions and werkzeug:
                installed.append('django_extensions')

            # django-jinja 1.0.4 support
            if DJANGO_JINJA:
                installed.append("django_jinja")
                kw['TEMPLATE_LOADERS'] = list(kw.get('TEMPLATE_LOADERS', []))
                kw['TEMPLATE_LOADERS'] += (
                    'django_jinja.loaders.AppLoader',
                    'django_jinja.loaders.FileSystemLoader',
                )
            # coffin 0.3.8 support
            if COFFIN:
                installed.append('coffin')
                kw['TEMPLATE_LOADERS'] = list(kw.get('TEMPLATE_LOADERS', []))
                kw['TEMPLATE_LOADERS'] += (
                    'coffin.contrib.loader.AppLoader',
                    'coffin.contrib.loader.FileSystemLoader',
                )

            kw['INSTALLED_APPS'] = installed

            if "DEBUG" not in kw:
                kw["DEBUG"] = kw["TEMPLATE_DEBUG"] = True
            if "APP_DIR" not in kw:
                kw["APP_DIR"] = self.APP_DIR
            if "SECRET_KEY" not in kw:
                kw["SECRET_KEY"] = self.get_secret_key()
            # admins and managers
            if "ADMINS" not in kw:
                kw["ADMINS"] = kw["MANAGERS"] = ((getuser(), ""), )
            autoimport = kw.pop("autoimport", True)

            kw["SETTINGS_MODULE"] = kw.get("SETTINGS_MODULE", "importd")

            # self._fix_coffin_pre()
            settings.configure(**kw)
            if hasattr(django, "setup"):
                django.setup()

            self._import_django()
            # self._fix_coffin_post()

            from django.contrib.staticfiles.urls import staticfiles_urlpatterns
            urlpatterns = self.get_urlpatterns()
            urlpatterns += staticfiles_urlpatterns()

            if autoimport:
                # django depends on INSTALLED_APPS's model
                for app in settings.INSTALLED_APPS:
                    self._import_app_module("{}.admin", app)
                    self._import_app_module("{}.models", app)

            if admin_url:
                from django.contrib import admin
                try:
                    from django.conf.urls import include
                except ImportError:
                    from django.conf.urls.defaults import include  # lint:ok
                admin.autodiscover()
                self.add_view(admin_url, include(admin.site.urls))

            if autoimport:
                # import .views and .forms for each installed app
                for app in settings.INSTALLED_APPS:
                    self._import_app_module("{}.forms", app)
                    self._import_app_module("{}.views", app)
                    self._import_app_module("{}.signals", app)

        # import blueprints from config
        self.blueprints = kw.pop("blueprints", {})
        for namespace, meta in self.blueprints.items():
            if isinstance(meta, basestring):
                meta = {"blueprint": meta}

            mod_path, bp_name = meta["blueprint"].rsplit(".", 1)
            mod = importlib.import_module(mod_path)
            bp = getattr(mod, bp_name)

            self.register_blueprint(
                bp, url_prefix=meta.get("url_prefix", namespace + "/"),
                namespace=namespace, app_name=meta.get("app_name", ""))

        self._configured = True
Пример #35
0
import logging.config
import os
from os import path

import envdir

log_setting_file_path = path.join(path.dirname(path.abspath(__file__)),
                                  'logging.conf')
logging.config.fileConfig(log_setting_file_path)

ENVDIR_DIRECTORY = os.environ.get("ENVDIR_DIRECTORY", path.join(".env"))

if os.path.exists(ENVDIR_DIRECTORY):
    envdir.open(ENVDIR_DIRECTORY)