How to use the baseplate.lib.config.Optional function in baseplate

To help you get started, we’ve selected a few baseplate examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github reddit / baseplate.py / baseplate / clients / cassandra.py View on Github external
* ``contact_points`` (required): comma delimited list of contact points to
      try connecting for cluster discovery
    * ``port``: The server-side port to open connections to.
    * ``credentials_secret`` (optional): the key used to retrieve the database
        credentials from ``secrets`` as a :py:class:`~baseplate.lib.secrets.CredentialSecret`.

    :param execution_profiles: Configured execution profiles to provide to the
        rest of the application.

    """
    assert prefix.endswith(".")
    parser = config.SpecParser(
        {
            "contact_points": config.TupleOf(config.String),
            "port": config.Optional(config.Integer, default=None),
            "credentials_secret": config.Optional(config.String),
        }
    )
    options = parser.parse(prefix[:-1], app_config)

    if options.port:
        kwargs.setdefault("port", options.port)

    if options.credentials_secret:
        if not secrets:
            raise TypeError("'secrets' is required if 'credentials_secret' is set")
        credentials = secrets.get_credentials(options.credentials_secret)
        kwargs.setdefault(
            "auth_provider",
            PlainTextAuthProvider(username=credentials.username, password=credentials.password),
        )
github reddit / baseplate.py / baseplate / sidecars / secrets_fetcher.py View on Github external
"url": config.String,
                "role": config.String,
                "auth_type": config.Optional(
                    config.OneOf(**VaultClientFactory.auth_types()),
                    default=VaultClientFactory.auth_types()["aws"],
                ),
                "mount_point": config.Optional(config.String, default="aws-ec2"),
            },
            "output": {
                "path": config.Optional(config.String, default="/var/local/secrets.json"),
                "owner": config.Optional(config.UnixUser, default=0),
                "group": config.Optional(config.UnixGroup, default=0),
                "mode": config.Optional(config.Integer(base=8), default=0o400),  # type: ignore
            },
            "secrets": config.Optional(config.TupleOf(config.String), default=[]),
            "callback": config.Optional(config.String),
        },
    )

    # pylint: disable=maybe-no-member
    client_factory = VaultClientFactory(
        cfg.vault.url, cfg.vault.role, cfg.vault.auth_type, cfg.vault.mount_point
    )

    if args.once:
        logger.info("Running secret fetcher once")
        fetch_secrets(cfg, client_factory)
        trigger_callback(cfg.callback, cfg.output.path)
    else:
        logger.info("Running secret fetcher as a daemon")
        last_proc = None
        while True:
github reddit / baseplate.py / baseplate / observers / sentry.py View on Github external
:param raw_config: The application configuration which should have
        settings for the error reporter.
    :param module_name: ``__name__`` of the root module of the application.

    """
    cfg = config.parse_config(
        raw_config,
        {
            "sentry": {
                "dsn": config.Optional(config.String, default=None),
                "site": config.Optional(config.String, default=None),
                "environment": config.Optional(config.String, default=None),
                "include_paths": config.Optional(config.String, default=None),
                "exclude_paths": config.Optional(config.String, default=None),
                "ignore_exceptions": config.Optional(config.TupleOf(config.String), default=[]),
                "sample_rate": config.Optional(config.Percent, default=1),
                "processors": config.Optional(
                    config.TupleOf(config.String),
                    default=["raven.processors.SanitizePasswordsProcessor"],
                ),
            }
        },
    )

    application_module = sys.modules[module_name]
    module_path = os.path.abspath(application_module.__file__)
    directory = os.path.dirname(module_path)
    release = None
    while directory != "/":
        try:
            release = raven.fetch_git_sha(directory)
        except raven.exceptions.InvalidGitRepository:
github reddit / baseplate.py / baseplate / observers / sentry.py View on Github external
:param raw_config: The application configuration which should have
        settings for the error reporter.
    :param module_name: ``__name__`` of the root module of the application.

    """
    cfg = config.parse_config(
        raw_config,
        {
            "sentry": {
                "dsn": config.Optional(config.String, default=None),
                "site": config.Optional(config.String, default=None),
                "environment": config.Optional(config.String, default=None),
                "include_paths": config.Optional(config.String, default=None),
                "exclude_paths": config.Optional(config.String, default=None),
                "ignore_exceptions": config.Optional(config.TupleOf(config.String), default=[]),
                "sample_rate": config.Optional(config.Percent, default=1),
                "processors": config.Optional(
                    config.TupleOf(config.String),
                    default=["raven.processors.SanitizePasswordsProcessor"],
                ),
            }
        },
    )

    application_module = sys.modules[module_name]
    module_path = os.path.abspath(application_module.__file__)
    directory = os.path.dirname(module_path)
    release = None
    while directory != "/":
        try:
            release = raven.fetch_git_sha(directory)
github reddit / baseplate.py / baseplate / sidecars / secrets_fetcher.py View on Github external
level = logging.DEBUG
    else:
        level = logging.INFO

    logging.basicConfig(format="%(asctime)s:%(levelname)s:%(message)s", level=level)
    parser = configparser.RawConfigParser()
    parser.read_file(args.config_file)
    fetcher_config = dict(parser.items("secret-fetcher"))

    cfg = config.parse_config(
        fetcher_config,
        {
            "vault": {
                "url": config.String,
                "role": config.String,
                "auth_type": config.Optional(
                    config.OneOf(**VaultClientFactory.auth_types()),
                    default=VaultClientFactory.auth_types()["aws"],
                ),
                "mount_point": config.Optional(config.String, default="aws-ec2"),
            },
            "output": {
                "path": config.Optional(config.String, default="/var/local/secrets.json"),
                "owner": config.Optional(config.UnixUser, default=0),
                "group": config.Optional(config.UnixGroup, default=0),
                "mode": config.Optional(config.Integer(base=8), default=0o400),  # type: ignore
            },
            "secrets": config.Optional(config.TupleOf(config.String), default=[]),
            "callback": config.Optional(config.String),
        },
    )
github reddit / baseplate.py / baseplate / clients / sqlalchemy.py View on Github external
:py:func:`~sqlalchemy.engine.url.make_url` to create the
        :py:class:`~sqlalchemy.engine.url.URL` used to connect to the database.
    * ``credentials_secret`` (optional): the key used to retrieve the database
        credentials from ``secrets`` as a :py:class:`~baseplate.lib.secrets.CredentialSecret`.
        If this is supplied, any credentials given in ``url`` we be replaced by
        these.
    * ``pool_recycle`` (optional): this setting causes the pool to recycle connections after
        the given number of seconds has passed. It defaults to -1, or no timeout.

    """
    assert prefix.endswith(".")
    parser = config.SpecParser(
        {
            "url": config.String,
            "credentials_secret": config.Optional(config.String),
            "pool_recycle": config.Optional(config.Integer),
        }
    )
    options = parser.parse(prefix[:-1], app_config)
    url = make_url(options.url)

    if options.pool_recycle is not None:
        kwargs.setdefault("pool_recycle", options.pool_recycle)

    if options.credentials_secret:
        if not secrets:
            raise TypeError("'secrets' is required if 'credentials_secret' is set")
        credentials = secrets.get_credentials(options.credentials_secret)
        url.username = credentials.username
        url.password = credentials.password

    return create_engine(url, **kwargs)
github reddit / baseplate.py / baseplate / server / runtime_monitor.py View on Github external
def start(server_config: Dict[str, str], application: Any, pool: Pool) -> None:
    baseplate: Baseplate = getattr(application, "baseplate", None)
    if not baseplate or not baseplate._metrics_client:
        logger.info("No metrics client configured. Server metrics will not be sent.")
        return

    cfg = config.parse_config(
        server_config,
        {
            "monitoring": {
                "blocked_hub": config.Optional(config.Timespan, default=None),
                "concurrency": config.Optional(config.Boolean, default=True),
                "connection_pool": config.Optional(config.Boolean, default=False),
                "gc": {
                    "stats": config.Optional(config.Boolean, default=True),
                    "timing": config.Optional(config.Boolean, default=False),
                    "refcycle": config.Optional(config.String, default=None),
                },
            }
        },
    )

    reporters: List[_Reporter] = []

    if cfg.monitoring.concurrency:
        reporters.append(_OpenConnectionsReporter(pool))
        observer = _ActiveRequestsObserver()
        reporters.append(observer)
        baseplate.register(observer)