示例#1
0
    def interpolate(self):
        """ Interpolates the considered config.

        In order to perform this variable substitution LXDock will use environment variables plus
        some other pre-defined variables. The later will be injected in the context used to perform
        this interpolation.
        """
        # Builds a dictionary of variables that will be used to perform variable substitution in the
        # config values.
        mapping = {}
        mapping.update(os.environ)

        # Fetches variables that could be defined in a .env file and inserts them in the mapping.
        env_filepath = os.path.join(self.homedir, '.env')
        if os.path.exists(env_filepath):
            mapping.update(dotenv_values(env_filepath))

        # Inserts LXDock special variables into the final mapping.
        mapping.update({
            # The absolute path toward the home directory of the LXDock project is injected into
            # the mapping used to perform variable substitution in the initial config.
            # This can be useful to reference paths that are relative to the project's root
            # directory in LXDock file options such as inline commands.
            'LXDOCK_YML_DIR': self.homedir,
        })

        try:
            self._dict = interpolate_variables(self._dict, mapping)
        except KeyError as e:
            raise ConfigFileInterpolationError(
                'Variable substitution failed when parsing the LXDock file. The failing variable '
                'name is: ${}'.format(e.args[0]))
示例#2
0
def _get_user_credentials(
    api_key: Optional[str] = None,
    full_name: Optional[str] = None,
    affiliation: Optional[str] = None,
    email: Optional[str] = None,
    reason: Optional[str] = None,
    mailing_list: Optional[bool] = None,
) -> Dict[str, str]:
    """Reads user credential file in user's home directory.

    Args:
        api_key (Optional[str], optional): [description]. Defaults to None.
        full_name (Optional[str], optional): [description]. Defaults to None.
        affiliation (Optional[str], optional): [description]. Defaults to None.
        email (Optional[str], optional): [description]. Defaults to None.
        reason (Optional[str], optional): [description]. Defaults to None.
        mailing_list (Optional[bool], optional): [description]. Defaults to
            None.

    Raises:
        FileNotFoundError: Raised if file is not found.
        ValueError: Raised if credential file does not contain entry for
            API_KEY.

    Returns:
        Dict[str, str]: Dictionary of credential values.
    """
    home = Path.home()
    config_file = home.joinpath(".pyNSRDB")
    # config_file doesn't matter if api_key is provided
    if config_file.exists():
        user_config = {
            k.lower(): v
            for k, v in dotenv_values(config_file).items()
        }
        if "api_key" not in user_config:
            raise ValueError(
                "NSRDB credentials do not contain an `API_KEY`"
                "value. Please see documentation for setup instructions.")
    elif api_key is None:
        raise FileNotFoundError(
            "NSRDB credentials not found. Please see documentation for"
            "setup information.")
    else:
        config_file = {}

    # Provided items take precedent over config file?
    items = zip(
        [
            "api_key",
            "full_name",
            "email",
            "affiliation",
            "reason",
            "mailing_list",
        ],
        [api_key, full_name, email, affiliation, reason, mailing_list],
    )
    user_config.update({k: v for k, v in items if v is not None})
    return user_config
示例#3
0
def add_env_to_dockerfile():
    env_path = Path(os.path.join(os.getcwd(), ".env"))
    env_vars = dotenv_values(env_path)
    dockerfile_path = os.path.join(os.getcwd(), DOCKERFILE)

    with open(dockerfile_path, "r") as original_file:
        buf = original_file.readlines()

    with open(dockerfile_path, "w") as modified_file:
        for line in buf:
            if line == DOCKER_ENV_VARS_PLACEMENT:
                for key, value in env_vars.items():
                    line += "ENV {} {}\n".format(key, value)
            modified_file.write(line)
示例#4
0
    def _load_envfile(name, envfiles):
        r = {}

        if not isinstance(envfiles, list):
            LOG.error("invalid payload envfiles. (notifier: %r)", name)
            return r

        for envfile in envfiles:
            try:
                r.update(dotenv_values(envfile))
            except Exception as e:
                LOG.warning("unable to load envfile: %r, error: %r", envfile,
                            e)

        return r
示例#5
0
    def load_dotenv(dotenv_folder, dotenv_file, prefix='IdP', suffix='.env'):
        """
        """
        if dotenv_file is None:
            return {}

        msg = 'prefix must be a string in {}'.format(VALID_ID_PROVIDERS)
        assert prefix in VALID_ID_PROVIDERS, msg

        val = 'ipyauth-' + prefix + '-'
        msg = 'dotenv_file must start with ' + val
        assert dotenv_file.startswith(val), msg

        suffix = '.env'
        msg = 'dotenv_file must end with ' + suffix
        assert dotenv_file.endswith(suffix), msg

        path_dotenv = os.path.join(dotenv_folder, dotenv_file)
        msg = 'file {} does not exist'.format(path_dotenv)
        assert os.path.exists(path_dotenv), msg

        dic = dict(dotenv_values(path_dotenv))

        return dic
示例#6
0
def get_current_config(configPath):
    return main.dotenv_values(configPath)
示例#7
0
    return '.env.development'


dotsetup_path = join(dirname(__file__), '.env.setup')
load_dotenv(dotsetup_path)

# Accessing variables.
MODE = os.getenv('MODE')

#print(MODE)

dotenv = getenvirontment(MODE)
#print(dotenv)

dotenv_path = join(dirname(__file__), dotenv)
environtmens = dotenv_values(dotenv_path)
#load_dotenv(dotenv_path)

#get all keys and set to global variables

for k, v in environtmens.items():
    globals()[k] = v

# globals()['URL_TARGET'] = os.getenv('URL_TARGET')
# globals()['URL_BROWSER'] = os.getenv('URL_BROWSER')
# globals()['USERNAME'] = os.getenv('USERNAME')
globals()['MODE'] = MODE
globals(
)['RUNNING_ON'] = '--headless' if MODE == 'staging' or MODE == 'production' else '-incognito'

# for param in os.environ.keys():
import os

from dotenv.main import dotenv_values

base_dir = os.path.dirname(os.path.abspath(__file__))
env_file_path = os.path.join(base_dir, '.env')

envconf = dotenv_values(env_file_path)

# Configuration file for jupyter-notebook.

#------------------------------------------------------------------------------
# Application(SingletonConfigurable) configuration
#------------------------------------------------------------------------------

## This is an application.

## The date format used by logging formatters for %(asctime)s
#c.Application.log_datefmt = '%Y-%m-%d %H:%M:%S'

## The Logging format template
#c.Application.log_format = '[%(name)s]%(highlevel)s %(message)s'

## Set the log level by value or name.
#c.Application.log_level = 30

#------------------------------------------------------------------------------
# JupyterApp(Application) configuration
#------------------------------------------------------------------------------

## Base class for Jupyter applications
示例#9
0
from dotenv.main import dotenv_values
import requests
from bs4 import BeautifulSoup
from typing import Dict, List, Union
from twilio.rest import Client
from os import environ
from dotenv import load_dotenv, dotenv_values
import webbrowser

load_dotenv()

envValues: Dict[str, str] = dotenv_values('.env')

accountSID: str = envValues['TWILIO_ACCOUNT_SID']
authToken: str = envValues['TWILIO_AUTH_TOKEN']
myPhoneNumber: str = envValues['MY_PHONE']
botPhoneNumber: str = envValues['BOT_PHONE']

rootUrl: str = 'https://www.doctolib.de/institut/berlin/ciz-berlin-berlin?pid=practice-'


class CheckAvailability():
    def __init__(self, rootUrl: str) -> None:
        self.rootUrl: str = rootUrl
        self.headers: Dict[str, str] = {
            "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.170'}
        self.keepChecking: bool = True
        self.accountSID: str = accountSID
        self.authToken: str = authToken
        self.client: object = Client(self.accountSID, self.authToken)
        self.pageInfoDict: Dict[int, str] = {158431: 'Arena Berlin', 158434: 'Messe Berlin / Halle 21',
示例#10
0
from dotenv.main import dotenv_values, find_dotenv
from types import SimpleNamespace
"""
DISCORD_TOKEN
ELASTIC_DOMAIN
ELASTIC_PORT
GUILD_ID
TEST_DISCORD_TOKEN
MONGO_USER
MONGO_PASSWD
MONGO_ENDPOINT
DB_NAME
ALGOLIA_APP_ID
ALGOLIA_SEARCH_KEY
ALGOLIA_ADMIN_KEY
"""


class Config(SimpleNamespace):
    """Basic Config Manager."""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def __contains__(self, key):
        return key in self.__dict__


CONFIG = Config(**dotenv_values(find_dotenv()))

assert 'DISCORD_TOKEN' in CONFIG, "DISCORD_TOKEN must be set in .env"
示例#11
0
def is_brewblox_dir(dir: str) -> bool:  # pragma: no cover
    return const.CFG_VERSION_KEY in dotenv_values(f'{dir}/.env')
示例#12
0
 def env_config(cls):
     """Get autobot configuration values from .env file."""
     return dotenv_values(cls.dotenv_path)
示例#13
0
import os
from dotenv.main import dotenv_values
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .creditals import *

app = Flask(__name__)
app.config.from_object('config')
project_root = os.path.join(os.path.dirname(__file__), '../')
config = dotenv_values(project_root + '.env')

engine = create_engine('mysql://{}:{}@{}/{}'.format(config['MYSQL_USER'],
                                                    config['MYSQL_PASSWORD'],
                                                    config['MYSQL_SERVER'],
                                                    config['MYSQL_DATABASE']))
session = sessionmaker(bind=engine)
session = session()
from app import views
示例#14
0
]
Stimuli_Names = {
    "A": "DMSO",
    "B": "zVD",
    "C": "BPT",
    "D": "BPT_zVD",
    "E": "BPT_Nec1s",
    "F": "BPT_zVD_Nec1s",
    "G": "Nec1s",
    "H": "PIK75"
}

print("\nConfig paths:")
for name, value in globals().copy().items():
    if type(value) == str:
        print(name, value)

##################################
# .env variables
##################################
# Look in directories above for .env file
# ROOT_DIR = os.getenv("ROOT_DIR")
load_dotenv()
EMAIL = os.getenv("EMAIL")

PATH_DICT = dotenv_values()
if len(PATH_DICT) > 0:
    print("Hidden parameters to load:")
    for d in PATH_DICT:
        print(d)