python-syncthing¶
Python bindings to the Syncthing REST interface.
- Syncthing
- Syncthing REST Documentation
- Syncthing Forums
- Pypi (
syncthing
)
Reference¶
Module¶
-
exception
syncthing.
SyncthingError
[source]¶ Base Syncthing Exception class all non-assert errors will raise from.
-
class
syncthing.
ErrorEvent
(when, message)¶ tuple[datetime.datetime,str]: used to process error lists more easily, instead of by two-key dictionaries.
-
message
¶ Alias for field number 1
-
when
¶ Alias for field number 0
-
-
class
syncthing.
BaseAPI
(api_key, host='localhost', port=8384, timeout=10.0, is_https=False, ssl_cert_file=None)[source]¶ Placeholder for HTTP REST API URL prefix.
-
class
syncthing.
System
(api_key, host='localhost', port=8384, timeout=10.0, is_https=False, ssl_cert_file=None)[source]¶ HTTP REST endpoint for System calls.
-
add_discovery
(device, address)[source]¶ Add an entry to the discovery cache.
Parameters: Returns: None
-
browse
(path=None)[source]¶ Returns a list of directories matching the path given.
Parameters: path (str) – glob pattern. Returns: List[str]
-
config
()[source]¶ Returns the current configuration.
Returns: dict >>> s = _syncthing().system >>> config = s.config() >>> config ... {...} >>> 'version' in config and config['version'] >= 15 True >>> 'folders' in config True >>> 'devices' in config True
-
config_insync
()[source]¶ Returns whether the config is in sync, i.e. whether the running configuration is the same as that on disk.
Returns: bool
-
connections
()[source]¶ Returns the list of configured devices and some metadata associated with them. The list also contains the local device itself as not connected.
Returns: dict >>> s = _syncthing().system >>> connections = s.connections() >>> sorted([k for k in connections.keys()]) ['connections', 'total'] >>> isinstance(connections['connections'], dict) True >>> isinstance(connections['total'], dict) True
-
debug
()[source]¶ Returns the set of debug facilities and which of them are currently enabled.
Returns: dict >>> s = _syncthing().system >>> debug = s.debug() >>> debug ... {...} >>> len(debug.keys()) 2 >>> 'enabled' in debug and 'facilities' in debug True >>> isinstance(debug['enabled'], list) or debug['enabled'] is None True >>> isinstance(debug['facilities'], dict) True
-
disable_debug
(*on)[source]¶ Disables debugging for specified facilities.
Parameters: on (str) – debugging points to apply disable
.Returns: None
-
do_upgrade
()[source]¶ Perform an upgrade to the newest released version and restart. Does nothing if there is no newer version than currently running.
Returns: None
-
enable_debug
(*on)[source]¶ Enables debugging for specified facilities.
Parameters: on (str) – debugging points to apply enable
.Returns: None
-
errors
()[source]¶ Returns the list of recent errors.
Returns: of ErrorEvent
tuples.Return type: list
-
pause
(device)[source]¶ Pause the given device.
Parameters: device (str) – Device ID. Returns: with keys success
anderror
.Return type: dict
-
ping
(with_method='GET')[source]¶ Pings the Syncthing server.
Parameters: with_method (str) – uses a given HTTP method, options are GET
andPOST
.Returns: dict
-
reset_folder
(folder)[source]¶ Erase the database index from a given folder and restart Syncthing.
Parameters: folder (str) – Folder ID. Returns: None
-
resume
(device)[source]¶ Resume the given device.
Parameters: device (str) – Device ID. Returns: with keys success
anderror
.Return type: dict
-
set_config
(config, and_restart=False)[source]¶ Post the full contents of the configuration, in the same format as returned by
config()
. The configuration will be saved to disk and theconfigInSync
flag set toFalse
. Restart Syncthing to activate.
-
show_error
(message)[source]¶ Send an error message to the active client. The new error will be displayed on any active GUI clients.
Parameters: message (str) – Plain-text message to display. Returns: None >>> s = _syncthing() >>> s.system.show_error('my error msg') >>> s.system.errors()[0] ... ErrorEvent(when=datetime.datetime(...), message='"my error msg"') >>> s.system.clear_errors() >>> s.system.errors() []
-
-
class
syncthing.
Database
(api_key, host='localhost', port=8384, timeout=10.0, is_https=False, ssl_cert_file=None)[source]¶ HTTP REST endpoint for Database calls.
-
browse
(folder, levels=None, prefix=None)[source]¶ Returns the directory tree of the global model.
Directories are always JSON objects (map/dictionary), and files are always arrays of modification time and size. The first integer is the files modification time, and the second integer is the file size.
Parameters: Returns: dict
-
completion
(device, folder)[source]¶ Returns the completion percentage (0 to 100) for a given device and folder.
Parameters: - Returs:
- int
-
file
(folder, file_)[source]¶ Returns most data available about a given file, including version and availability.
Parameters: Returns: dict
-
ignores
(folder)[source]¶ Returns the content of the
.stignore
as the ignore field. A second field, expanded, provides a list of strings which represent globbing patterns described by gobwas/glob (based on standard wildcards) that match the patterns in.stignore
and all the includes.If appropriate these globs are prepended by the following modifiers:
!
to negate the glob,(?i)
to do case insensitive matching and(?d)
to enable removing of ignored files in an otherwise empty directory.- Args:
- folder
- Returns:
- dict
-
need
(folder, page=None, perpage=None)[source]¶ Returns lists of files which are needed by this device in order for it to become in sync.
- Args:
folder (str): page (int): If defined applies pagination accross the
collection of results.- perpage (int): If defined applies pagination across the
- collection of results.
- Returns:
- dict
-
override
(folder)[source]¶ Request override of a send-only folder.
Parameters: folder (str) – folder ID. Returns: dict
-
prio
(folder, file_)[source]¶ Moves the file to the top of the download queue.
Parameters: Returns: dict
-
scan
(folder, sub=None, next_=None)[source]¶ Request immediate rescan of a folder, or a specific path within a folder.
- Args:
folder (str): Folder ID. sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scanned for changes, otherwise only the given path children are scanned.- next_ (int): Delays Syncthing’s automated rescan interval for
- a given amount of seconds.
- Returns:
- str
-
-
class
syncthing.
Statistics
(api_key, host='localhost', port=8384, timeout=10.0, is_https=False, ssl_cert_file=None)[source]¶ HTTP REST endpoint for Statistic calls.
-
class
syncthing.
Syncthing
(api_key, host='localhost', port=8384, timeout=10.0, is_https=False, ssl_cert_file=None)[source]¶ Default interface for interacting with Syncthing server instance.
Parameters: -
stats
¶ instance of
Statistics
.
-
-
syncthing.
keys_to_datetime
(obj, *keys)[source]¶ Converts all the keys in an object to DateTime instances.
Parameters: Returns: obj
inplace.Return type: >>> keys_to_datetime(None) is None True >>> keys_to_datetime({}) {} >>> a = {} >>> id(keys_to_datetime(a)) == id(a) True >>> a = {'one': '2016-06-06T19:41:43.039284', 'two': '2016-06-06T19:41:43.039284'} >>> keys_to_datetime(a) == a True >>> keys_to_datetime(a, 'one')['one'] datetime.datetime(2016, 6, 6, 19, 41, 43, 39284) >>> keys_to_datetime(a, 'one')['two'] '2016-06-06T19:41:43.039284'
System Endpoints¶
-
class
syncthing.
System
[source] HTTP REST endpoint for System calls.
-
add_discovery
(device, address)[source] Add an entry to the discovery cache.
Parameters: Returns: None
-
browse
(path=None)[source] Returns a list of directories matching the path given.
Parameters: path (str) – glob pattern. Returns: List[str]
-
can_upgrade
()[source] Returns when there’s a newer version than the instance running.
Returns: bool
-
clear
()[source] Remove all recent errors.
Returns: None
-
config
()[source] Returns the current configuration.
Returns: dict >>> s = _syncthing().system >>> config = s.config() >>> config ... {...} >>> 'version' in config and config['version'] >= 15 True >>> 'folders' in config True >>> 'devices' in config True
-
config_insync
()[source] Returns whether the config is in sync, i.e. whether the running configuration is the same as that on disk.
Returns: bool
-
connections
()[source] Returns the list of configured devices and some metadata associated with them. The list also contains the local device itself as not connected.
Returns: dict >>> s = _syncthing().system >>> connections = s.connections() >>> sorted([k for k in connections.keys()]) ['connections', 'total'] >>> isinstance(connections['connections'], dict) True >>> isinstance(connections['total'], dict) True
-
debug
()[source] Returns the set of debug facilities and which of them are currently enabled.
Returns: dict >>> s = _syncthing().system >>> debug = s.debug() >>> debug ... {...} >>> len(debug.keys()) 2 >>> 'enabled' in debug and 'facilities' in debug True >>> isinstance(debug['enabled'], list) or debug['enabled'] is None True >>> isinstance(debug['facilities'], dict) True
-
disable_debug
(*on)[source] Disables debugging for specified facilities.
Parameters: on (str) – debugging points to apply disable
.Returns: None
-
discovery
()[source] Returns the contents of the local discovery cache.
Returns: dict
-
do_upgrade
()[source] Perform an upgrade to the newest released version and restart. Does nothing if there is no newer version than currently running.
Returns: None
-
enable_debug
(*on)[source] Enables debugging for specified facilities.
Parameters: on (str) – debugging points to apply enable
.Returns: None
-
errors
()[source] Returns the list of recent errors.
Returns: of ErrorEvent
tuples.Return type: list
-
log
()[source] Returns the list of recent log entries.
Returns: dict
-
pause
(device)[source] Pause the given device.
Parameters: device (str) – Device ID. Returns: with keys success
anderror
.Return type: dict
-
ping
(with_method='GET')[source] Pings the Syncthing server.
Parameters: with_method (str) – uses a given HTTP method, options are GET
andPOST
.Returns: dict
-
prefix
= '/rest/system/'¶
-
reset
()[source] Erase the current index database and restart Syncthing.
Returns: None
-
reset_folder
(folder)[source] Erase the database index from a given folder and restart Syncthing.
Parameters: folder (str) – Folder ID. Returns: None
-
restart
()[source] Immediately restart Syncthing.
Returns: None
-
resume
(device)[source] Resume the given device.
Parameters: device (str) – Device ID. Returns: with keys success
anderror
.Return type: dict
-
set_config
(config, and_restart=False)[source] Post the full contents of the configuration, in the same format as returned by
config()
. The configuration will be saved to disk and theconfigInSync
flag set toFalse
. Restart Syncthing to activate.
-
show_error
(message)[source] Send an error message to the active client. The new error will be displayed on any active GUI clients.
Parameters: message (str) – Plain-text message to display. Returns: None >>> s = _syncthing() >>> s.system.show_error('my error msg') >>> s.system.errors()[0] ... ErrorEvent(when=datetime.datetime(...), message='"my error msg"') >>> s.system.clear_errors() >>> s.system.errors() []
-
shutdown
()[source] Causes Syncthing to exit and not restart.
Returns: None
-
status
()[source] Returns information about current system status and resource usage.
Returns: dict
-
upgrade
()[source] Checks for a possible upgrade and returns an object describing the newest version and upgrade possibility.
Returns: dict
-
version
()[source] Returns the current Syncthing version information.
Returns: dict
-
Database Endpoints¶
-
class
syncthing.
Database
[source] HTTP REST endpoint for Database calls.
-
browse
(folder, levels=None, prefix=None)[source] Returns the directory tree of the global model.
Directories are always JSON objects (map/dictionary), and files are always arrays of modification time and size. The first integer is the files modification time, and the second integer is the file size.
Parameters: Returns: dict
-
completion
(device, folder)[source] Returns the completion percentage (0 to 100) for a given device and folder.
Parameters: - Returs:
- int
-
file
(folder, file_)[source] Returns most data available about a given file, including version and availability.
Parameters: Returns: dict
-
ignores
(folder)[source] Returns the content of the
.stignore
as the ignore field. A second field, expanded, provides a list of strings which represent globbing patterns described by gobwas/glob (based on standard wildcards) that match the patterns in.stignore
and all the includes.If appropriate these globs are prepended by the following modifiers:
!
to negate the glob,(?i)
to do case insensitive matching and(?d)
to enable removing of ignored files in an otherwise empty directory.- Args:
- folder
- Returns:
- dict
-
need
(folder, page=None, perpage=None)[source] Returns lists of files which are needed by this device in order for it to become in sync.
- Args:
folder (str): page (int): If defined applies pagination accross the
collection of results.- perpage (int): If defined applies pagination across the
- collection of results.
- Returns:
- dict
-
override
(folder)[source] Request override of a send-only folder.
Parameters: folder (str) – folder ID. Returns: dict
-
prefix
= '/rest/db/'¶
-
prio
(folder, file_)[source] Moves the file to the top of the download queue.
Parameters: Returns: dict
-
scan
(folder, sub=None, next_=None)[source] Request immediate rescan of a folder, or a specific path within a folder.
- Args:
folder (str): Folder ID. sub (str): Path relative to the folder root. If sub is omitted
the entire folder is scanned for changes, otherwise only the given path children are scanned.- next_ (int): Delays Syncthing’s automated rescan interval for
- a given amount of seconds.
- Returns:
- str
-
set_ignores
(folder, *patterns)[source] Applies
patterns
tofolder
’s.stignore
file.Parameters: Returns: dict
-
Events Endpoints¶
-
class
syncthing.
Events
[source]¶ HTTP REST endpoints for Event based calls.
Syncthing provides a simple long polling interface for exposing events from the core utility towards a GUI.
syncthing = Syncthing() event_stream = syncthing.events(limit=5) for event in event_stream: print(event) if event_stream.count > 10: event_stream.stop()
-
count
¶ The number of events that have been processed by this event stream.
Returns: int
-
disk_events
()[source]¶ Blocking generator of disk related events. Each event is represented as a
dict
with metadata.- Returns:
- generator[dict]
-
prefix
= '/rest/'¶
-
Statistic Endpoints¶
-
class
syncthing.
Statistics
[source] HTTP REST endpoint for Statistic calls.
-
device
()[source] Returns general statistics about devices.
Currently, only contains the time the device was last seen.
Returns: dict
-
folder
()[source] Returns general statistics about folders.
Currently contains the last scan time and the last synced file.
Returns: dict
-
prefix
= '/rest/stats/'¶
-
Misc. Endpoints¶
-
class
syncthing.
Misc
[source]¶ HTTP REST endpoint for Miscelaneous calls.
-
device_id
(id_)[source]¶ Verifies and formats a device ID. Accepts all currently valid formats (52 or 56 characters with or without separators, upper or lower case, with trivial substitutions). Takes one parameter, id, and returns either a valid device ID in modern format, or an error.
Parameters: id (str) – Raises: SyncthingError
– whenid_
is an invalid length.Returns: str
-
language
()[source]¶ Returns a list of canonicalized localization codes, as picked up from the Accept-Language header sent by the browser. By default, this API will return a single element that’s empty; however calling
Misc.get()
directly with lang you can set specific headers to get values back as intended.Returns: List[str] >>> s = _syncthing() >>> len(s.misc.language()) 1 >>> s.misc.language()[0] '' >>> s.misc.get('lang', headers={'Accept-Language': 'en-us'}) ['en-us']
-
prefix
= '/rest/svc/'¶
-
random_string
(length=32)[source]¶ Returns a strong random generated string (alphanumeric) of the specified length.
Parameters: length (int) – default 32
.Returns: str >>> s = _syncthing() >>> len(s.misc.random_string()) 32 >>> len(s.misc.random_string(32)) 32 >>> len(s.misc.random_string(1)) 1 >>> len(s.misc.random_string(0)) 32 >>> len(s.misc.random_string(None)) 32 >>> import string >>> all_letters = string.ascii_letters + string.digits >>> all([c in all_letters for c in s.misc.random_string(128)]) True >>> all([c in all_letters for c in s.misc.random_string(1024)]) True
-
Running Tests¶
The API doctests rely on the following function to run against your instance. None of the “breaking” calls will be tested. You must set the following environment variables otherwise all tests will fail.
def _syncthing(): KEY = os.getenv('SYNCTHING_API_KEY') HOST = os.getenv('SYNCTHING_HOST', '127.0.0.1') PORT = os.getenv('SYNCTHING_PORT', 8384) IS_HTTPS = bool(int(os.getenv('SYNCTHING_HTTPS', '0'))) SSL_CERT_FILE = os.getenv('SYNCTHING_CERT_FILE') return Syncthing(KEY, HOST, PORT, 10.0, IS_HTTPS, SSL_CERT_FILE)
License¶
The MIT License (MIT)
Copyright (c) 2015-2016 Blake VandeMerwe
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.