FritzConnection API#

fritzconnection is structured into subpackages:

fritzconnection --|-- cli
                  |-- core --|-- devices
                  |          |-- exceptions
                  |          |-- fritzconnection
                  |          |-- fritzhttp
                  |          |-- fritzmonitor
                  |          |-- logger
                  |          |-- processor
                  |          |-- soaper
                  |          |-- utils
                  |
                  |-- lib
                  |-- tests

The package cli implements the entry-points for command line usage, the tests are in the tests package and the library modules are in lib. The implementation of fritzconnection itself is structured in the core package.

Public API#

The public interface is provided by the FritzConnection class, the fritzmonitor- and the exceptions-module.

There are shortcuts to import FritzConnection and FritzMonitor:

from fritzconnection import FritzConnection
from fritzconnection import FritzMonitor

fritzconnection#

Module to communicate with the AVM Fritz!Box.

class fritzconnection.core.fritzconnection.FritzConnection(address: Optional[str] = None, port: Optional[int] = None, user: Optional[str] = None, password: Optional[str] = None, timeout: Optional[float] = None, use_tls: bool = False, use_cache: bool = False, verify_cache: bool = True, cache_directory: Optional[Union[str, Path]] = None, cache_format: Optional[str] = None, pool_connections: int = 10, pool_maxsize: int = 10)#

Main class to set up a connection to the Fritz!Box router. All parameters are optional. address should be the ip of a router, in case that are multiple Fritz!Box routers in a network, the ip must be given. Otherwise, it is undefined which router will respond. If user and password are not provided, the environment gets checked for FRITZ_USERNAME and FRITZ_PASSWORD settings and taken from there, if found.

Basic usage assuming user and password stored in the environment:

>>> fc = FritzConnection(address="192.168.178.1")
>>> fc.call_action("WANIPConn1", "ForceTermination", arguments={})

This will reconnect the router with the external network. arguments is not necessary here, but in case where arguments must be provided, this is done by arguments (see also the documentation for the call_action()` method`). The call_action() method is used for the TR-064 API and returns a dictionary with the results.

For accessing the http-interface (aka AHA-HTTP-Interface) of the router, FritzConnection provides the call_http() method (added in version 1.12). As arguments this method takes a required command (like getswitchlist) and optional parameters as described in the AVM documentation:

>>> fc.call_http("getswitchlist")

This method triggers a http response and returns a dictionary with three key-value pairs: the content-type, the encoding and the content itself. The values are all of type string. The content-type is typically “text/plain” or “text/xml”, the encoding, typically “utf-8”.

The method will raise a FritzAuthorizationError in case of missing credentials. In case of an unknown command or identifier a FritzHttpInterfaceError will get raised.

New in version 1.12.

The optional parameter timeout is a floating number in seconds limiting the time waiting for a router response. This is a global setting for the internal communication with the router. In case of a timeout a requests.ConnectTimeout exception gets raised.

New in version 1.1.

use_tls accepts a boolean for using encrypted communication with the Fritz!Box. Default is False.

New in version 1.2.

For some actions the Fritz!Box needs a password and since Fritz!OS 7.24 also requires a username, the previous default username is just valid for OS versions < 7.24. In case the username is not given and the system version is 7.24 or newer, FritzConnection uses the last logged-in username as default.

New in version 1.5.

For applications where the urllib3 default connection-pool size should get adapted, the arguments pool_connections and pool_maxsize can get set explicitly.

New in version 1.6.

The flag use_cache activates caching (default False). Caching can speed up instanciation significantly. The cached data are specific for the router ip, the router model and the installed FritzOS version. Multiple devices in the network can have separate cache-fies and can get used in parallel. By default the cache files are stored in the user home-directory in a .fritzconnection folder. To change this location use the parameter cache_directory providing a string or a pathlib.Path object. With cache_format two formats can specified for data serialization: json and pickle. These two values are available as constants FRITZ_CACHE_FORMAT_JSON and FRITZ_CACHE_FORMAT_PICKLE. Default is pickle. The flag verify_cache will enable cache verification (default is True). If set to False loading the api-data will be even faster, but the cache will not get renewed in case of FritzOS updates or a router change. All cache-settings can also configured in the environment: FRITZ_USECACHE (True|False), FRITZ_CACHEFORMAT (json|pickle) and FRITZ_CACHEDIRECTORY (a path).

New in version 1.10.

call_action(service_name: str, action_name: str, *, arguments: Optional[dict] = None, **kwargs) dict[str, Any]#

Executes the given action of the given service. Both parameters are required. Arguments are optional and can be provided as a dictionary given to ‘arguments’ or as separate keyword parameters. If ‘arguments’ is given additional keyword-parameters as further arguments are ignored.

The argument values can be of type str, int or bool. (Note: bool is provided since 1.3. In former versions booleans must be provided as numeric values: 1, 0).

If the service_name does not end with a number-character (like “1””), a “1” gets added by default. If the service_name ends with a colon and a number, the colon gets removed. So i.e. “WLANConfiguration” expands to “WLANConfiguration1” and “WLANConfiguration:2” converts to “WLANConfiguration2””. Invalid service names will raise a ServiceError and invalid action names will raise an ActionError.

The method returns a dictionary with argument-names as keys and the corresponding information as values. Numeric and boolean values are converted from strings to Python datatypes.

call_http(command: str, identifier: Optional[str] = None, **kwargs) dict[str, str]#

Excecutes the given command by means of the http-interface. This can be useful for homeautomation-task currently not provided by the TR-064 interface. The identifier represents the ain of a target-device. kwargs can hold additional parameters depending on the device.

The method returns a dictionary of strings with three items: the content-type, the encoding and the corresponding result (the content). The content-type is typically “text/plain” or “text/xml”, the encoding, typically “utf-8”.

The method will raise a FritzAuthorizationError in case of missing credentials. In case of an unknown command or identifier a FritzHttpInterfaceError will get raised.

Note: information and interactions with actors provided by TR-064 and the http-interface partly overlap. If response time is an issue, TR-064 should be preferred because at time of writing a call to call_action (the TR-064 interface) is about 5 to 6 times faster than calling call_http (the http-interface).

New in version 1.12.

property device_description: str#

Returns a string with the device description. This is a combination of the device model name and the installed software version.

property modelname: str#

Returns the modelname of the router.

static normalize_name(name: str) str#

Returns the normalized service name. E.g. WLANConfiguration and WLANConfiguration:1 will get converted to WLANConfiguration1.

reboot() None#

Reboot the system.

reconnect() None#

Terminate the connection and reconnects with a new ip.

property services: dict[str, fritzconnection.core.processor.Service]#

Dictionary of service instances. Keys are the service names.

static set_protocol(url: str, use_tls: bool) str#

Sets the protocol of the url according to the use_tls-flag and returns the modified url. Does not check whether the url given as parameter is correct.

property system_version: str#

Returns system version if known, otherwise None.

property updatecheck: dict#

Dictionary with information about the hard- and software version of the device according to “http://fritz.box/jason_boxinfo.xml”.

fritzmonitor#

Module to communicate with the AVM Fritz!Box service providing real time phone-call events.

To run fritzmonitor, the CallMonitor service of the box has to be activated. This can be done with any registered Phone by typing the following codes: activate: #96*5* deactivate: #96*4*

class fritzconnection.core.fritzmonitor.EventReporter(monitor_queue: Queue, block_on_filled_queue: bool = False)#

Takes a Queue and implements a buffer for line-separated data. If at least one line is in the buffer, the line gets put into the Queue for further processing elsewhere (by a routine reading the queue).

add(data: str) None#

Adds the given ‘data’ to the buffer. If the buffer holds at least one line (separated by newline-character), the line (or lines) are put into the ‘monitor_queue’ as events to be processed from a reader elsewhere.

class fritzconnection.core.fritzmonitor.FritzMonitor(address: str = '169.254.1.1', port: int = 1012, timeout: int = 10, encoding: str = 'utf-8')#

Monitor Fritz!Box events about started, finished, incoming and outgoing calls.

property has_monitor_thread: bool#

Returns True if a monitor-thread has been created. That should be the case after calling start() and before calling stop().

property is_alive: bool#

Returns True if there is a monitor-thread and the thread is running. Returns False otherwise.

start(queue_size: int = 256, block_on_filled_queue: bool = False, reconnect_delay: float = 60, reconnect_tries: float = 10, sock=None) Queue#

Start the monitor thread and return a Queue instance with the given size to report the call_monitor events. Events are of type string. Raises an OSError if the socket can not get connected in a given timeout. Raises a RuntimeError if start() get called a second time without calling stop() first. queue_size is the number of events the queue can store. If block_on_filled_queue is False the event will get discarded in case of no free block (default). On True the EventReporter will block until a slot is available. reconnect_delay defines the maximum time interval in seconds between reconnection tries, in case that a socket-connection gets lost. reconnect_tries defines the number of consecutive to reconnect a socket before giving up. sock is used for testing to inject a mock-socket.

stop() None#

Stop the current running monitor_thread.

exceptions#

Exceptions can get imported by:

from fritzconnection.core.exceptions import FritzServiceError
# or:
from fritzconnection.core.exceptions import *

The latter style is often discouraged because of possible namespace-pollution, less clarity about the origin of imported objects and potential name clashings. By using a * import fritzconnection will just import exceptions starting with Fritz in their names.

Exception Hierarchy:

FritzConnectionException
                |
                |--> ActionError --> FritzActionError
                |--> ServiceError --> FritzServiceError
                |
                |--> FritzAuthorizationError
                |
                |--> FritzResourceError
                |
                |--> FritzArgumentError
                |       |
                |       |--> FritzArgumentValueError
                |               |
                |               |--> FritzArgumentStringToShortError
                |               |--> FritzArgumentStringToLongError
                |               |--> FritzArgumentCharacterError
                |
                |--> FritzInternalError
                |       |
                |       |--> FritzActionFailedError
                |       |--> FritzOutOfMemoryError
                |
                |--> FritzSecurityError
                |
                |-->|--> FritzLookUpError
                |   |
KeyError -------+-->|
                |
                |
                |-->|--> FritzArrayIndexError
                    |
IndexError -------->|

Module defining fritzconnection specific exceptions.

exception fritzconnection.core.exceptions.FritzActionError#

Exception raised by calling non-existing actions.

exception fritzconnection.core.exceptions.FritzActionFailedError#

Exception raised by the box unable to execute the action properly. Inherits from the more generic FritzInternalError.

exception fritzconnection.core.exceptions.FritzArgumentCharacterError#

Exception raised by arguments with invalid characters. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentError#

Exception raised by invalid arguments.

exception fritzconnection.core.exceptions.FritzArgumentStringToLongError#

Exception raised by arguments with invalid string length for the string being to long. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentStringToShortError#

Exception raised by arguments with invalid string length for the string being to short. Inherits from the more generic FritzArgumentValueError.

exception fritzconnection.core.exceptions.FritzArgumentValueError#

Exception raised by arguments with invalid values. Inherits from the more generic FritzArgumentError.

exception fritzconnection.core.exceptions.FritzArrayIndexError#

Addressing an entry in an internal array by index failed. Inherits from IndexError. So IndexError can also be used for exception handling.

exception fritzconnection.core.exceptions.FritzAuthorizationError#

Authentication error. Not allowed to access the box at all.

exception fritzconnection.core.exceptions.FritzConnectionException#

Base Exception for communication errors with the Fritz!Box

exception fritzconnection.core.exceptions.FritzHttpInterfaceError#

Exception raised on calling the aha-interface and getting an response with a status-code other than 200.

exception fritzconnection.core.exceptions.FritzInternalError#

Exception raised by panic in the box.

exception fritzconnection.core.exceptions.FritzLookUpError#

Lookup for id or entry in existing internal array failed. Inherits from KeyError. So KeyError can also be used for exception handling.

exception fritzconnection.core.exceptions.FritzOutOfMemoryError#

Exception raised by memory shortage of the box. Inherits from the more generic FritzInternalError.

exception fritzconnection.core.exceptions.FritzResourceError#

Exception raised if a description file like an igddesc-file is not provided by the router. This Exception is used internally and logged, but not reraised for the user of the library.

exception fritzconnection.core.exceptions.FritzSecurityError#

Authorization error or wrong security context.

exception fritzconnection.core.exceptions.FritzServiceError#

Exception raised by calling non-existing services.

Legathy Exceptions:

exception fritzconnection.core.exceptions.ActionError#

Exception raised by calling non-existing actions. Legacy Exception. Use FritzActionError instead.

exception fritzconnection.core.exceptions.ServiceError#

Exception raised by calling non-existing services. Legacy Exception. Use FritzServiceError instead.

Internal API#

The following core-modules don’t provide a public interface (at least it makes no sense) and are used internally.

devices#

Implements the DeviceManager for physical and virtual devices. Every physical device (a router) has a set of virtual subdevices.

class fritzconnection.core.devices.DeviceManager(timeout=None, session=None)#

Knows all data about the device and the sub-devices, including the available services. Takes an optional timeout parameter to limit the time waiting for a router response. The optional parameter session is a reusable connection and can speed up the communication with the device. In case session is given, timeout will not get used.

add_description(source)#

Adds description data about the devices and the according services. ‘source’ is a string with the xml-data, like the content of an igddesc- or tr64desc-file.

deserialize(data)#

Fills the collections self.descriptions and self.services with the content provided by data (from a json-source).

load_service_descriptions(address, port)#

Triggers the load of the scpd files of the services, so they known their actions.

property modelname#

Take the root-device of the first description and return the according modelname. This is the name of the Fritz!Box itself. Will raise an IndexError if the method is called before descriptions are added.

scan()#

Scans all available services defined by the description files. Must get called after all xml-descriptions are added.

serialize()#

Returns a json-serializable list with Python-datastructures representing the known api of the device.

property system_info#

Returns a tuple with Hardwarecode, Major-, Minor-, Patch-Level, Buildnumber and Display-String, in this order. Return None if this information is not available.

property system_version#

Returns the system-version as string with minor- and patch-level. This corresponds to the OS version reported by the router web-interface. Returns None if no system information is available.

fritzhttp#

fritzhttp.py

Access the AVM Fritz!Box AHA-HTTP-Inferface

class fritzconnection.core.fritzhttp.FritzHttp(fc)#

Implementation for the AVM AHA-HTTP-Inferface.

The current implementation does not handle a blocktime timeout so far. This is because the communication is based on a fritzconnection-session and the proper credentials are already handled there.

There may be the side-effect that someone else messes up with the login of the human web-interface while this script is running. In this case the aha-interface login will not return a valid sid until blocktime runs out.

execute(command=None, identifier=None, **kwargs)#

Send the command and the optional identifier to the http-interface and returns a tuple with the content-type and the response-text as is. On error raises a FritzAuthorizationError if the error code was 403 otherwise raises a generic FritzConnectionException with the corresponding error-code.

The command is a string like ‘getswitchlist’ or ‘getbasicdevicestats’ according to the AVM AHA documentation.

The identifier is a string, representing a device-ain.

property homeauto_url#

The homeauto-url including protocol and configurable port.

property login_url#

The login-url including protocol and configurable port.

property remote_port#

Provides the configurable https port for the aha-interface as int.

logger#

Logging module for the fritzconnection library. By default fritzconnection will emit all messages with a log-level of INFO and higher (WARNING, ERROR, CRITICAL).

The fritzconnection logger, defined as fritzlogger, is an instance of the logging.Logger class from the stdlib and can get accessed by:

>>> from fritzconnection.core.logger import fritzlogger

This module provides the additional functions activate_local_debug_mode and reset (see below) to activate a debug mode, suppressing handler-propagation, and to reset the logger to the initial state. To activate debug logging for fritzconnection call:

>>> from fritzconnection.core.logger import activate_local_debug_mode
>>> activate_local_debug_mode(handler=logging.StreamHandler())

In this debug mode fritzconnection will additionally log the data transfered between the library and the router and suppress logging-propagation to the parent-handlers. Here the StreamHandler will send all data to stderr. Because this can be a lot of data a FileHandler may be a better choice:

>>> activate_local_debug_mode(handler=logging.FileHandler(<the_file>))

To deactivate this mode call reset():

>>> from fritzconnection.core.logger import reset
>>> reset()

Beside this you can do everything with fritzlogger as with the logging.Logger, because fritzlogger is an instance of the latter.

fritzconnection.core.logger.activate_local_debug_mode(handler=None, propagate=False)#

Activates all logging messages on debug level and don’t propagate to parent-handlers. If no handler is given the NullHandler will get set, avoiding a call of the lastResort-handler. If the given handler has no formatter, the fritzformatter gets set (which provides the logging.BASIC_FORMAT). If propagate is True, all debug information will also get sent to the parent-handlers. Keep in mind, that this can be a lot of data if the parent-handlers are enabled for debug-level records.

fritzconnection.core.logger.reset(keep_handlers=False, propagate=True)#

Resets the logger to the initial state, i.e. after calling activate_local_debug_mode. All handlers will be removed, except keep_handlers is set to True.

processor#

Module to parse and store the device description and the service data provided by xml and the scpd protocol based on xml. Names partly violate PEP8 representing node-names from xml description files.

class fritzconnection.core.processor.Action#

Every Action has a name and a list of arguments.

property arguments#

Returns the action-arguments as a dict. argument-names are the keys and the argument objects are the values. The dictionary gets cached.

deserialize(data)#

Deserialize the data back to an Action instance with a given name and defined Argument-instances.

serialize()#

Return a dictionary with json serializable data: the name of the instance and a list of the serialized argument-instances in self._arguments.

class fritzconnection.core.processor.ActionList(storage)#

Collection of actions of a service. The Action instances are stored in the Scpd.actions attribute.

class fritzconnection.core.processor.Argument#

An argument with name, direction and relatedStateVariable attributes.

class fritzconnection.core.processor.ArgumentList(storage)#

Collects the arguments for an action.

class fritzconnection.core.processor.Description(root)#

Root class for a given description information as the content from the files igddesc.xml or tr64desc.xml.

deserialize(data)#

Sets the instance attributes according to data.

serialize()#

Return serialized instance attributes as dictionary.

property services#

Returns dictionary with the known services as values and the according service-names as keys.

property system_buildnumber#

Returns the buildnumber or None. This information is only available by the ‘tr64desc.xml’ file.

property system_display#

Returns the system display-string or None. This information is only available by the ‘tr64desc.xml’ file.

property system_info#

Returns the systemVersion attributes as a tuple: (HW, Major, Minor, Patch, Buildnumber, Display). This information is only available by the ‘tr64desc.xml’ file.

property system_version#

Returns the system version of the Fritz!Box as a string like ‘7.10’ or None. This information is only available by the ‘tr64desc.xml’ file.

class fritzconnection.core.processor.Device#

Storage for devices attributes and device sub-nodes. Sub-nodes are the serviceList and the deviceList. The services provided by a device are collected in services. Sub-devices are collected in devices. All instance attributes are public for read only use.

deserialize(data)#

Loads the data into the instance attributes. This is the reverse-function for serialize. No return value.

serialize()#

Returns a dictionary with a subset of the instance attributes and a list of serialized services that can be transformed to json-format.

class fritzconnection.core.processor.DeviceList(storage)#

Collection of sub-devices of a device. The Device instances are stored in the device.devices attribute of the parent device.

class fritzconnection.core.processor.Host#

Host class providing every requested attribute

property attributes#

Provide all attributes of the instance as a dictionary with the attribute names as keys and the values converted to python datatypes.

class fritzconnection.core.processor.HostStorage(root)#

Storage class collection all Item-nodes describing the hosts. The Item-nodes are converted to _Host instances.

property hosts_attributes#

Provide a list of dictionaries with the attributes of all hosts. The list is sorted with the lowest Index number first.

class fritzconnection.core.processor.InstanceAttributeFactory(cls)#

Non data descriptor returning instances of ‘cls’ and registering these instances in the ‘_storage’ attribute of the calling instance.

class fritzconnection.core.processor.Scpd(root)#

Provides information about the Service Control Point Definitions for every Service. Every Service has one instance of this class for accessing the description of its own actions and the according parameters. Root class for processing the content of an scpd-file.

property actions#

Returns a dictionary with the actions from the actions-list. The action-names are the keys and the actions themselves are the values.

property state_variables#

Returns a dictionary with the state_variable name as keys and the StateVariable itself as value.

class fritzconnection.core.processor.Serializer#

Simple abstract Serializer base class. This class and should not get instanciated.

classmethod from_data(data)#

Return a new instance with attributes initialized from data.

static get_sorted_dict(dictionary)#

Takes a dictionary and returns another one with all keys in alphabetical order.

class fritzconnection.core.processor.Service#

Class describing a service.

property actions#

Returns all known actions of this service as a dictionary. Action names are keys, the action objects are the values. Caches the dictionary once retrieved from _scpd.

deserialize(data)#

Inverse method for serialize. Takes the data (a dictionary) and populates the instance attributes extracted by serialize.

load_scpd(address, port, timeout=None, session=None)#

Loads the scpd data

serialize()#

Serialize the service instance attributes. Returns a dictionary with data that can be converted to json.

property state_variables#

Returns all known stateVariables of this service as a dictionary. Names are keys, the stateVariables objects are the values. Caches the dictionary once retrieved from _scpd.

class fritzconnection.core.processor.ServiceList(storage)#

Collection of Service instances for a device. The service instances are stored in the device.services attribute.

class fritzconnection.core.processor.ServiceStateTable(storage)#

Collection of stateVariables.

class fritzconnection.core.processor.SpecVersion#

Specification version from the schema device or service information.

class fritzconnection.core.processor.StateVariable#

Represents a stateVariable with the attributes name, dataType, defaultValue, allowedValueList and allowedValueRange.

deserialize(data)#

Deserialize the data back to a former state of a StateVariable instance.

serialize()#

Returns a dictionary with json serializable attribute data.

class fritzconnection.core.processor.Storage(storage)#

Baseclass for classes working with InstanceAttributeFactory.

class fritzconnection.core.processor.SystemVersion#

Information about the Fritz!OS version of the Fritz!Box. Information is just provided by the ‘tr64desc.xml’ file.

property info#

Returns a tuple with all instance attributes ‘HW, Major, Minor, Patch, Buildnumber, Display’ in this order.

property version#

Returns system version as string like ‘7.10’ or None if system version is unknown.

class fritzconnection.core.processor.ValueRange#
class fritzconnection.core.processor.ValueSequencer(sequence_name)#

Data descriptor storing a value (assigned as attribute value) in a given sequence.

fritzconnection.core.processor.process_node(obj, root)#

Take an object and a root of nodes. The node.text of nodes with the same name as an instance-attribute of ‘obj’ are set as values for the corresponding instance-attribute. If the attribute is a callable, processing the node gets delegated to the callable (which in turn calls process_node).

fritzconnection.core.processor.processor(cls)#

Class decorator to add the functionality of calling ‘process_node’ on invoking an instance as a callable.

soaper#

Module handling the SOAP based communication with the router.

class fritzconnection.core.soaper.Soaper(address, port, user, password, timeout=None, session=None)#

Class making the soap on its own to communicate with the FritzBox. Instead of ham, spam and eggs, it’s hopelessly addicted to soap.

For accessing the Fritz!Box the parameters address for the router ip, port, user, password and session are required. (These parameters will get set by FritzConnection.)

execute(service, action_name, arguments)#

Builds the soap request and returns the response as dictionary. Numeric and boolean values are converted from strings to Python datatypes.

get_body(service, action_name, arguments)#

Returns the body by template substitution.

parse_response(response, service, action_name)#

Extracts all known parameters of the given action from the response and returns this as a dictionary with the out-parameter names as keys and the corresponding response as values. Will raise an ActionError on unknown action_name.

fritzconnection.core.soaper.boolean_convert(value)#

Converts a string like ‘1’ or ‘0’ to a boolean value. Raise ValueError if it is something else than ‘1’ or ‘0’, because this violates the data_type according to the AVM documentation.

fritzconnection.core.soaper.datetime_convert(value)#

Converts a string in ISO 8601 format to a datetime-object. Raise ValueError if value does not match ISO 8601.

fritzconnection.core.soaper.encode_boolean(value)#

Returns 1 or 0 if the value is True or False. None gets interpreted as False. Otherwise, the original value is returned.

fritzconnection.core.soaper.get_argument_value(root, argument_name)#

Takes an etree-root object, which is a parsed soap-response from the Fritz!Box, and an argument_name, which corresponds to a node-name in the element-tree hierarchy. Returns the text-attribute of the node as a string. Raise an AttributeError in case that a node is not found.

fritzconnection.core.soaper.get_converted_value(data_type, value)#

Try to convert the value from string to the given data_type. The data_type is used as key in the CONVERSION_TABLE dictionary. In case the data_type is unknown, the original value is returned.

fritzconnection.core.soaper.get_html_safe_value(value)#

Returns a xml encoded value if it’s an encodable value. value can be of any type. If it is a boolean or None it gets converted to the integer 1 or 0. If it is a string the characters in the set &<>’” are converted to html-safe sequences. Any other datatype gets returned as is.

fritzconnection.core.soaper.is_html_response(text)#

Returns a boolean whether the raw response text starts with an html-tag.

fritzconnection.core.soaper.preprocess_arguments(arguments)#

Takes a dictionary with arguments for a soap call and converts all values which are True, False or None to the according integers: 1, 0, 0. Returns a new dictionary with the processed values.

fritzconnection.core.soaper.raise_fritzconnection_error(response)#

Handles all responses with status codes other than 200. Will raise a FritzConnectionException with the error code and description if available. Can also raise a FritzAuthorizationError in case of 401 html-response status code.

fritzconnection.core.soaper.remove_html_tags(text)#

Returns the given string response_text with all tags removed.

fritzconnection.core.soaper.uuid_convert(value)#

Strips the leading ‘uuid:’ part from the string.

utils#

Common functions for other core-modules.

fritzconnection.core.utils.boolean_from_string(value)#

Takes a value as a string and converts it to a boolean or None. The string could be “true” or “false” in upper-, lower- and mixed-case. Also “on”, “off” and “0”, “1” are converted. If the value can not converted a ValueError gets raised. If the value does not support the .lower() method, an AttributeError gets raised.

fritzconnection.core.utils.get_bool_env(key, default=None)#

Return the value of the environment variable key converted to a boolean if it exists, or default if it doesn’t or can’t get converted to a boolean. keys convertable to a boolean are “true”, “on”, “1” and “false”, “off”, “0”.

fritzconnection.core.utils.get_boolean_from_string(value, default=None)#

Same as boolean_from_string but returns the default argument instead of raising an exception.

fritzconnection.core.utils.get_content_from(url, timeout=None, session=None)#

Returns text from a get-request for the given url. In case of a secure request (using TLS) the parameter verify is set to False, in order to disable certificate verifications. As the Fritz!Box creates a self-signed certificate for use in the LAN, encryption will work but verification will fail.

fritzconnection.core.utils.get_xml_root(source, timeout=None, session=None)#

Function to help migrate from lxml to the standard-library xml-package.

‘source’ must be a string and can be a xml-string, a uri or a file name. timeout is an optional parameter limiting the time waiting for a router response. In all cases this function returns a xml.etree.Element instance which is the root of the parsed tree.