code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def fw_hex_to_int(hex_str, words): return struct.unpack('<{}H'.format(words), binascii.unhexlify(hex_str))
Unpack hex string into integers. Use little-endian and unsigned int format. Specify number of words to unpack with argument words.
def fw_int_to_hex(*args): return binascii.hexlify( struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8')
Pack integers into hex string. Use little-endian and unsigned int format.
def compute_crc(data): crc16 = crcmod.predefined.Crc('modbus') crc16.update(data) return int(crc16.hexdigest(), 16)
Compute CRC16 of data and return an int.
def load_fw(path): fname = os.path.realpath(path) exists = os.path.isfile(fname) if not exists or not os.access(fname, os.R_OK): _LOGGER.error( 'Firmware path %s does not exist or is not readable', path) return None try: intel_hex = IntelHex() ...
Open firmware file and return a binary string.
def prepare_fw(bin_string): pads = len(bin_string) % 128 # 128 bytes per page for atmega328 for _ in range(128 - pads): # pad up to even 128 bytes bin_string += b'\xff' fware = { 'blocks': int(len(bin_string) / FIRMWARE_BLOCK_SIZE), 'crc': compute_crc(bin_string), 'dat...
Check that firmware is valid and return dict with binary data.
def _get_fw(self, msg, updates, req_fw_type=None, req_fw_ver=None): fw_type = None fw_ver = None if not isinstance(updates, tuple): updates = (updates, ) for store in updates: fw_id = store.pop(msg.node_id, None) if fw_id is not None: ...
Get firmware type, version and a dict holding binary data.
def respond_fw(self, msg): req_fw_type, req_fw_ver, req_blk = fw_hex_to_int(msg.payload, 3) _LOGGER.debug( 'Received firmware request with firmware type %s, ' 'firmware version %s, block index %s', req_fw_type, req_fw_ver, req_blk) fw_type, fw_ver, fw...
Respond to a firmware request.
def respond_fw_config(self, msg): (req_fw_type, req_fw_ver, req_blocks, req_crc, bloader_ver) = fw_hex_to_int(msg.payload, 5) _LOGGER.debug( 'Received firmware config request with firmware type %s, ' 'firmware version %s, %s blocks, CR...
Respond to a firmware config request.
def make_update(self, nids, fw_type, fw_ver, fw_bin=None): try: fw_type, fw_ver = int(fw_type), int(fw_ver) except ValueError: _LOGGER.error( 'Firmware type %s or version %s not valid, ' 'please enter integers', fw_type, fw_ver) ...
Start firmware update process for one or more node_id.
def handle_smartsleep(msg): while msg.gateway.sensors[msg.node_id].queue: msg.gateway.add_job( str, msg.gateway.sensors[msg.node_id].queue.popleft()) for child in msg.gateway.sensors[msg.node_id].children.values(): new_child = msg.gateway.sensors[msg.node_id].new_state.get( ...
Process a message before going back to smartsleep.
def handle_presentation(msg): if msg.child_id == SYSTEM_CHILD_ID: # this is a presentation of the sensor platform sensorid = msg.gateway.add_sensor(msg.node_id) if sensorid is None: return None msg.gateway.sensors[msg.node_id].type = msg.sub_type msg.gateway....
Process a presentation message.
def handle_set(msg): if not msg.gateway.is_sensor(msg.node_id, msg.child_id): return None msg.gateway.sensors[msg.node_id].set_child_value( msg.child_id, msg.sub_type, msg.payload) if msg.gateway.sensors[msg.node_id].new_state: msg.gateway.sensors[msg.node_id].set_child_value( ...
Process a set message.
def handle_req(msg): if not msg.gateway.is_sensor(msg.node_id, msg.child_id): return None value = msg.gateway.sensors[msg.node_id].children[ msg.child_id].values.get(msg.sub_type) if value is not None: return msg.copy( type=msg.gateway.const.MessageType.set, payload=...
Process a req message. This will return the value if it exists. If no value exists, nothing is returned.
def handle_internal(msg): internal = msg.gateway.const.Internal(msg.sub_type) handler = internal.get_handler(msg.gateway.handlers) if handler is None: return None return handler(msg)
Process an internal message.
def handle_stream(msg): if not msg.gateway.is_sensor(msg.node_id): return None stream = msg.gateway.const.Stream(msg.sub_type) handler = stream.get_handler(msg.gateway.handlers) if handler is None: return None return handler(msg)
Process a stream type message.
def handle_id_request(msg): node_id = msg.gateway.add_sensor() return msg.copy( ack=0, sub_type=msg.gateway.const.Internal['I_ID_RESPONSE'], payload=node_id) if node_id is not None else None
Process an internal id request message.
def handle_time(msg): return msg.copy(ack=0, payload=calendar.timegm(time.localtime()))
Process an internal time request message.
def handle_battery_level(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].battery_level = msg.payload msg.gateway.alert(msg) return None
Process an internal battery level message.
def handle_sketch_name(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].sketch_name = msg.payload msg.gateway.alert(msg) return None
Process an internal sketch name message.
def handle_sketch_version(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].sketch_version = msg.payload msg.gateway.alert(msg) return None
Process an internal sketch version message.
def handle_log_message(msg): # pylint: disable=useless-return msg.gateway.can_log = True _LOGGER.debug( 'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type, msg.sub_type, msg.payload) return None
Process an internal log message.
def handle_gateway_ready(msg): # pylint: disable=useless-return _LOGGER.info( 'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type, msg.sub_type, msg.payload) msg.gateway.alert(msg) return None
Process an internal gateway ready message.
def handle_gateway_ready_20(msg): _LOGGER.info( 'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type, msg.sub_type, msg.payload) msg.gateway.alert(msg) return msg.copy( node_id=255, ack=0, sub_type=msg.gateway.const.Internal.I_DISCOVER, payload='')
Process an internal gateway ready message.
def handle_heartbeat_response(msg): if not msg.gateway.is_sensor(msg.node_id): return None handle_smartsleep(msg) msg.gateway.sensors[msg.node_id].heartbeat = msg.payload msg.gateway.alert(msg) return None
Process an internal heartbeat response message.
def handle_heartbeat_response_22(msg): if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].heartbeat = msg.payload msg.gateway.alert(msg) return None
Process an internal heartbeat response message.
def publish(self, topic, payload, qos, retain): self._mqttc.publish(topic, payload, qos, retain)
Publish an MQTT message.
def subscribe(self, topic, callback, qos): if topic in self.topics: return def _message_callback(mqttc, userdata, msg): """Callback added to callback list for received message.""" callback(msg.topic, msg.payload.decode('utf-8'), msg.qos) self._mqttc...
Subscribe to an MQTT topic.
def get_gateway_id(self): info = next(serial.tools.list_ports.grep(self.port), None) return info.serial_number if info is not None else None
Return a unique id for the gateway.
def _connect(self): while self.protocol: _LOGGER.info('Trying to connect to %s', self.port) try: ser = serial.serial_for_url( self.port, self.baud, timeout=self.timeout) except serial.SerialException: _LOGGER.error(...
Connect to the serial port. This should be run in a new thread.
def _connect(self): try: while True: _LOGGER.info('Trying to connect to %s', self.port) try: yield from serial_asyncio.create_serial_connection( self.loop, lambda: self.protocol, self.port, self.baud) ...
Connect to the serial port.
def is_version(value): try: value = str(value) if not parse_ver('1.4') <= parse_ver(value): raise ValueError() return value except (AttributeError, TypeError, ValueError): raise vol.Invalid( '{} is not a valid version specifier'.format(value))
Validate that value is a valid version string.
def is_battery_level(value): try: value = percent_int(value) return value except vol.Invalid: _LOGGER.warning( '%s is not a valid battery level, falling back to battery level 0', value) return 0
Validate that value is a valid battery level integer.
def is_heartbeat(value): try: value = vol.Coerce(int)(value) return value except vol.Invalid: _LOGGER.warning( '%s is not a valid heartbeat value, falling back to heartbeat 0', value) return 0
Validate that value is a valid heartbeat integer.
def mksalt(method=None, rounds=None): if method is None: method = methods[0] salt = ['${0}$'.format(method.ident) if method.ident else ''] if rounds: salt.append('rounds={0:d}$'.format(rounds)) salt.append(''.join(_sr.choice(_BASE64_CHARACTERS) for char in range(method.salt_chars)))...
Generate a salt for the specified method. If not specified, the strongest available method will be used.
def crypt(word, salt=None, rounds=_ROUNDS_DEFAULT): if salt is None or isinstance(salt, _Method): salt = mksalt(salt, rounds) algo, rounds, salt = extract_components_from_salt(salt) if algo == 5: hashfunc = hashlib.sha256 elif algo == 6: hashfunc = hashlib.sha512 else: ...
Return a string representing the one-way hash of a password, with a salt prepended. If ``salt`` is not specified or is ``None``, the strongest available method will be selected and a salt generated. Otherwise, ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as returned by ``crypt....
def double_prompt_for_plaintext_password(): password = 1 password_repeat = 2 while password != password_repeat: password = getpass.getpass('Enter password: ') password_repeat = getpass.getpass('Repeat password: ') if password != password_repeat: sys.stderr.write('Pas...
Get the desired password from the user through a double prompt.
def logic(self, data): try: msg = Message(data, self) msg.validate(self.protocol_version) except (ValueError, vol.Invalid) as exc: _LOGGER.warning('Not a valid message: %s', exc) return None message_type = self.const.MessageType(msg.type)...
Parse the data and respond to it appropriately. Response is returned to the caller and has to be sent data as a mysensors command string.
def alert(self, msg): if self.event_callback is not None: try: self.event_callback(msg) except Exception as exception: # pylint: disable=broad-except _LOGGER.exception(exception) if self.persistence: self.persistence.need_sav...
Tell anyone who wants to know that a sensor was updated.
def _get_next_id(self): if self.sensors: next_id = max(self.sensors.keys()) + 1 else: next_id = 1 if next_id <= self.const.MAX_NODE_ID: return next_id return None
Return the next available sensor id.
def add_sensor(self, sensorid=None): if sensorid is None: sensorid = self._get_next_id() if sensorid is not None and sensorid not in self.sensors: self.sensors[sensorid] = Sensor(sensorid) return sensorid if sensorid in self.sensors else None
Add a sensor to the gateway.
def is_sensor(self, sensorid, child_id=None): ret = sensorid in self.sensors if not ret: _LOGGER.warning('Node %s is unknown', sensorid) if ret and child_id is not None: ret = child_id in self.sensors[sensorid].children if not ret: _LO...
Return True if a sensor and its child exist.
def run_job(self, job=None): if job is None: if not self.queue: return None job = self.queue.popleft() start = timer() func, args = job reply = func(*args) end = timer() if end - start > 0.1: _LOGGER.debug( ...
Run a job, either passed in or from the queue. A job is a tuple of function and optional args. Keyword arguments can be passed via use of functools.partial. The job should return a string that should be sent by the gateway protocol. The function will be called with the arguments and the...
def set_child_value( self, sensor_id, child_id, value_type, value, **kwargs): if not self.is_sensor(sensor_id, child_id): return if self.sensors[sensor_id].new_state: self.sensors[sensor_id].set_child_value( child_id, value_type, value, ...
Add a command to set a sensor value, to the queue. A queued command will be sent to the sensor when the gateway thread has sent all previously queued commands. If the sensor attribute new_state returns True, the command will be buffered in a queue on the sensor, and only the internal s...
def start(self): connect_thread = threading.Thread(target=self._connect) connect_thread.start()
Start the connection to a transport.
def _poll_queue(self): while not self._stop_event.is_set(): reply = self.run_job() self.send(reply) if self.queue: continue time.sleep(0.02)
Poll the queue for work.
def _create_scheduler(self, save_sensors): def schedule_save(): """Save sensors and schedule a new save.""" save_sensors() scheduler = threading.Timer(10.0, schedule_save) scheduler.start() self._cancel_save = scheduler.cancel return s...
Return function to schedule saving sensors.
def start_persistence(self): if not self.persistence: return self.persistence.safe_load_sensors() self.persistence.schedule_save_sensors()
Load persistence file and schedule saving of persistence file.
def stop(self): self._stop_event.set() if not self.persistence: return if self._cancel_save is not None: self._cancel_save() self._cancel_save = None self.persistence.save_sensors()
Stop the background thread.
def update_fw(self, nids, fw_type, fw_ver, fw_path=None): fw_bin = None if fw_path: fw_bin = load_fw(fw_path) if not fw_bin: return self.ota.make_update(nids, fw_type, fw_ver, fw_bin)
Update firwmare of all node_ids in nids.
def _disconnect(self): if not self.protocol or not self.protocol.transport: self.protocol = None # Make sure protocol is None return _LOGGER.info('Disconnecting from gateway') self.protocol.transport.close() self.protocol = None
Disconnect from the transport.
def send(self, message): if not message or not self.protocol or not self.protocol.transport: return if not self.can_log: _LOGGER.debug('Sending %s', message.strip()) try: self.protocol.transport.write(message.encode()) except OSError as exc: ...
Write a message to the gateway.
def stop(self): _LOGGER.info('Stopping gateway') self._disconnect() if self.connect_task and not self.connect_task.cancelled(): self.connect_task.cancel() self.connect_task = None if not self.persistence: return if self._cancel_save is...
Stop the gateway.
def add_job(self, func, *args): job = func, args reply = self.run_job(job) self.send(reply)
Add a job that should return a reply to be sent. A job is a tuple of function and optional args. Keyword arguments can be passed via use of functools.partial. The job should return a string that should be sent by the gateway protocol. The async version of this method will send the repl...
def _create_scheduler(self, save_sensors): @asyncio.coroutine def schedule_save(): """Save sensors and schedule a new save.""" yield from self.loop.run_in_executor(None, save_sensors) callback = partial(self.loop.create_task, schedule_save()) task...
Return function to schedule saving sensors.
def start_persistence(self): if not self.persistence: return yield from self.loop.run_in_executor( None, self.persistence.safe_load_sensors) yield from self.persistence.schedule_save_sensors()
Load persistence file and schedule saving of persistence file.
def connection_made(self, transport): super().connection_made(transport) if hasattr(self.transport, 'serial'): _LOGGER.info('Connected to %s', self.transport.serial) else: _LOGGER.info('Connected to %s', self.transport)
Handle created connection.
def handle_line(self, line): if not self.gateway.can_log: _LOGGER.debug('Receiving %s', line) self.gateway.add_job(self.gateway.logic, line)
Handle incoming string data one line at a time.
def connection_lost(self, exc): _LOGGER.debug('Connection lost with %s', self.transport.serial) if exc: _LOGGER.error(exc) self.transport.serial.close() self.conn_lost_callback() self.transport = None
Handle lost connection.
def add_child_sensor(self, child_id, child_type, description=''): if child_id in self.children: _LOGGER.warning( 'child_id %s already exists in children of node %s, ' 'cannot add child', child_id, self.sensor_id) return None self.children[...
Create and add a child sensor.
def set_child_value(self, child_id, value_type, value, **kwargs): children = kwargs.get('children', self.children) if not isinstance(children, dict) or child_id not in children: return None msg_type = kwargs.get('msg_type', 1) ack = kwargs.get('ack', 0) msg =...
Set a child sensor's value.
def get_schema(self, protocol_version): const = get_const(protocol_version) custom_schema = vol.Schema({ typ.value: const.VALID_SETREQ[typ] for typ in const.VALID_TYPES[const.Presentation.S_CUSTOM]}) return custom_schema.extend({ typ.value: const.VALI...
Return the child schema for the correct const version.
def validate(self, protocol_version, values=None): if values is None: values = self.values return self.get_schema(protocol_version)(values)
Validate child value types and values against protocol_version.
def _get_shipped_from(row): try: spans = row.find('div', {'id': 'coltextR2'}).find_all('span') if len(spans) < 2: return None return spans[1].string except AttributeError: return None
Get where package was shipped from.
def _get_status_timestamp(row): try: divs = row.find('div', {'id': 'coltextR3'}).find_all('div') if len(divs) < 2: return None timestamp_string = divs[1].string except AttributeError: return None try: return parse(timestamp_string) except ValueErr...
Get latest package timestamp.
def _get_delivery_date(row): try: month = row.find('div', {'class': 'date-small'}).string day = row.find('div', {'class': 'date-num-large'}).string except AttributeError: return None try: return parse('{} {}'.format(month, day)).date() except ValueError: retu...
Get delivery date (estimated or actual).
def _get_driver(driver_type): if driver_type == 'phantomjs': return webdriver.PhantomJS(service_log_path=os.path.devnull) if driver_type == 'firefox': return webdriver.Firefox(firefox_options=FIREFOXOPTIONS) elif driver_type == 'chrome': chrome_options = webdriver.ChromeOptions(...
Get webdriver.
def _login(session): _LOGGER.debug("attempting login") session.cookies.clear() try: session.remove_expired_responses() except AttributeError: pass try: driver = _get_driver(session.auth.driver) except WebDriverException as exception: raise USPSError(str(excep...
Login. Use Selenium webdriver to login. USPS authenticates users in part by a key generated by complex, obfuscated client-side Javascript, which can't (easily) be replicated in Python. Invokes the webdriver once to perform login, then uses the resulting session cookies with a standard Python `reque...
def authenticated(function): def wrapped(*args): """Wrap function.""" try: return function(*args) except USPSError: _LOGGER.info("attempted to access page before login") _login(args[0]) return function(*args) return wrapped
Re-authenticate if session expired.
def get_profile(session): response = session.get(PROFILE_URL, allow_redirects=False) if response.status_code == 302: raise USPSError('expired session') parsed = BeautifulSoup(response.text, HTML_PARSER) profile = parsed.find('div', {'class': 'atg_store_myProfileInfo'}) data = {} for...
Get profile data.
def get_packages(session): _LOGGER.info("attempting to get package data") response = _get_dashboard(session) parsed = BeautifulSoup(response.text, HTML_PARSER) packages = [] for row in parsed.find_all('div', {'class': 'pack_row'}): packages.append({ 'tracking_number': _get_t...
Get package data.
def get_mail(session, date=None): _LOGGER.info("attempting to get mail data") if not date: date = datetime.datetime.now().date() response = _get_dashboard(session, date) parsed = BeautifulSoup(response.text, HTML_PARSER) mail = [] for row in parsed.find_all('div', {'class': 'mailpie...
Get mail data.
def get_session(username, password, cookie_path=COOKIE_PATH, cache=True, cache_expiry=300, cache_path=CACHE_PATH, driver='phantomjs'): class USPSAuth(AuthBase): # pylint: disable=too-few-public-methods """USPS authorization storage.""" def __init__(self, username, password, co...
Get session, existing or new.
def rc4(data, key): S, j, out = list(range(256)), 0, [] for i in range(256): j = (j + S[i] + ord(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] i = j = 0 for ch in data: i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] out.append(ch...
RC4 encryption and decryption method.
def verify_email_for_object(self, email, content_object, email_field_name='email'): confirmation_key = generate_random_token() try: confirmation = EmailConfirmation() confirmation.content_object = content_object confirmation.email_field_name = email_field_n...
Create an email confirmation for `content_object` and send a confirmation mail. The email will be directly saved to `content_object.email_field_name` when `is_primary` and `skip_verify` both are true.
def clean(self): EmailConfirmation.objects.filter(content_type=self.content_type, object_id=self.object_id, email_field_name=self.email_field_name).delete()
delete all confirmations for the same content_object and the same field
def render_paginate(request, template, objects, per_page, extra_context={}): paginator = Paginator(objects, per_page) page = request.GET.get('page', 1) get_params = '&'.join(['%s=%s' % (k, request.GET[k]) for k in request.GET if k != 'page']) try: page_number = i...
Paginated list of objects.
def values(self): report = {} for k, k_changes in self._changes.items(): if len(k_changes) == 1: report[k] = k_changes[0].new_value elif k_changes[0].old_value != k_changes[-1].new_value: report[k] = k_changes[-1].new_value return ...
Returns a mapping of items to their new values. The mapping includes only items whose value or raw string value has changed in the context.
def changes(self): report = {} for k, k_changes in self._changes.items(): if len(k_changes) == 1: report[k] = k_changes[0] else: first = k_changes[0] last = k_changes[-1] if first.old_value != last.new_value...
Returns a mapping of items to their effective change objects which include the old values and the new. The mapping includes only items whose value or raw string value has changed in the context.
def load(self, source, as_defaults=False): if isinstance(source, six.string_types): source = os.path.expanduser(source) with open(source, encoding='utf-8') as f: self._rw.load_config_from_file(self._config, f, as_defaults=as_defaults) elif isinstance(sou...
Load configuration values from the specified source. Args: source: as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
def loads(self, config_str, as_defaults=False): self._rw.load_config_from_string(self._config, config_str, as_defaults=as_defaults)
Load configuration values from the specified source string. Args: config_str: as_defaults (bool): if ``True``, contents of ``source`` will be treated as schema of configuration items.
def dump(self, destination, with_defaults=False): if isinstance(destination, six.string_types): with open(destination, 'w', encoding='utf-8') as f: self._rw.dump_config_to_file(self._config, f, with_defaults=with_defaults) else: self._rw.dump_config_to_fi...
Write configuration values to the specified destination. Args: destination: with_defaults (bool): if ``True``, values of items with no custom values will be included in the output if they have a default value set.
def dumps(self, with_defaults=False): return self._rw.dump_config_to_string(self._config, with_defaults=with_defaults)
Generate a string representing all the configuration values. Args: with_defaults (bool): if ``True``, values of items with no custom values will be included in the output if they have a default value set.
def _default_key_setter(self, name, subject): if is_config_item(subject): self.add_item(name, subject) elif is_config_section(subject): self.add_section(name, subject) else: raise TypeError( 'Section items can only be replaced with ite...
This method is used only when there is a custom key_setter set. Do not override this method.
def _set_key(self, key, value): if is_config_section(value): self.add_section(key, value) return if key not in self._tree or self.settings.key_setter is None: if is_config_item(value): self.add_item(key, value) return ...
This method must NOT be called from outside the Section class. Do not override this method.
def _get_by_key(self, key, handle_not_found=True): resolution = self._get_item_or_section(key, handle_not_found=handle_not_found) if self.settings.key_getter: return self.settings.key_getter(parent=self, subject=resolution) else: return resolution
This method must NOT be called from outside the Section class. Do not override this method.
def _get_item_or_section(self, key, handle_not_found=True): if isinstance(key, six.string_types): if self.settings.str_path_separator in key: return self._get_item_or_section(key.split(self.settings.str_path_separator)) if key.endswith('_') and keyword.iskeyword...
This method must NOT be called from outside the Section class. Do not override this method. If handle_not_found is set to False, hooks won't be called. This is needed when checking key existence -- the whole purpose of key existence checking is to avoid errors (and error handling).
def get_item(self, *key): item = self._get_item_or_section(key) if not item.is_item: raise RuntimeError('{} is a section, not an item'.format(key)) return item
The recommended way of retrieving an item by key when extending configmanager's behaviour. Attribute and dictionary key access is configurable and may not always return items (see PlainConfig for example), whereas this method will always return the corresponding Item as long as NOT_FOUND hook ca...
def get_section(self, *key): section = self._get_item_or_section(key) if not section.is_section: raise RuntimeError('{} is an item, not a section'.format(key)) return section
The recommended way of retrieving a section by key when extending configmanager's behaviour.
def add_item(self, alias, item): if not isinstance(alias, six.string_types): raise TypeError('Item name must be a string, got a {!r}'.format(type(alias))) item = copy.deepcopy(item) if item.name is not_set: item.name = alias if self.settings.str_path_sep...
Add a config item to this section.
def add_section(self, alias, section): if not isinstance(alias, six.string_types): raise TypeError('Section name must be a string, got a {!r}'.format(type(alias))) self._tree[alias] = section if self.settings.str_path_separator in alias: raise ValueError( ...
Add a sub-section to this section.
def _get_recursive_iterator(self, recursive=False): names_yielded = set() for obj_alias, obj in self._tree.items(): if obj.is_section: if obj.alias in names_yielded: continue names_yielded.add(obj.alias) yield (o...
Basic recursive iterator whose only purpose is to yield all items and sections in order, with their full paths as keys. Main challenge is to de-duplicate items and sections which have aliases. Do not add any new features to this iterator, instead build others that extend this o...
def iter_all(self, recursive=False, path=None, key='path'): if isinstance(key, six.string_types) or key is None: if key in _iter_emitters: emitter = _iter_emitters[key] else: raise ValueError('Invalid key {!r}'.format(key)) else: ...
Args: recursive: if ``True``, recurse into sub-sections path (tuple or string): optional path to limit iteration over. key: ``path`` (default), ``str_path``, ``name``, ``None``, or a function to calculate the key from ``(k, v)`` tuple. Returns: ...
def iter_sections(self, recursive=False, path=None, key='path'): for x in self.iter_all(recursive=recursive, path=path, key=key): if key is None: if x.is_section: yield x elif x[1].is_section: yield x
See :meth:`.iter_all` for standard iterator argument descriptions. Returns: iterator: iterator over ``(key, section)`` pairs of all sections in this section (and sub-sections if ``recursive=True``).
def reset(self): for _, item in self.iter_items(recursive=True): item.reset()
Recursively resets values of all items contained in this section and its subsections to their default values.
def is_default(self): for _, item in self.iter_items(recursive=True): if not item.is_default: return False return True
``True`` if values of all config items in this section and its subsections have their values equal to defaults or have no value set.
def dump_values(self, with_defaults=True, dict_cls=dict, flat=False): values = dict_cls() if flat: for str_path, item in self.iter_items(recursive=True, key='str_path'): if item.has_value: if with_defaults or not item.is_default: ...
Export values of all items contained in this section to a dictionary. Items with no values set (and no defaults set if ``with_defaults=True``) will be excluded. Returns: dict: A dictionary of key-value pairs, where for sections values are dictionaries of their contents.
def load_values(self, dictionary, as_defaults=False, flat=False): if flat: # Deflatten the dictionary and then pass on to the normal case. separator = self.settings.str_path_separator flat_dictionary = dictionary dictionary = collections.OrderedDict() ...
Import config values from a dictionary. When ``as_defaults`` is set to ``True``, the values imported will be set as defaults. This can be used to declare the sections and items of configuration. Values of sections and items in ``dictionary`` can be dictionaries as well as instan...
def create_section(self, *args, **kwargs): kwargs.setdefault('section', self) return self.settings.section_factory(*args, **kwargs)
Internal factory method used to create an instance of configuration section. Should only be used when extending or modifying configmanager's functionality. Under normal circumstances you should let configmanager create sections and items when parsing configuration schemas. Do not overr...
def get_path(self): if not self.alias: return () if self.section: return self.section.get_path() + (self.alias,) else: return self.alias,
Calculate section's path in configuration tree. Use this sparingly -- path is calculated by going up the configuration tree. For a large number of sections, it is more efficient to use iterators that return paths as keys. Path value is stable only once the configuration tree is complete...
def item_attribute(self, f=None, name=None): def decorator(func): attr_name = name or func.__name__ if attr_name.startswith('_'): raise RuntimeError('Invalid dynamic item attribute name -- should not start with an underscore') self.__item_attributes[a...
A decorator to register a dynamic item attribute provider. By default, uses function name for attribute name. Override that with ``name=``.