Пример #1
0
def get_configuration(logger):
    """Loads configuration from .env and aws secrets manager"""
    try:

        def configuration():
            return None

        if not find_dotenv(ENV_PATH):
            raise ConfigurationError(strings.ENV_FILE_NOT_FOUND)

        load_dotenv(ENV_PATH, verbose=True)
        configuration.NAME = os.getenv('NAME')
        # Flask debug + testing
        configuration.DEBUG = (os.getenv('FLASK_DEBUG') == 'True')
        configuration.TESTING = (os.getenv('TESTING') == 'True')
        # Auth
        configuration.AUTH_TOKEN_EXPIRY = os.getenv('AUTH_TOKEN_EXPIRY')
        # Logging
        configuration.LOG_CONSOLE_LEVEL = os.getenv('LOG_CONSOLE_LEVEL')
        configuration.LOG_DEBUG_FILE_LEVEL = os.getenv('LOG_DEBUG_FILE_LEVEL')
        configuration.LOG_DEBUG_FILE_TO = os.getenv('LOG_DEBUG_FILE_TO')
        configuration.LOG_ERROR_FILE_LEVEL = os.getenv('LOG_ERROR_FILE_LEVEL')
        configuration.LOG_ERROR_FILE_TO = os.getenv('LOG_ERROR_FILE_TO')
        # SQLAlchemy
        configuration.SQLALCHEMY_DATABASE_URI = os.getenv(
            'SQLALCHEMY_DATABASE_URI')
        configuration.SQLALCHEMY_TRACK_MODIFICATIONS = (
            os.getenv('SQLALCHEMY_TRACK_MODIFICATIONS') == 'True')

        return configuration
    except ConfigurationError as error:
        logger.fatal('[Boot] ' + getattr(error, 'message', str(error)))
        sys.exit(1)
Пример #2
0
 def load_dotenv(dotenv_path=None,
                 stream=None,
                 verbose=False,
                 override=False):
     f = dotenv_path or stream or find_dotenv(usecwd=True)
     return DotEnv(
         f, verbose=verbose).set_as_environment_variables(override=override)
Пример #3
0
def test_app():
    # Create the new board & update the board id environment variable
    file_path = find_dotenv('.env')
    load_dotenv(file_path, override=True)
    os.environ['FLASK_SKIP_LOGIN'] = "******"
    os.environ['MONGO_DB'] = "test_db"

    mongo_srv = os.getenv('MONGO_SRV')
    mongo_user = os.getenv('MONGO_USER')
    mongo_pwd = os.getenv('MONGO_PWD')
    mongo_connection = os.getenv('MONGO_CONNECTION')

    testClient = ToDoMongoClient(mongo_user, mongo_pwd, mongo_srv, "test_db",
                                 mongo_connection)

    admin_user = testClient.add_user("admin_user", "Admin")
    writer_user = testClient.add_user("writer_user", "Writer")
    reader_user = testClient.add_user("reader_user", "Reader")

    application = create_app()

    # start the app in its own thread.
    thread = Thread(target=lambda: application.run(use_reloader=False))
    thread.daemon = True
    thread.start()
    yield application

    # Tear Down
    thread.join(1)
    testClient.delete_user(admin_user.id)
    testClient.delete_user(writer_user.id)
    testClient.delete_user(reader_user.id)
Пример #4
0
def client():
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True, verbose=True)

    with mongomock.patch(servers=(('fakemongo.com', 27017), )):
        test_app = create_app()
        with test_app.test_client() as client:
            yield client
Пример #5
0
def client():
    # Use our test integration config instead of the 'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)
    # Create the new app.
    test_app = app.create_app()
    # Use the app to create a test_client that can be used in our tests.
    with test_app.test_client() as client:
        yield client
Пример #6
0
def client():
    # Use our test integration config instead of the 'real' version
    file_path = find_dotenv('.env.test')
    load_dotenv(file_path, override=True)

    with mongomock.patch(servers=(('test.mongodb.net', 27017), )):
        # Create the new app.
        test_app = create_app()

        # Use the app to create a test_client that can be used in our tests.
        with test_app.test_client() as client:
            yield client
Пример #7
0
def prepare(notebook_id: str, dev: bool = False):
    # Legacy. This will be removed in an upcoming release.

    # actual setup
    dot_env = DotEnv(find_dotenv())
    dot_env.set_as_environment_variables()

    # the rest displays information
    requirement_name_mapping = _get_requirement_name_mapping(dev=dev)
    notebook = _get_notebook(notebook_id, dev=dev)

    requirements = [
        requirement_name_mapping.get(req, req)
        for req in notebook.get("requirements", [])
    ]

    info = dedent(f"""
        ***Notebook Title***  
        {notebook['name']}
        
        ***Notebook Description***  
        {notebook['description']}
        
        """)

    if requirements:
        info += dedent("""
            ***Notebook Dependencies***  
            This notebook requires an active subscription to:
            """)
        info += "".join(f"* {req}\n" for req in requirements)

    info += dedent("""
        ---------
        
        *API credentials have automatically been injected for your active subscriptions.*
        
        The following environment variables are now available:
        """)
    info += "".join(f"* `{k}`\n" for k in dot_env.dict().keys())
    info += "\n-------------\n"

    display(Markdown(info))
Пример #8
0
def app_with_temp_db():
    file_path = find_dotenv('.env')
    load_dotenv(file_path, override=True, verbose=True)
     # Update the mongo db name environment variable
    test_db = "Todo_e2e_tests"
    os.environ['MONGO_DATABASE_NAME'] = test_db
    # construct the new application
    application = create_app()
    # start the app in its own thread.
    thread = Thread(target=lambda: application.run(use_reloader=False))
    thread.daemon = True
    thread.start()

    yield application

    # Tear Down
    thread.join(1)
    mongoClient = pymongo.MongoClient(f'{os.environ["MONGO_CONNECTION_STRING"]}')
    mongoClient.drop_database(test_db)
Пример #9
0
def setup_environment_variables():
    """Called in every notebook to inject credentials to environment"""
    dot_env = DotEnv(find_dotenv())
    dot_env.set_as_environment_variables()
    info = (
        "API credentials have automatically been injected for your active subscriptions.  \n"
        + "The following environment variables are now available:\n" +
        _format_env_list(dot_env.dict().keys()) + "\n")

    user_dot_env_path = "~/custom.env"
    user_dot_env = DotEnv(os.path.expanduser(user_dot_env_path))
    # NOTE: override is not True by default in dotenv
    user_dot_env.set_as_environment_variables()
    user_vars = user_dot_env.dict()
    if user_vars:
        info += (
            f"The following additional environment variables have been loaded from `{user_dot_env_path}`:\n"
            + _format_env_list(user_vars.keys()))

    display(Markdown(info))
Пример #10
0
def end_instance():
    USER_VARIABLES = DotEnv(find_dotenv()).dict()
    GCE_JSON_CERT = os.path.join(os.getcwd(), USER_VARIABLES['GCE_JSON_CERT'])
    GCE_PROJECT_NAME = USER_VARIABLES['GCE_PROJECT_NAME']
    GCE_ZONE = USER_VARIABLES['GCE_ZONE']
    GCE_USER = USER_VARIABLES['GCE_USER']

    credentials = service_account.Credentials.from_service_account_file(
        GCE_JSON_CERT)
    compute = googleapiclient.discovery.build('compute',
                                              'v1',
                                              credentials=credentials)

    result = compute.instances().list(project=GCE_PROJECT_NAME,
                                      zone=GCE_ZONE).execute()
    instance_name = result['items'][0]['name']
    request_id = compute.instances().stop(project=GCE_PROJECT_NAME,
                                          zone=GCE_ZONE,
                                          instance=instance_name).execute()
    wait_for_operation(compute, GCE_PROJECT_NAME, GCE_ZONE, request_id['name'])

    result = compute.instances().list(project=GCE_PROJECT_NAME,
                                      zone=GCE_ZONE).execute()
 def configureExternalVariables(self):
     load_dotenv(find_dotenv())
     self.aasConfigurer.setExternalVariables(os.environ)
     self.serviceLogger.info('External Variables are configured.')
Пример #12
0
from flask import Flask, render_template, request, redirect, url_for, session, g, flash
from flask_mail import Mail, Message
from datetime import datetime, timedelta
from werkzeug.security import check_password_hash
import requests, uuid, os, sys
import scripts.Helper as Helper
from scripts.Helper import populateAccountsListByUserID, populateAccountByAccountNumber, updateUserList, populateEventsListByEndpoint, getUserEditStatus
from scripts.FormTemplates import AccountCreationForm, UserCreationForm, UserPasswordChangeForm, UserPasswordChangeForm
from scripts.FormTemplates import AdminEmailForm, ForgotPasswordForm, AccountEditForm, JournalEntryForm, JournalActionForm
from os.path import join, dirname
from dotenv import load_dotenv
from dotenv.main import find_dotenv

load_dotenv(find_dotenv())

app = Flask(__name__, static_folder='static')
app.config.from_object("config.DevelopementConfig")

app_url = 'http://127.0.0.1:5000'
api_url = 'http://127.0.0.2:5000'

mail = Mail(app)

#adds userdata to list for user tracking and authentication
users = []
users = updateUserList(users, api_url)
SAS = os.environ.get('SAS')


def passwordExEmail(user):
Пример #13
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"
Пример #14
0
    print('Waiting for operation to finish...')
    while True:
        result = compute.zoneOperations().get(project=project,
                                              zone=zone,
                                              operation=operation).execute()

        if result['status'] == 'DONE':
            print("done.")
            if 'error' in result:
                raise Exception(result['error'])
            return result

        time.sleep(1)


USER_VARIABLES = DotEnv(find_dotenv()).dict()
GCE_JSON_CERT = os.path.join(os.getcwd(), USER_VARIABLES['GCE_JSON_CERT'])
GCE_PROJECT_NAME = USER_VARIABLES['GCE_PROJECT_NAME']
GCE_ZONE = USER_VARIABLES['GCE_ZONE']
GCE_USER = USER_VARIABLES['GCE_USER']


def start_message(ip_address):
    print("Connect via")
    print('ssh gce')

    launch_jupyter = ' '.join(['ssh gce "jupyter notebook --port=8888"'])

    print("If you want to launch Jupyer:")
    print(launch_jupyter)
    print('''Connect to it:
Пример #15
0
def get_board():
    file_path = find_dotenv(usecwd=True)
    load_dotenv(file_path, override=True)
    # Create the new board & update the board id environment variable
    trello_transport = TrelloTransport(os.environ.get('TRELLO_API_KEY'), os.environ.get('TRELLO_SERVER_TOKEN'))
    return Boards(trello_transport)