Python voluptuous.Required() Examples

The following are 30 code examples of voluptuous.Required(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module voluptuous , or try the search function .
Example #1
Source File: create_schema.py    From visonic with Apache License 2.0 6 votes vote down vote up
def create_parameters1(options):
    # Panel settings - can only be set on creation
    return {
        vol.Required(CONF_LANGUAGE,         default=create_default(options, CONF_LANGUAGE, "EN") )         : str,
        vol.Optional(CONF_EXCLUDE_SENSOR,   default=create_default(options, CONF_EXCLUDE_SENSOR, ""))      : str,
        vol.Optional(CONF_EXCLUDE_X10,      default=create_default(options, CONF_EXCLUDE_X10, ""))         : str,
        vol.Optional(CONF_DOWNLOAD_CODE,    default=create_default(options, CONF_DOWNLOAD_CODE, "") )      : str,
        vol.Optional(CONF_FORCE_STANDARD,   default=create_default(options, CONF_FORCE_STANDARD, False))   : bool, 
        vol.Optional(CONF_FORCE_AUTOENROLL, default=create_default(options, CONF_FORCE_AUTOENROLL, False)) : bool, 
        vol.Optional(CONF_AUTO_SYNC_TIME,   default=create_default(options, CONF_AUTO_SYNC_TIME, True))    : bool
    } 
Example #2
Source File: config_flow.py    From unifiprotect with MIT License 6 votes vote down vote up
def _show_setup_form(self, errors=None):
        """Show the setup form to the user."""
        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_HOST): str,
                    vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
                    vol.Required(CONF_USERNAME): str,
                    vol.Required(CONF_PASSWORD): str,
                    vol.Optional(
                        CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
                    ): vol.All(vol.Coerce(int), vol.Range(min=2, max=20)),
                    vol.Optional(CONF_SNAPSHOT_DIRECT, default=False): bool,
                    vol.Optional(CONF_IR_ON, default=TYPE_IR_AUTO): vol.In(TYPES_IR_ON),
                    vol.Optional(CONF_IR_OFF, default=TYPE_IR_OFF): vol.In(
                        TYPES_IR_OFF
                    ),
                }
            ),
            errors=errors or {},
        ) 
Example #3
Source File: test_utils.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def test_simple_add_input_schema_body(self):

        @api_utils.add_input_schema('body', {
            voluptuous.Required(
                'arg_one', default='one'): api_utils.SingleQueryParam(str),
        })
        def test_func(self, arg_one=None):
            self.assertEqual(arg_one, 'one')

        self.assertEqual(len(test_func.input_schema.schema.keys()), 1)
        self.assertEqual(
            list(test_func.input_schema.schema.keys())[0], 'arg_one')

        with mock.patch('flask.request') as m:
            m.get_json.return_value = {}
            test_func(self)

        with mock.patch('flask.request') as m:
            m.get_json.return_value = {'arg_one': 'one'}
            test_func(self) 
Example #4
Source File: test_utils.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def test_simple_add_input_schema_query(self):

        @api_utils.add_input_schema('query', {
            voluptuous.Required(
                'arg_one', default='one'): api_utils.SingleQueryParam(str),
        })
        def test_func(self, arg_one=None):
            self.assertEqual(arg_one, 'one')

        self.assertEqual(len(test_func.input_schema.schema.keys()), 1)
        self.assertEqual(
            list(test_func.input_schema.schema.keys())[0], 'arg_one')

        with mock.patch('flask.request') as m:
            m.args = MultiDict({})
            test_func(self)
            m.args = MultiDict({'arg_one': 'one'})
            test_func(self) 
Example #5
Source File: dataframe.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def from_dict(cls, dict_, legacy=False):
        try:
            schema = DATAFRAME_SCHEMA
            if legacy:
                validator = functools.partial(DataPoint.from_dict, legacy=True)
                # NOTE(peschk_l): __name__ is required for voluptuous exception
                # message formatting
                validator.__name__ = 'DataPoint.from_dict'
                # NOTE(peschk_l): In case the legacy format is required, we
                # create a new schema where DataPoint.from_dict is called with
                # legacy=True. The "extend" method does create a new objects,
                # and replaces existing keys with new ones.
                schema = DATAFRAME_SCHEMA.extend({
                    voluptuous.Required('usage'): vutils.IterableValuesDict(
                        str, validator
                    ),
                })
            valid = schema(dict_)
            return cls(
                valid["period"]["begin"],
                valid["period"]["end"],
                usage=valid["usage"])
        except (voluptuous.error.Invalid, KeyError) as e:
            raise ValueError("{} isn't a valid DataFrame: {}".format(dict_, e)) 
Example #6
Source File: config_flow.py    From Anniversaries with MIT License 6 votes vote down vote up
def _show_icon_form(self, user_input):
        icon_normal = DEFAULT_ICON_NORMAL
        icon_today = DEFAULT_ICON_TODAY
        days_as_soon = DEFAULT_SOON
        icon_soon = DEFAULT_ICON_SOON
        if user_input is not None:
            if CONF_ICON_NORMAL in user_input:
                icon_normal = user_input[CONF_ICON_NORMAL]
            if CONF_ICON_TODAY in user_input:
                icon_today = user_input[CONF_ICON_TODAY]
            if CONF_SOON in user_input:
                days_as_soon = user_input[CONF_SOON]
            if CONF_ICON_SOON in user_input:
                icon_soon = user_input[CONF_ICON_SOON]
        data_schema = OrderedDict()
        data_schema[vol.Required(CONF_ICON_NORMAL, default=icon_normal)] = str
        data_schema[vol.Required(CONF_ICON_TODAY, default=icon_today)] = str
        data_schema[vol.Required(CONF_SOON, default=days_as_soon)] = int
        data_schema[vol.Required(CONF_ICON_SOON, default=icon_soon)] = str
        return self.async_show_form(step_id="icons", data_schema=vol.Schema(data_schema), errors=self._errors) 
Example #7
Source File: config_flow.py    From Anniversaries with MIT License 6 votes vote down vote up
def _show_init_form(self, user_input):
        data_schema = OrderedDict()
        one_time = self.config_entry.options.get(CONF_ONE_TIME)
        unit_of_measurement = self.config_entry.options.get(CONF_UNIT_OF_MEASUREMENT)
        half_anniversary = self.config_entry.options.get(CONF_HALF_ANNIVERSARY)
        if one_time is None:
            one_time = DEFAULT_ONE_TIME
        if half_anniversary is None:
            half_anniversary = DEFAULT_HALF_ANNIVERSARY
        if unit_of_measurement is None:
            unit_of_measurement = DEFAULT_UNIT_OF_MEASUREMENT
        data_schema[vol.Required(CONF_NAME,default=self.config_entry.options.get(CONF_NAME),)] = str
        data_schema[vol.Required(CONF_DATE, default=self.config_entry.options.get(CONF_DATE),)] = str
        data_schema[vol.Required(CONF_ONE_TIME, default=one_time,)] = bool
        data_schema[vol.Required(CONF_HALF_ANNIVERSARY,default=half_anniversary,)] = bool
        data_schema[vol.Required(CONF_DATE_FORMAT,default=self.config_entry.options.get(CONF_DATE_FORMAT),)] = str
        data_schema[vol.Required(CONF_UNIT_OF_MEASUREMENT,default=unit_of_measurement,)] = str
        return self.async_show_form(
            step_id="init", data_schema=vol.Schema(data_schema), errors=self._errors
        ) 
Example #8
Source File: api.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def patch(self):
        ap = pecan.request.indexer.get_archive_policy(self.archive_policy)
        if not ap:
            abort(404, six.text_type(
                indexer.NoSuchArchivePolicy(self.archive_policy)))
        enforce("update archive policy", ap)

        body = deserialize_and_validate(voluptuous.Schema({
            voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
        }))
        # Validate the data
        try:
            ap_items = [archive_policy.ArchivePolicyItem(**item) for item in
                        body['definition']]
        except ValueError as e:
            abort(400, six.text_type(e))

        try:
            return pecan.request.indexer.update_archive_policy(
                self.archive_policy, ap_items)
        except indexer.UnsupportedArchivePolicyChange as e:
            abort(400, six.text_type(e)) 
Example #9
Source File: resource_type.py    From gnocchi with Apache License 2.0 6 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(ResourceTypeSchemaManager, self).__init__(*args, **kwargs)
        type_schemas = tuple([ext.plugin.meta_schema()
                              for ext in self.extensions])
        self._schema = voluptuous.Schema({
            "name": six.text_type,
            voluptuous.Required("attributes", default={}): {
                six.text_type: voluptuous.Any(*tuple(type_schemas))
            }
        })

        type_schemas = tuple([ext.plugin.meta_schema(for_update=True)
                              for ext in self.extensions])
        self._schema_for_update = voluptuous.Schema({
            "name": six.text_type,
            voluptuous.Required("attributes", default={}): {
                six.text_type: voluptuous.Any(*tuple(type_schemas))
            }
        }) 
Example #10
Source File: xboxone.py    From hassio-addons with MIT License 6 votes vote down vote up
def _check_server(self):
        if not self.is_server_correct_version:
            return False

        try:
            resp = self.get('/versions').json()
            version = resp['versions']['xbox-smartglass-rest']
            if version != REQUIRED_SERVER_VERSION:
                self.is_server_correct_version = False
                _LOGGER.error("Invalid xbox-smartglass-rest version: %s. Required: %s",
                              version, REQUIRED_SERVER_VERSION)
        except requests.exceptions.RequestException:
            self.is_server_up = False
            return False

        self.is_server_up = True
        return True 
Example #11
Source File: config_flow.py    From Anniversaries with MIT License 5 votes vote down vote up
def _show_user_form(self, user_input):
        name = ""
        date = ""
        one_time = DEFAULT_ONE_TIME
        half_anniversary = DEFAULT_HALF_ANNIVERSARY
        date_format = DEFAULT_DATE_FORMAT
        unit_of_measurement = DEFAULT_UNIT_OF_MEASUREMENT
        id_prefix = DEFAULT_ID_PREFIX
        if user_input is not None:
            if CONF_NAME in user_input:
                name = user_input[CONF_NAME]
            if CONF_DATE in user_input:
                date = user_input[CONF_DATE]
            if CONF_ONE_TIME in user_input:
                one_time = user_input[CONF_ONE_TIME]
            if CONF_HALF_ANNIVERSARY in user_input:
                half_anniversary = user_input[CONF_HALF_ANNIVERSARY]
            if CONF_DATE_FORMAT in user_input:
                date_format = user_input[CONF_DATE_FORMAT]
            if CONF_UNIT_OF_MEASUREMENT in user_input:
                unit_of_measurement = user_input[CONF_UNIT_OF_MEASUREMENT]
            if CONF_ID_PREFIX in user_input:
                id_prefix = user_input[CONF_ID_PREFIX]
        data_schema = OrderedDict()
        data_schema[vol.Required(CONF_NAME, default=name)] = str
        data_schema[vol.Required(CONF_DATE, default=date)] = str
        data_schema[vol.Required(CONF_ONE_TIME, default=one_time)] = bool
        data_schema[vol.Required(CONF_HALF_ANNIVERSARY, default=half_anniversary)] = bool
        data_schema[vol.Required(CONF_DATE_FORMAT, default=date_format)] = str
        data_schema[vol.Required(CONF_UNIT_OF_MEASUREMENT, default=unit_of_measurement)] = str
        data_schema[vol.Optional(CONF_ID_PREFIX, default=id_prefix)] = str
        return self.async_show_form(step_id="user", data_schema=vol.Schema(data_schema), errors=self._errors) 
Example #12
Source File: config_schema.py    From climate.programmable_thermostat with The Unlicense 5 votes vote down vote up
def get_config_flow_schema(config: dict = {}, config_flow_step: int = 0) -> dict:
    if not config:
        config = {
            CONF_NAME: DEFAULT_NAME,
            CONF_HEATER: "",
            CONF_COOLER: "",
            CONF_SENSOR: "",
            CONF_TARGET: "",
            CONF_MAX_TEMP: DEFAULT_MAX_TEMP,
            CONF_MIN_TEMP: DEFAULT_MIN_TEMP,
            CONF_TOLERANCE: DEFAULT_TOLERANCE,
            CONF_RELATED_CLIMATE: "",
            CONF_HVAC_OPTIONS: DEFAULT_HVAC_OPTIONS,
            CONF_AUTO_MODE: DEFAULT_AUTO_MODE,
            CONF_INITIAL_HVAC_MODE: ""
        }
    if config_flow_step==1:
        return {
            vol.Optional(CONF_NAME, default=config.get(CONF_NAME)): str,
            vol.Optional(CONF_HEATER, default=config.get(CONF_HEATER)): str,
            vol.Optional(CONF_COOLER, default=config.get(CONF_COOLER)): str,
            vol.Required(CONF_SENSOR, default=config.get(CONF_SENSOR)): str,
            vol.Required(CONF_TARGET, default=config.get(CONF_TARGET)): str
        }
    elif config_flow_step==2:
        return {
            vol.Optional(CONF_MAX_TEMP, default=config.get(CONF_MAX_TEMP)): int,
            vol.Optional(CONF_MIN_TEMP, default=config.get(CONF_MIN_TEMP)): int,
            vol.Optional(CONF_TOLERANCE, default=config.get(CONF_TOLERANCE)): float
        }
    elif config_flow_step==3:
        return {
            vol.Optional(CONF_RELATED_CLIMATE, default=config.get(CONF_RELATED_CLIMATE)): str,
            vol.Optional(CONF_HVAC_OPTIONS, default=config.get(CONF_HVAC_OPTIONS)):  vol.In(range(MAX_HVAC_OPTIONS)),
            vol.Optional(CONF_AUTO_MODE, default=config.get(CONF_AUTO_MODE)): vol.In(AUTO_MODE_OPTIONS),
            vol.Optional(CONF_INITIAL_HVAC_MODE, default=config.get(CONF_INITIAL_HVAC_MODE)): vol.In(INITIAL_HVAC_MODE_OPTIONS)
        }

    return {} 
Example #13
Source File: test_voluptuous.py    From pydantic with MIT License 5 votes vote down vote up
def __init__(self, allow_extra):
        self.schema = v.Schema(
            {
                v.Required('id'): int,
                v.Required('client_name'): v.All(str, v.Length(max=255)),
                v.Required('sort_index'): float,
                # v.Optional('client_email'): v.Maybe(v.Email),
                v.Optional('client_phone'): v.Maybe(v.All(str, v.Length(max=255))),
                v.Optional('location'): v.Maybe(
                    v.Schema(
                        {
                            'latitude': v.Maybe(float),
                            'longitude': v.Maybe(float)
                        },
                        required=True
                    )
                ),
                v.Optional('contractor'): v.Maybe(v.All(v.Coerce(int), v.Range(min=1))),
                v.Optional('upstream_http_referrer'): v.Maybe(v.All(str, v.Length(max=1023))),
                v.Required('grecaptcha_response'): v.All(str, v.Length(min=20, max=1000)),
                v.Optional('last_updated'): v.Maybe(parse_datetime),
                v.Required('skills', default=[]): [
                    v.Schema(
                        {
                            v.Required('subject'): str,
                            v.Required('subject_id'): int,
                            v.Required('category'): str,
                            v.Required('qual_level'): str,
                            v.Required('qual_level_id'): int,
                            v.Required('qual_level_ranking', default=0): float,
                        }
                    )
                ],
            },
            extra=allow_extra,
        ) 
Example #14
Source File: config_flow.py    From blueprint with MIT License 5 votes vote down vote up
def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        if user_input is not None:
            self.options.update(user_input)
            return await self._update_options()

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(x, default=self.options.get(x, True)): bool
                    for x in sorted(PLATFORMS)
                }
            ),
        ) 
Example #15
Source File: config_flow.py    From blueprint with MIT License 5 votes vote down vote up
def _show_config_form(self, user_input):  # pylint: disable=unused-argument
        """Show the configuration form to edit location data."""
        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
            ),
            errors=self._errors,
        ) 
Example #16
Source File: config_flow.py    From havcs with Apache License 2.0 5 votes vote down vote up
def async_step_clear(self, user_input=None):
        errors = {}
        if user_input is not None:
            if user_input.get('comfirm'):
                for entry in self._user_entries:
                    await self.hass.async_create_task(self.hass.config_entries.async_remove(entry.entry_id))
                return self.async_abort(reason='clear_finish')
            else:
                return self.async_abort(reason='clear_cancel')
        else:
            user_input = {}
        fields = OrderedDict()
        fields[vol.Required('comfirm', default = user_input.get('comfirm', False))] = bool
        return self.async_show_form(
            step_id='clear', data_schema=vol.Schema(fields), errors=errors) 
Example #17
Source File: configuration_schema.py    From SmartHouse with MIT License 5 votes vote down vote up
def hacs_base_config_schema(config: dict = {}, config_flow: bool = False) -> dict:
    """Return a shcema configuration dict for HACS."""
    if not config:
        config = {
            TOKEN: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
            SIDEPANEL_ICON: "mdi:alpha-c-box",
            SIDEPANEL_TITLE: "HACS",
            APPDAEMON: False,
            NETDAEMON: False,
            PYTHON_SCRIPT: False,
            THEME: False,
        }
    if config_flow:
        return {
            vol.Required(TOKEN, default=config.get(TOKEN)): str,
            vol.Optional(SIDEPANEL_TITLE, default=config.get(SIDEPANEL_TITLE)): str,
            vol.Optional(SIDEPANEL_ICON, default=config.get(SIDEPANEL_ICON)): str,
            vol.Optional(APPDAEMON, default=config.get(APPDAEMON)): bool,
            vol.Optional(NETDAEMON, default=config.get(NETDAEMON)): bool,
        }
    return {
        vol.Required(TOKEN, default=config.get(TOKEN)): str,
        vol.Optional(SIDEPANEL_TITLE, default=config.get(SIDEPANEL_TITLE)): str,
        vol.Optional(SIDEPANEL_ICON, default=config.get(SIDEPANEL_ICON)): str,
        vol.Optional(APPDAEMON, default=config.get(APPDAEMON)): bool,
        vol.Optional(NETDAEMON, default=config.get(NETDAEMON)): bool,
        vol.Optional(PYTHON_SCRIPT, default=config.get(PYTHON_SCRIPT)): bool,
        vol.Optional(THEME, default=config.get(THEME)): bool,
    } 
Example #18
Source File: config_flow.py    From SmartHouse with MIT License 5 votes vote down vote up
def _show_config_form(self, user_input):
        """Show the configuration form to edit location data."""

        # Defaults
        url = ""
        api_key = ""
        port = DEFAULT_PORT_NUMBER
        verify_ssl = True

        if user_input is not None:
            if "url" in user_input:
                url = user_input["url"]
            if "api_key" in user_input:
                api_key = user_input["api_key"]
            if "port" in user_input:
                port = user_input["port"]
            if "verify_ssl" in user_input:
                verify_ssl = user_input["verify_ssl"]

        data_schema = OrderedDict()
        data_schema[vol.Required("url", default=url)] = str
        data_schema[vol.Required("api_key", default=api_key)] = str
        data_schema[vol.Optional("port", default=port)] = int
        data_schema[vol.Optional("verify_ssl", default=verify_ssl)] = bool
        return self.async_show_form(
            step_id="user", data_schema=vol.Schema(data_schema), errors=self._errors
        ) 
Example #19
Source File: config_flow.py    From Anniversaries with MIT License 5 votes vote down vote up
def _show_icon_form(self, user_input):
        data_schema = OrderedDict()
        data_schema[vol.Required(CONF_ICON_NORMAL,default=self.config_entry.options.get(CONF_ICON_NORMAL),)] = str
        data_schema[vol.Required(CONF_ICON_TODAY,default=self.config_entry.options.get(CONF_ICON_TODAY),)] = str
        data_schema[vol.Required(CONF_SOON,default=self.config_entry.options.get(CONF_SOON),)] = int
        data_schema[vol.Required(CONF_ICON_SOON,default=self.config_entry.options.get(CONF_ICON_SOON),)] = str
        return self.async_show_form(step_id="icons", data_schema=vol.Schema(data_schema), errors=self._errors) 
Example #20
Source File: utils.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def add_output_schema(schema):
    """Add a voluptuous schema validation on a method's output

    Example usage::

       class Example(base.BaseResource):

           @api_utils.add_output_schema({
               voluptuous.Required(
                   'message',
                   default='This is an example endpoint',
               ): validation_utils.get_string_type(),
           })
           def get(self):
               return {}

    :param schema: Schema to apply to the method's output
    :type schema: dict
    """
    schema = voluptuous.Schema(schema)

    def decorator(f):
        def wrap(*args, **kwargs):
            resp = f(*args, **kwargs)
            return schema(resp)
        return wrap
    return decorator 
Example #21
Source File: utils.py    From cloudkitty with Apache License 2.0 5 votes vote down vote up
def paginated(func):
    """Helper function for pagination.

    Adds two parameters to the decorated function:
    * ``offset``: int >=0. Defaults to 0.
    * ``limit``: int >=1. Defaults to 100.

    Example usage::

       class Example(base.BaseResource):

           @api_utils.paginated
           @api_utils.add_output_schema({
               voluptuous.Required(
                   'message',
                   default='This is an example endpoint',
               ): validation_utils.get_string_type(),
           })
           def get(self, offset=0, limit=100):
               # [...]
    """
    return add_input_schema('query', {
        voluptuous.Required('offset', default=0): voluptuous.All(
            SingleQueryParam(int), voluptuous.Range(min=0)),
        voluptuous.Required('limit', default=100): voluptuous.All(
            SingleQueryParam(int), voluptuous.Range(min=1)),
    })(func) 
Example #22
Source File: _importer.py    From tcconfig with MIT License 5 votes vote down vote up
def load_tcconfig(self, config_file_path):
        from voluptuous import Schema, Required, Any, ALLOW_EXTRA

        schema = Schema(
            {Required(str): {Any(*TrafficDirection.LIST): {str: {str: Any(str, int, float)}}}},
            extra=ALLOW_EXTRA,
        )

        with open(config_file_path, encoding="utf-8") as fp:
            self.__config_table = json.load(fp)

        schema(self.__config_table)
        self.__logger.debug(
            "tc config file: {:s}".format(json.dumps(self.__config_table, indent=4))
        ) 
Example #23
Source File: create_schema.py    From visonic with Apache License 2.0 5 votes vote down vote up
def create_parameters1cv(options):
    # Panel settings - can only be set on creation
    return {
        vol.Required(CONF_LANGUAGE,         default=create_default(options, CONF_LANGUAGE, "EN") )         : cv.string,
        vol.Optional(CONF_EXCLUDE_SENSOR,   default=create_default(options, CONF_EXCLUDE_SENSOR, ""))      : cv.string,
        vol.Optional(CONF_EXCLUDE_X10,      default=create_default(options, CONF_EXCLUDE_X10, ""))         : cv.string,
        vol.Optional(CONF_DOWNLOAD_CODE,    default=create_default(options, CONF_DOWNLOAD_CODE, "") )      : cv.string,
        vol.Optional(CONF_FORCE_STANDARD,   default=create_default(options, CONF_FORCE_STANDARD, False))   : cv.boolean, 
        vol.Optional(CONF_FORCE_AUTOENROLL, default=create_default(options, CONF_FORCE_AUTOENROLL, False)) : cv.boolean, 
        vol.Optional(CONF_AUTO_SYNC_TIME,   default=create_default(options, CONF_AUTO_SYNC_TIME, True))    : cv.boolean
    } 
Example #24
Source File: configuration_schema.py    From integration with MIT License 5 votes vote down vote up
def hacs_base_config_schema(config: dict = {}) -> dict:
    """Return a shcema configuration dict for HACS."""
    if not config:
        config = {
            TOKEN: "xxxxxxxxxxxxxxxxxxxxxxxxxxx",
        }
    return {
        vol.Required(TOKEN, default=config.get(TOKEN)): str,
    } 
Example #25
Source File: config_flow.py    From pyduofern with GNU General Public License v2.0 5 votes vote down vote up
def async_step_user(self, user_input=None):
        errors = {}
        if user_input is not None:
            if len(user_input['code']) != 4:
                errors["base"] = "not_hex"
            else:
                try:
                    if hex(int(user_input['code'], 16)).lower() != "0x" + user_input['code'].lower():
                        errors["base"] = "not_hex"
                except ValueError:
                    errors["base"] = "not_hex"
            if not errors:
                return self.async_create_entry(
                    title='duofern', data=user_input
                )
        if os.path.isdir("/dev/serial/by-id"):
            serialdevs = set(os.listdir("/dev/serial/by-id/"))
        else:
            serialdevs=["could not find /dev/serial/by-id/, did you plug in your dufoern stick correctly?"]
        return self.async_show_form(
            step_id='user',
            data_schema=vol.Schema({
                vol.Required('code'): str,
                vol.Optional('serial_port',
                             default="/dev/serial/by-id/usb-Rademacher_DuoFern_USB-Stick_WR04ZFP4-if00-port0"): vol.In(serialdevs),
                vol.Optional('config_file', default=os.path.join(os.path.dirname(__file__), "../../duofern.json")): str
            }),
            errors=errors
        ) 
Example #26
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def patch(self):
        ArchivePolicyRuleSchema = voluptuous.Schema({
            voluptuous.Required("name"): six.text_type,
            })
        body = deserialize_and_validate(ArchivePolicyRuleSchema)
        enforce("update archive policy rule", {})
        try:
            return pecan.request.indexer.update_archive_policy_rule(
                self.archive_policy_rule.name, body["name"])
        except indexer.UnsupportedArchivePolicyRuleChange as e:
            abort(400, six.text_type(e)) 
Example #27
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def post(self):
        enforce("create archive policy", {})
        # NOTE(jd): Initialize this one at run-time because we rely on conf
        conf = pecan.request.conf
        valid_agg_methods = list(
            archive_policy.ArchivePolicy.VALID_AGGREGATION_METHODS_VALUES
        )
        ArchivePolicySchema = voluptuous.Schema({
            voluptuous.Required("name"): six.text_type,
            voluptuous.Required("back_window", default=0): voluptuous.All(
                voluptuous.Coerce(int),
                voluptuous.Range(min=0),
            ),
            voluptuous.Required(
                "aggregation_methods",
                default=list(conf.archive_policy.default_aggregation_methods)):
            valid_agg_methods,
            voluptuous.Required("definition"): ArchivePolicyDefinitionSchema,
        })

        body = deserialize_and_validate(ArchivePolicySchema)
        # Validate the data
        try:
            ap = archive_policy.ArchivePolicy.from_dict(body)
        except ValueError as e:
            abort(400, six.text_type(e))
        enforce("create archive policy", ap)
        try:
            ap = pecan.request.indexer.create_archive_policy(ap)
        except indexer.ArchivePolicyAlreadyExists as e:
            abort(409, six.text_type(e))

        location = "/archive_policy/" + ap.name
        set_resp_location_hdr(location)
        pecan.response.status = 201
        return ap 
Example #28
Source File: api.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def get_pagination_options(params, default):
    try:
        opts = voluptuous.Schema({
            voluptuous.Required(
                "limit", default=pecan.request.conf.api.max_limit):
            voluptuous.All(voluptuous.Coerce(int),
                           voluptuous.Range(min=1),
                           voluptuous.Clamp(
                               min=1, max=pecan.request.conf.api.max_limit)),
            "marker": six.text_type,
            voluptuous.Required("sort", default=default):
            voluptuous.All(
                voluptuous.Coerce(arg_to_list),
                [six.text_type]),
        }, extra=voluptuous.REMOVE_EXTRA)(params)
    except voluptuous.Invalid as e:
        abort(400, {"cause": "Argument value error",
                    "reason": str(e)})
    opts['sorts'] = opts['sort']
    del opts['sort']
    return opts 
Example #29
Source File: resource_type.py    From gnocchi with Apache License 2.0 5 votes vote down vote up
def meta_schema(cls, for_update=False):
        d = {
            voluptuous.Required('type'): cls.typename,
            voluptuous.Required('required', default=True): bool
        }
        if for_update:
            d[voluptuous.Required('options', default={})] = OperationOptions
        if callable(cls.meta_schema_ext):
            d.update(cls.meta_schema_ext())
        else:
            d.update(cls.meta_schema_ext)
        return d 
Example #30
Source File: policy.py    From nmeta with Apache License 2.0 4 votes vote down vote up
def __init__(self, config, pol_dir_default=POL_DIR_DEFAULT,
                    pol_dir_user=POL_DIR_USER,
                    pol_filename=POL_FILENAME):
        """ Initialise the Policy Class """
        #*** Required for BaseClass:
        self.config = config
        #*** Set up Logging with inherited base class method:
        self.configure_logging(__name__, "policy_logging_level_s",
                                       "policy_logging_level_c")
        self.policy_dir_default = pol_dir_default
        self.policy_dir_user = pol_dir_user
        self.policy_filename = pol_filename
        #*** Get working directory:
        self.working_directory = os.path.dirname(__file__)
        #*** Build the full path and filename for the user policy file:
        self.fullpathname = os.path.join(self.working_directory,
                                         self.policy_dir_user,
                                         self.policy_filename)
        if os.path.isfile(self.fullpathname):
            self.logger.info("Opening user policy file=%s", self.fullpathname)
        else:
            self.logger.info("User policy file=%s not found",
                                                            self.fullpathname)
            self.fullpathname = os.path.join(self.working_directory,
                                         self.policy_dir_default,
                                         self.policy_filename)
            self.logger.info("Opening default policy file=%s",
                                                            self.fullpathname)
        #*** Ingest the policy file:
        try:
            with open(self.fullpathname, 'r') as filename:
                self.main_policy = yaml.safe_load(filename)
        except (IOError, OSError) as exception:
            self.logger.error("Failed to open policy "
                              "file=%s exception=%s",
                              self.fullpathname, exception)
            sys.exit("Exiting nmeta. Please create policy file")

        #*** Instantiate Classes:
        self.static = tc_static.StaticInspect(config, self)
        self.identity = tc_identity.IdentityInspect(config)
        self.custom = tc_custom.CustomInspect(config)

        #*** Check the correctness of the top level of main policy:
        validate(self.logger, self.main_policy, TOP_LEVEL_SCHEMA, 'top')

        #*** Instantiate classes for the second levels of policy:
        self.port_sets = PortSets(self)
        self.locations = Locations(self)
        self.tc_rules = TCRules(self)
        self.qos_treatment = QoSTreatment(self)

        #*** Instantiate any custom classifiers:
        self.custom.instantiate_classifiers(self.tc_rules.custom_classifiers)