コード例 #1
0
    def load_settings(self) -> LazySettings:
        """Put Turbulette app settings together in a LazySettings object.

        The LazySettings object is from ``simple_settings`` library, which accepts
        multiple modules path during instantiation.

        Returns:
            LazySettings: LazySettings initialized with all settings module found
        """
        if not conf.settings:
            all_settings = []

            for app in self.apps.values():
                if (app.package_path / f"{self.settings_module}.py").is_file():
                    all_settings.append(f"{app.package_name}.{self.settings_module}")

            # Add project settings at last position to let user
            # defined settings overwrite default ones
            all_settings.append(self.project_settings_path)

            settings = LazySettings(*all_settings)
            settings._dict["SIMPLE_SETTINGS"] = conf.SIMPLE_SETTINGS
            settings.strategies = (TurbuletteSettingsLoadStrategy,)
            # Make settings variable availble in the `turbulette.conf` package
            conf.settings = settings

            return settings
        return conf.settings
コード例 #2
0
class ProjectSettings(object):
    """
    A Borg ProjectSettings object that you only need to instantiate once.
    """

    __shared_state = {}  # Borg design pattern's shared state.

    def __init__(self, filename=None, *args, **kwargs):
        self.__dict__ = self.__shared_state

        try:
            # check if object was already instantiated
            if self.__dict__.get('filename') and self.__dict__.get('config'):
                return

            if filename:
                self.filename = filename
                self.config = LazySettings(self.filename)
            else:
                raise NotImplementedError
        except NotImplementedError as e:
            print('Please pass a filename first.')
            print(sys.exc_info())
        except Exception as e:
            print(sys.exc_info())

    def __getattr__(self, key):
        """
        Called if there is no class attribute found on the object.
        """
        try:
            if self.config:
                return self.config.as_dict().get(key)
            else:
                raise NotImplementedError
        except NotImplementedError as e:
            print('LazySettings not yet created.')
            print(sys.exc_info())
        except Exception as e:
            print(sys.exc_info())

    def __str__(self):
        return f'ProjectSettings(filename="{self.filename}")'

    def as_dict(self):
        if self.config:
            return self.config.as_dict()
        else:
            return {}
コード例 #3
0
    def __init__(self, filename=None, *args, **kwargs):
        self.__dict__ = self.__shared_state

        try:
            # check if object was already instantiated
            if self.__dict__.get('filename') and self.__dict__.get('config'):
                return

            if filename:
                self.filename = filename
                self.config = LazySettings(self.filename)
            else:
                raise NotImplementedError
        except NotImplementedError as e:
            print('Please pass a filename first.')
            print(sys.exc_info())
        except Exception as e:
            print(sys.exc_info())
コード例 #4
0
    def __init__(self, parent=None):
        super(BrokerConnectionDialog, self).__init__(parent)
        
        self.settings = LazySettings('settings')
        self.broker = BrokerConnection()

        onlyInt = QIntValidator(1, 9999)

        hostLabel = QLabel("Host:")
        self.hostEdit = QLineEdit(self.settings.HOST)

        portLabel = QLabel("Port:")
        self.portEdit = QLineEdit(str(self.settings.PORT))
        self.portEdit.setValidator(onlyInt)

        clientIdLabel = QLabel("Client ID:")
        self.clientIdEdit = QLineEdit('1')
        self.clientIdEdit.setValidator(onlyInt)


        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.groupBox = QGroupBox()
        groupLayout = QVBoxLayout()
        groupLayout.addWidget(hostLabel)
        groupLayout.addWidget(self.hostEdit)
        groupLayout.addWidget(portLabel)
        groupLayout.addWidget(self.portEdit)
        groupLayout.addWidget(clientIdLabel)
        groupLayout.addWidget(self.clientIdEdit)
        groupLayout.addStretch(1)
        self.groupBox.setLayout(groupLayout)
        
        if self.broker.isConnected():
            buttonBox.button(QDialogButtonBox.Ok).setText('Disconnect')
            self.groupBox.setEnabled(False)
        else:
            buttonBox.button(QDialogButtonBox.Ok).setText('Connect')
        
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.groupBox)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("Settings")
コード例 #5
0
from simple_settings import LazySettings

settings = LazySettings('coinmarketcap_slack_notifier.settings')
コード例 #6
0
import pytest
from simple_settings import LazySettings

instance = LazySettings('tests.settings')


@pytest.fixture()
def settings_instance():
    return instance


def test_settings(fake_settings):
    # act
    fake_settings.BAR = 2
    fake_settings.set(BAZ=3)

    # assert
    assert instance.FOO == 1
    assert instance.BAR == 2
    assert instance.BAZ == 3
コード例 #7
0
default_settings = 'settings'

# Everything below this line can be used without modification
settings_module = '.'.join([__package__, default_settings])

import os as _os
if 'SIMPLE_SETTINGS' not in _os.environ:
    _os.environ['SIMPLE_SETTINGS'] = settings_module

from simple_settings import LazySettings

# make simple_settings aware of valid command-line args
LazySettings.COMMAND_LINE_ARGS = ('--settings', '-s')

# set default settings
settings = LazySettings(settings_module)

# with no args, LazySettings first consults any files specified by
#   the command-line --settings arg, then failing that, looks for the
#   file in the SIMPLE_SETTINGS env var;
user_settings = LazySettings()

# override any settings by those in user_settings; hence, with no
#   command-line --settings arg, the default settings will be loaded
#   twice, and the second load (to user_settings) overrides the first
settings.configure(**user_settings.as_dict())

###############################################################################
# logging setup
###############################################################################
コード例 #8
0
ファイル: __init__.py プロジェクト: slawler/PyTelTools
import os
from simple_settings import LazySettings
import sys


# Add default configuration
settings_list = ['pyteltools.conf.default_settings']

# Add user configuration if `PYTELTOOLS_SETTINGS` environment variable is present and not empty
settings_env = os.environ.get('PYTELTOOLS_SETTINGS')
if settings_env is not None:
    if settings_env:
        settings_list.append(settings_env)

try:
    settings = LazySettings(*settings_list)
    settings.as_dict()  # Only check if settings could be read
except FileNotFoundError:
    sys.stderr.write('User configuration file could not be found\n')
    sys.stderr.write('File "%s" does not exist (or check `PYTELTOOLS_SETTINGS` environment file)\n' % settings_env)
    sys.exit(1)
コード例 #9
0
import requests
import re

from lxml.html import fromstring
from simple_settings import LazySettings
from telegram.ext import Updater, CommandHandler

settings = LazySettings('settings.base')
updater = Updater(token=settings.BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher


class TibiaLevelInfo:
    def process(self):
        start_handler = CommandHandler('start', self.start)
        dispatcher.add_handler(start_handler)

        updater.start_polling()

        tibia_level_handler = CommandHandler('level', self._post_info)
        dispatcher.add_handler(tibia_level_handler)

    def start(self, update, context):
        context.bot.send_message(chat_id=update.effective_chat.id,
                                 text="I'm a bot, please talk to me!")

    def _post_info(self, update, context):
        context.bot.send_message(
            chat_id=update.effective_chat.id,
            text=f"{self._get_info(1)} \n{self._get_info(2)}")
コード例 #10
0
from simple_settings import LazySettings

settings = LazySettings('project_settings')

print(settings.SIMPLE_CONF)
コード例 #11
0
#!/usr/bin/python
"""This Script is used to find arbitrage pairs between binance and bittrex"""

from binance.client import Client
from bittrex.bittrex import Bittrex
from simple_settings import LazySettings
settings = LazySettings('settings')

myBinance = Client(settings.BINANCE_API_KEY, settings.BINANCE_API_SECRET)
myBittrex = Bittrex(settings.BITTREX_API_KEY,
                    settings.BITTREX_API_SECRET,
                    api_version='v1.1')

quote_currencies = ['BTC', 'ETH', 'USDT']


def get_trex_list(base):
    test_coins = []
    for coin in myBittrex.get_markets()['result']:
        if coin['BaseCurrency'] == base:
            test_coins.append(coin['MarketCurrency'])
    return test_coins


def get_nance_list(base, coin_list):
    test_coins = []
    final_list = []
    for pair in myBinance.get_exchange_info()['symbols']:
        if pair['quoteAsset'] == base:
            test_coins.append(pair['baseAsset'])
    for test in test_coins:
コード例 #12
0
ファイル: settings.py プロジェクト: COMBAT-TB/vcf_snps_utils
# -*- coding: utf-8 -*-
from simple_settings import LazySettings

settings = LazySettings('conf/config.ini')
コード例 #13
0
# -*- coding: utf-8 -*-
"""Top-level package for Vishuda."""

__author__ = """Cedric ROMAN"""
__email__ = '*****@*****.**'
__version__ = '0.1.0'

from simple_settings import LazySettings
settings = LazySettings('vishuda.config.settings', 'VISHUDA_.environ')

# PROTECTED REGION ID(vishuda.init) ENABLED START
from ngoschema.loaders import register_module
register_module('vishuda')
import ngomm_cms.models

from .vishuda import *
__all__ = [
    'settings',
]
# PROTECTED REGION END
コード例 #14
0
def load_default_app_config(app_name, app_author=None):
    from simple_settings import LazySettings
    settings_list = [str(p.resolve()) for p in search_app_config_files(app_name, app_author)]\
                  + ['%s_.environ' % app_name.upper()]
    settings = LazySettings(*settings_list)
    return settings.as_dict()
コード例 #15
0
# -*- coding: utf-8 -*-

__author__ = """Cedric ROMAN"""
__email__ = "*****@*****.**"
__version__ = "__version__ = '1.0.10'"

# load settings
from simple_settings import LazySettings

settings = LazySettings('ngoschema.config.settings')

# register module and load schemas
from .loaders import register_module

register_module('ngoschema')

from .exceptions import InvalidOperation, SchemaError, ValidationError
from .managers import *
from .protocols import *
from .repositories import *
from .query import Query, Filter
from .registries import serializers_registry, transformers_registry, repositories_registry

# create a default context
from .protocols.context import DEFAULT_CONTEXT

# loads default context file if present in execution dir
DEFAULT_CONTEXT.load_default_context(settings.CLI_CONTEXT_FILENAME)
# adds ngoschema settings dictionary to application context
APP_CONTEXT = DEFAULT_CONTEXT.create_child(_ngoschema_env=settings.as_dict())
コード例 #16
0
from simple_settings import LazySettings

settings = LazySettings('first_settings', 'second_settings')

print(settings.ONLY_IN_FIRST)
print(settings.ONLY_IN_SECOND)
print(settings.SIMPLE_CONF)
コード例 #17
0
__version__ = '{{ cookiecutter.version }}'

from simple_settings import LazySettings
settings = LazySettings('{{ cookiecutter.app_name }}.config.settings',
                        '{{ cookiecutter.app_name|upper }}_.environ')

__all__ = [
    'settings',
]