Beispiel #1
0
def get_nearest_config(fname: str = "config.env",
                       limit: int = 4,
                       devmode: bool = False,
                       start_dir: Union[str, None] = None):
    """
    Look for a file `fname` in the directory of the calling file and then up the tree (up to `limit`-steps).

    Advantage over directly using `from decouple import config` the full filename can be defined explicitly.

    :param fname:
    :param limit:       How much steps to go up at maximum
    :param devmode:     Flag that triggers development mode (default: False).
                        If True variables which end with "__DEVMODE" will replace variables without such appendix

    :param start_dir:   (optional) start directory

    :return:    config object from decoupl module
    """
    assert fname.endswith(".ini")

    old_dir = os.getcwd()

    if start_dir is None:
        start_dir = get_dir_of_this_file(upcount=2)
    else:
        assert os.path.isdir(start_dir)
    os.chdir(start_dir)

    path_list = [fname]
    for i in range(limit + 1):
        path = os.path.join(*path_list)
        if os.path.isfile(path):
            break
        path_list.insert(0, "..")
    else:
        msg = f"Could not find {fname} in current directory nor in {limit} parent dirs."
        raise FileNotFoundError(msg)
    from decouple import Config, RepositoryIni, Csv

    config = Config(RepositoryIni(path))

    if devmode:
        relevant_dict = config.repository.parser.__dict__["_sections"][
            "settings"]
        for key, value in relevant_dict.items():
            # it seems that keys are converted to lowercase automatically
            if key.endswith("__devmode"):

                # use the value specified for the development-mode for the actual variable (if it exists)
                main_key = key.replace("__devmode", "")
                if main_key in relevant_dict:
                    relevant_dict[main_key] = value

    # enable convenient access to Csv parser and actual path of the file
    config.Csv = Csv
    config.path = os.path.abspath(path)

    os.chdir(old_dir)
    return config
Beispiel #2
0
def configs():
    encoding = 'utf8'
    env_path, ini_path = write_files(encoding)
    yield [
        Config(RepositoryEnv(env_path, encoding)),
        Config(RepositoryIni(ini_path, encoding))
    ]
    clean((env_path, ini_path))
Beispiel #3
0
def test_another_encoding():
    encoding = 'cp1251'
    env_path, ini_path = write_files(encoding)
    configs = [
        Config(RepositoryEnv(env_path, encoding)),
        Config(RepositoryIni(ini_path, encoding))
    ]
    assert_all_equals(configs, 'KeyUTF8', u'значение')
Beispiel #4
0
def insert(data):

    DOTENV_FILE = '/home/pi/Desktop/smart-greenhouse/.env'
    env_config = Config(RepositoryEnv(DOTENV_FILE))

    state_name_id = data[0]
    state = data[1]
    value = data[2]
    created_at = data[3]

    # Read database connection url from .env
    DATABASE_URL = env_config.get('DATABASE_URL')

    postgres_insert_query = """
                            INSERT INTO data_state (
                                state_name_id,
                                state,
                                value,
                                created_at
                            ) 
                            VALUES (
                                %s, %s, %s, %s
                            )
                            """

    record_to_insert = (state_name_id, state, value, created_at)

    con = None
    try:
        # create a new database connection by calling the connect() function
        con = psycopg2.connect(DATABASE_URL)

        #  create a new cursor
        cur = con.cursor()
        cur.execute(postgres_insert_query, record_to_insert)
        con.commit()
        print(state_name_id, " successfully inserted into table")

        # close the communication with the HerokuPostgres
        cur.close()
    except Exception as error:
        print('Could not connect')
        print('Cause: {}'.format(error))

    finally:
        # close the communication with the database server by calling the close()
        if con is not None:
            con.close()
            print('Connection closed')
Beispiel #5
0
class Settings:
    secret = Config(RepositoryEnv('.secret'))
    TOKEN = secret.get('TOKEN')

    PATTERN_FILTER = config('PATTERN_FILTER')
    KEYFORGE_API = config('KEYFORGE_API')
    LOGGING_PATH = config('LOGGING_PATH')
def test_secret_overriden_by_environ():
    path = os.path.join(os.path.dirname(__file__), 'secrets')
    config = Config(RepositorySecret(path))

    os.environ['db_user'] = '******'
    assert 'hi' == config('db_user')
    del os.environ['db_user']
def test_no_secret_but_present_in_os_environ():
    path = os.path.join(os.path.dirname(__file__), 'secrets')
    config = Config(RepositorySecret(path))

    os.environ['KeyOnlyEnviron'] = 'SOMETHING'
    assert 'SOMETHING' == config('KeyOnlyEnviron')
    del os.environ['KeyOnlyEnviron']
Beispiel #8
0
    def setUpClass(cls):
        log = logging.getLogger("CommonTest")
        log.debug("Setting up CommonTest")

        DOTENV_FILE = '.env.test'
        env_config = Config(RepositoryEnv(DOTENV_FILE))

        cls.secret_key = config('SHARED_SECRET_ADENINE')
        cls.did_to_use = env_config('DID_TO_USE')
 def init_config(self, hive_config='/etc/hive/.env'):
     env_dist = os.environ
     if "HIVE_CONFIG" in env_dist:
         hive_config = env_dist["HIVE_CONFIG"]
     config_file = Path(hive_config).resolve()
     if config_file.exists():
         self.env_config = Config(RepositoryEnv(config_file.as_posix()))
         logging.getLogger("Setting").debug("Config file is:" +
                                            config_file.as_posix())
         print("Setting Config file is:" + config_file.as_posix())
 def __init__(self, global_config_file_path):
     # global_config holds environment variables that don't change often
     # such as LDAP parameters and project_db stuff
     global_config = Config(RepositoryEnv(global_config_file_path))
     self.url_base = global_config('ROR_URL')
     self.proxies = {
         "http": global_config('PROXY_HTTP', default=None),
         "https": global_config('PROXY_HTTPS', default=None)
     }
     if self.proxies['http'] == None and self.proxies['https'] == None:
         self.proxies = None
Beispiel #11
0
def get_config(source, region):
    """ Get config object but fallback to AutoConfig if AWS connection fails"""
    try:
        logger.debug(
            'Querying AWS Secrets manager for %s in region %s', source, region)
        repo = RepositoryAwsSecretManager(source, region)
        logger.debug('Successfully queried for %s in region %s',
                     source, region)
        return Config(repo)
    except AWSException as e:
        logger.error(
            'Failed retrieving secrets from AWS Secrets Manager: %s', e)
        return AutoConfig()
Beispiel #12
0
    def setUpClass(cls):
        log = logging.getLogger("NodeRpcTest")
        log.debug("Setting up NodeRpcTest")

        DOTENV_FILE = '.env.test'
        env_config = Config(RepositoryEnv(DOTENV_FILE))

        cls.network = env_config('NETWORK')
        cls.ela_to_use = env_config('ELA_TO_USE')
        cls.ela_eth_to_use = env_config('ELA_ETH_TO_USE')
        cls.did_to_use = env_config('DID_TO_USE')
        cls.api_key_to_use = get_api_from_did(cls.did_to_use)
        cls.private_key_to_use = env_config('PRIVATE_KEY_TO_USE')
Beispiel #13
0
def set_test_input(request):
    global env_config

    DOTENV_FILE = '.env.test'
    env_config = Config(RepositoryEnv(DOTENV_FILE))

    test_input['host'] = config('GRPC_SERVER_HOST')
    test_input['port'] = config('GRPC_SERVER_PORT')
    test_input['production'] = config('PRODUCTION', default=False, cast=bool)
    test_input['network'] = env_config('NETWORK')
    test_input['ela_to_use'] = env_config('ELA_TO_USE')
    test_input['ela_eth_to_use'] = env_config('ELA_ETH_TO_USE')
    test_input['did_to_use'] = env_config('DID_TO_USE')
    test_input['private_key_to_use'] = env_config('PRIVATE_KEY_TO_USE')
    return test_input
Beispiel #14
0
import os
from itertools import zip_longest
from threading import Event  # Wait for an event to occur

from django.db import transaction, IntegrityError
from decouple import Config, RepositoryEnv, UndefinedValueError
from redis import StrictRedis, WatchError
import socketio

from .chatbot import room_to_chatbot_user, ChatBotUser
from .serializers import ChatBoxMessageSerializer
from .models import ChatRoom

# Redis Server Options
DOTENV_FILE = os.path.join(os.getcwd(), 'chatbox_socketio', '.env')
env_config = Config(RepositoryEnv(DOTENV_FILE))

HOST = env_config.get('REDIS_SERVER_HOST')

try:
    PASSWORD = env_config.get('REDIS_SERVER_PASSWORD')
except UndefinedValueError:
    PASSWORD = None

PORT = env_config.get('REDIS_SERVER_PORT')

if PASSWORD is None:
    REDIS_CONNECTION = StrictRedis(host=HOST, port=PORT)
else:
    REDIS_CONNECTION = StrictRedis(host=HOST, password=PASSWORD, port=PORT)
Beispiel #15
0
from decouple import Config, RepositoryEnv
from .common import *

# Go up two directories from project base and then into config
env_path = os.path.join(BASE_DIR,'..','..','config','production.env')

env_config = Config(RepositoryEnv(env_path))

SECRET_KEY = env_config.get('PROJECT_SECRET_KEY')
# Key for GEOCODE and MAPS API
GOOGLE_GEOCODE_API_KEY = env_config.get('GOOGLE_GEOCODE_API_KEY')
# Key for PLACES API
GOOGLE_PLACES_API_KEY = env_config.get('GOOGLE_PLACES_API_KEY')
# Key for DIRECTIONS API
GOOGLE_DIRECTIONS_API_KEY = env_config.get('GOOGLE_DIRECTIONS_API_KEY')

DEBUG = env_config.get('DEBUG',cast=bool)
ALLOWED_HOSTS = env_config.get('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])

DATABASES = {
    'default': {
        'ENGINE': env_config.get('DB_ENGINE'), 
        'NAME': env_config.get('DB_NAME'),
        'USER': env_config.get('DB_USER'),
        'PASSWORD': env_config.get('DB_PASSWORD'),
        'HOST': env_config.get('DB_HOST'),   # Or an IP Address that your DB is hosted on
        'PORT': env_config.get('DB_PORT'),
    }
}
import boto3
from boto3.dynamodb.conditions import Key, Attr
import datetime
import uuid
import boto3
import datetime
import uuid
from decouple import Config, RepositoryEnv

DOTENV_PATH = ".env"
env = Config(RepositoryEnv(DOTENV_PATH))

# Call user/event table from AWS
session = boto3.Session(
    aws_access_key_id=env.get('AWS_ACCESS_KEY_ID'),
    aws_secret_access_key=env.get('AWS_SECRET_ACCESS_KEY'),
)
s3 = session.client('s3')
dynamodb = session.resource('dynamodb', region_name='ap-southeast-2')
meet_ball_user = dynamodb.Table('meet_ball_user')

# Note compulsory attributes name, host_id, location
# Attributes without values will use default vaues

# If creating new event attributes can be empty
# if person_limit, time_limit and radius are empty enter default values


def add_event_to_table(host_id, name, place, description, photo, time,
                       person_limit, time_limit, radius):
Beispiel #17
0
from decouple import Config, RepositoryEnv
from .common import *

# decouple, by default searches for .env files in repo root
# Need to point it in the right directory which is config/production.env
env_path = os.path.join(BASE_DIR,'..','..','config','production.env')

env_config = Config(RepositoryEnv(env_path))
SECRET_KEY = env_config.get('SECRET_KEY')
DEBUG = env_config.get('DEBUG',cast=bool)
# Allowed Hosts should be a list
ALLOWD_HOSTS = env_config.get('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')])

DATABASES = {
    'default': {
        'ENGINE': env_config.get('DB_ENGINE'),
        'NAME': env_config.get('DB_NAME'),
        'USER': env_config.get('DB_USER'),
        'PASSWORD': env_config.get('DB_PASSWORD'),
        'HOST': env_config.get('DB_HOST'),
        'PORT': env_config.get('DB_PORT')
    }
}
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import datetime
import os

from decouple import Config, RepositoryEnv, config

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SERVER_ENV = os.environ.get('SERVER_ENV')

if SERVER_ENV == 'prod':
    ENV_FILE = os.path.join(BASE_DIR, '.env.prod')
    env_config = Config(RepositoryEnv(ENV_FILE))
elif SERVER_ENV == 'heroku-prod':
    env_config = config
else:
    ENV_FILE = os.path.join(BASE_DIR, '.env.dev')
    env_config = Config(RepositoryEnv(ENV_FILE))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env_config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env_config("DEBUG", cast=bool)

ALLOWED_HOSTS = ['*']
Beispiel #19
0
from decouple import Config, RepositoryEnv
from dj_database_url import parse as db_url
from cmj.settings import *  # flake8: noqa

config = Config(RepositoryEnv(BASE_DIR.child('.env')))

INSTALLED_APPS += ('cmj.legacy_sislegis_publicacoes', )

DATABASES['legacy_sislegis_publicacoes'] = config(
    'DATABASE_URL_SISLEGIS_PUBLICACOES',
    cast=db_url,
)

DATABASE_ROUTERS = [
    'cmj.legacy_sislegis_publicacoes.router.LegacyRouter',
]

DEBUG = True
Beispiel #20
0
https://docs.djangoproject.com/en/3.0/topics/settings/

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

import os
import json

from decouple import Config, RepositoryEnv
from datetime import timedelta

from ast import literal_eval

DOTENV_FILE = './.env'
env_config = Config(RepositoryEnv(DOTENV_FILE))

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

IMPORTED_SETTINGS = None

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env_config.get('SECRET_KEY')

# Application definition

INSTALLED_APPS = [
Beispiel #21
0
def config():
    with patch('decouple.open', return_value=StringIO(INIFILE), create=True):
        return Config(RepositoryIni('settings.ini'))
Beispiel #22
0
from .base import *

from decouple import Csv, Config, RepositoryEnv

# Set config as .env.dev file
env_path = 'notebook/settings/.env.staging'
env_config = Config(RepositoryEnv(env_path))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env_config.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env_config.get('DEBUG', default=False, cast=bool)

ALLOWED_HOSTS = env_config.get('ALLOWED_HOSTS', cast=Csv())

# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': env_config.get('DB_NAME'),
        'USER': env_config.get('DB_USER'),
        'PASSWORD': env_config.get('DB_PASSWORD'),
        'HOST': env_config.get('DB_HOST'),
        'PORT': env_config.get('DB_PORT'),
    }
}
Beispiel #23
0
from decouple import RepositoryIni, Config

config = Config(RepositoryIni("settings.ini"))

CLIENT_ID = config("CLIENT_ID")
CLIENT_SECRET = config("CLIENT_SECRET")
SPOTIPY_REDIRECT_URI = config("SPOTIPY_REDIRECT_URI")
DB_CONNSTR = config("DB_CONNSTR")
class AppConfig:
    SECRET_KEY = Config('SECRET')
    MONGO_URI = Config('MONGO_URI')
    DB_NAME = Config('DB_NAME')
from os.path import dirname, abspath, join
from decouple import Config, RepositoryEnv

BASE_DIR = dirname(abspath(__file__))
DOTENV_FILE = join(BASE_DIR, '.env')
env_config = Config(RepositoryEnv(DOTENV_FILE))

SERVER_ADDR = env_config.get("SERVER_ADDR")
SERVER_PORT = env_config.get("SERVER_PORT")
MSG_LEN = 1024
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
from decouple import Config, RepositoryEnv

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

# Load config file
DOTENV_FILE = BASE_DIR + '/config.ini'
config = Config(RepositoryEnv(DOTENV_FILE))

# 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 = config.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config.get('DEBUG', cast=bool)

ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

# Application definition

INSTALLED_APPS = [
Beispiel #27
0
import os

from decouple import Config, RepositoryEnv, AutoConfig
from dj_database_url import parse as db_url

from .settings import *  # flake8: noqa

config = AutoConfig()
config.config = Config(RepositoryEnv(os.path.abspath('sapl/legacy/.env')))

INSTALLED_APPS += (
    'sapl.legacy',  # legacy reversed model definitions
)

DATABASES['legacy'] = config(
    'DATABASE_URL',
    cast=db_url,
)
"""DATABASES['legacy'] = {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'legacy_interlegis',
    'USER': '******',
    'PASSWORD': '',
    'HOST': '',   # Or an IP Address that your DB is hosted on
    'PORT': '3306',
}
"""

DATABASE_ROUTERS = [
    'sapl.legacy.router.LegacyRouter',
]
Beispiel #28
0
from pathlib import Path

import firebase_admin
from celery.schedules import crontab
from decouple import Config, RepositoryEnv

# Build paths inside the project like this: BASE_DIR / 'subdir'.
from firebase_admin import credentials

BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent

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

ENV_FILE = os.path.join(BASE_DIR, ".env.prod")
env_config = Config(RepositoryEnv(ENV_FILE))

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env_config.get("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(env_config.get("DEBUG", default=0))

ALLOWED_HOSTS = env_config.get("DJANGO_ALLOWED_HOSTS").split(" ")

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
Beispiel #29
0
from __future__ import absolute_import, unicode_literals

from decouple import Config, Csv, RepositoryIni
from pathlib2 import Path

from .auth.models import Customer, User, auth_index

# TODO should we pull the path from cli args or an env var?
config_path = str(Path(Path(__file__).parent, '../configs/settings.ini').resolve())
config = Config(RepositoryIni(config_path))

BASE_DIR = str(Path(__file__).parent)
ROOT_DIR = str(Path(__file__).parent.parent)

PORT = config('PORT', default=8080, cast=int)

DEBUG = config('DEBUG', default=False, cast=bool)
TESTING = config('TESTING', default=False, cast=bool)

SECRET_KEY = config('SECRET_KEY')

AUTH_JWT_ALGORITHM = config('AUTH_JWT_ALGORITHM', default='HS512')
AUTH_JWT_SECRET = config('AUTH_JWT_SECRET', default='phukoo9EMie5mei1yaeteeN')
AUTH_TOKEN_ISSUER = config('AUTH_TOKEN_ISSUER', default='RelES')
AUTH_TOKEN_LIFETIME = config('AUTH_TOKEN_LIFETIME', default=36000, cast=int)

CYCLES_CRUD = config('CYCLES_CRUD', default=1)
CYCLES_FACTOR_REFRESH = config('CYCLES_FACTOR_REFRESH', default=2)
CYCLES_GET_ARCHIVED_DOCUMENT = config('CYCLES_GET_ARCHIVED_DOCUMENT', default=1)
CYCLES_FILE_UPLOAD = config('CYCLES_FILE_UPLOAD', default=1)
CYCLES_GEOCODING = config('CYCLES_GEOCODING', default=1)
Beispiel #30
0
Django settings for config project.

Generated by 'django-admin startproject' using Django 3.1.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
from decouple import Config, RepositoryEnv

ENV_PATH = 'env/configuration.' + os.environ['PYTHONENV'] + '.env'
conf = Config(RepositoryEnv(ENV_PATH))

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = conf('SECRET_KEY')

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

ALLOWED_HOSTS = []