コード例 #1
0
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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: test_envdir.py プロジェクト: tabulon-ext/envdir
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
ファイル: test_envdir.py プロジェクト: shenkan/envdir
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
ファイル: __init__.py プロジェクト: kfdm/django-pomodoro
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
ファイル: manage.py プロジェクト: felicitydreams/www
#!/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
ファイル: test_envdir.py プロジェクト: squidsoup/envdir
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
ファイル: __init__.py プロジェクト: zhangjianweibj/promgen
# 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
ファイル: settings.py プロジェクト: rockmans/KyleAndEmily
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
ファイル: __init__.py プロジェクト: willharris/plexlib
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
ファイル: __init__.py プロジェクト: intiveda/importd
    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
ファイル: __init__.py プロジェクト: yoavsp/pastebin_indexer
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)