Beispiel #1
0
 def __init__(self, container):
     # type: (AnySettingsContainer) -> None
     """
     Initialize the mongo database from various type of container.
     """
     super(MongoDatabase, self).__init__(container)
     self._database = get_mongodb_engine(container)
     self._settings = get_settings(container)
     self._stores = dict()
Beispiel #2
0
def includeme(config):
    settings = get_settings(config)
    if asbool(settings.get("cowbird.build_docs", False)):
        LOGGER.info("Skipping database when building docs...")
        return

    LOGGER.info("Adding database...")

    def _add_db(request):
        return MongoDatabase(request.registry)

    config.add_request_method(_add_db, "db", reify=True)
Beispiel #3
0
def get_mongodb_connection(container):
    # type: (AnySettingsContainer) -> Database
    """
    Obtains the basic database connection from settings.
    """

    settings = get_settings(container)
    default_mongo_uri = "mongodb://0.0.0.0:27017/cowbird"
    if settings.get("mongo_uri", None) is None:
        warnings.warn(
            "Setting 'mongo_uri' not defined in registry, using default [{}].".
            format(default_mongo_uri))
        settings["mongo_uri"] = default_mongo_uri
    db_url = urlparse(settings["mongo_uri"])
    client = pymongo.MongoClient(
        host=db_url.hostname,
        port=db_url.port,
    )
    db = client[db_url.path[1:]]
    if db_url.username and db_url.password:
        db.authenticate(db_url.username, db_url.password)
    return db
Beispiel #4
0
 def __init__(self):
     self.settings = get_settings(None, app=True)
     config_path = get_config_path()
     svcs_configs = get_all_configs(config_path,
                                    "services",
                                    allow_missing=True)
     self.services_cfg = {}
     for svcs_config in svcs_configs:
         if not svcs_config:
             LOGGER.warning("Services configuration is empty.")
             continue
         for name, cfg in svcs_config.items():
             if name in self.services_cfg:
                 LOGGER.warning(
                     "Ignoring a duplicate service configuration for [%s].",
                     name)
             else:
                 self.services_cfg[name] = cfg
     self.services = {}
     LOGGER.info(
         "Services config : [%s]", ", ".join([
             "{0} [{1}]".format(name, cfg.get("active", False))
             for name, cfg in self.services_cfg.items()
         ]))
Beispiel #5
0
def get_constant(
    constant_name,  # type: str
    settings_container=None,  # type: Optional[AnySettingsContainer]
    settings_name=None,  # type: Optional[str]
    default_value=None,  # type: Optional[SettingValue]
    raise_missing=True,  # type: bool
    print_missing=False,  # type: bool
    raise_not_set=True  # type: bool
):  # type: (...) -> SettingValue
    """
    Search in order for matched value of :paramref:`constant_name`:
      1. search in :py:data:`COWBIRD_CONSTANTS`
      2. search in settings if specified
      3. search alternative setting names (see below)
      4. search in :mod:`cowbird.constants` definitions
      5. search in environment variables

    Parameter :paramref:`constant_name` is expected to have the format ``COWBIRD_[VARIABLE_NAME]`` although any value
    can be passed to retrieve generic settings from all above mentioned search locations.

    If :paramref:`settings_name` is provided as alternative name, it is used as is to search for results if
    :paramref:`constant_name` was not found. Otherwise, ``cowbird.[variable_name]`` is used for additional search when
    the format ``COWBIRD_[VARIABLE_NAME]`` was used for :paramref:`constant_name`
    (i.e.: ``COWBIRD_ADMIN_USER`` will also search for ``cowbird.admin_user`` and so on for corresponding constants).

    :param constant_name: key to search for a value
    :param settings_container: WSGI application settings container (if not provided, uses found one in current thread)
    :param settings_name: alternative name for `settings` if specified
    :param default_value: default value to be returned if not found anywhere, and exception raises are disabled.
    :param raise_missing: raise exception if key is not found anywhere
    :param print_missing: print message if key is not found anywhere, return ``None``
    :param raise_not_set: raise an exception if the found key is ``None``, search until last case if others are ``None``
    :returns: found value or `default_value`
    :raises ValueError: if resulting value is invalid based on options (by default raise missing/``None`` value)
    :raises LookupError: if no appropriate value could be found from all search locations (according to options)
    """
    from cowbird.utils import get_settings, print_log, raise_log  # pylint: disable=C0415  # avoid circular import error

    if constant_name in COWBIRD_CONSTANTS:
        return globals()[constant_name]
    missing = True
    cowbird_value = None
    if settings_container:
        settings = get_settings(settings_container)
    else:
        # note: this will work only after include of cowbird will have triggered configurator setup
        print_log("Using settings from local thread.", level=logging.DEBUG)
        settings = get_settings(get_current_registry())
    if settings and constant_name in settings:  # pylint: disable=E1135
        missing = False
        cowbird_value = settings.get(constant_name)
        if cowbird_value is not None:
            print_log(
                "Constant found in settings with: {}".format(constant_name),
                level=logging.DEBUG)
            return cowbird_value
    if not settings_name:
        settings_name = get_constant_setting_name(constant_name)
        print_log("Constant alternate search: {}".format(settings_name),
                  level=logging.DEBUG)
    if settings and settings_name and settings_name in settings:  # pylint: disable=E1135
        missing = False
        cowbird_value = settings.get(settings_name)
        if cowbird_value is not None:
            print_log(
                "Constant found in settings with: {}".format(settings_name),
                level=logging.DEBUG)
            return cowbird_value
    cowbird_globals = globals()
    if constant_name in cowbird_globals:
        missing = False
        cowbird_value = cowbird_globals.get(constant_name)
        if cowbird_value is not None:
            print_log(
                "Constant found in definitions with: {}".format(constant_name),
                level=logging.DEBUG)
            return cowbird_value
    if constant_name in os.environ:
        missing = False
        cowbird_value = os.environ.get(constant_name)
        if cowbird_value is not None:
            print_log(
                "Constant found in environment with: {}".format(constant_name),
                level=logging.DEBUG)
            return cowbird_value
    if not missing and raise_not_set:
        raise_log(
            "Constant was found but was not set: {}".format(constant_name),
            level=logging.ERROR,
            exception=ValueError)
    if missing and raise_missing:
        raise_log("Constant could not be found: {}".format(constant_name),
                  level=logging.ERROR,
                  exception=LookupError)
    if missing and print_missing:
        print_log("Constant could not be found: {} (using default: {})".format(
            constant_name, default_value),
                  level=logging.WARN)
    return cowbird_value or default_value