Skip to content

Commit

Permalink
Added write() method #33
Browse files Browse the repository at this point in the history
Closes #33
  • Loading branch information
nemesifier committed Dec 10, 2015
1 parent badf292 commit 6f8380d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
30 changes: 30 additions & 0 deletions docs/source/backends/openwrt.rst
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,36 @@ directly on the OpenWRT router where it can be finally "restored" with ``sysupg
Note that the restore command does not apply the configuration, to do this you have
to reload the services manually or reboot the router.

Write method
------------

.. automethod:: netjsonconfig.OpenWrt.write

Example:

.. code-block:: python
>>> import tarfile
>>> from netjsonconfig import OpenWrt
>>>
>>> o = OpenWrt({
... "interfaces": [
... {
... "name": "eth0",
... "type": "ethernet",
... "addresses": [
... {
... "proto": "dhcp",
... "family": "ipv4"
... }
... ]
... }
... ]
... })
>>> o.write('dhcp-router', path='/tmp/')
Will write the configuration archive in ``/tmp/dhcp-router.tar.gz``.

JSON method
-----------

Expand Down
17 changes: 17 additions & 0 deletions netjsonconfig/backends/openwrt/openwrt.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,23 @@ def generate(self):
byte_object.seek(0)
return byte_object

def write(self, name, path='./'):
"""
Like ``generate`` but writes to disk.
:param name: file name, the tar.gz extension will be added automatically
:param path: directory where the file will be written to, defaults to ``./``
:returns: closed file object
"""
byte_object = self.generate()
file_name = '{0}.tar.gz'.format(name)
if not path.endswith('/'):
path += '/'
f = open('{0}{1}'.format(path, file_name), 'wb')
f.write(byte_object.getvalue())
f.close()
return f

def _add_files(self, tar, timestamp):
"""
adds files specified in self.config['files']
Expand Down
12 changes: 12 additions & 0 deletions tests/openwrt/test_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,18 @@ def test_generate(self):
self.assertEqual(contents, expected)
tar.close()

def test_write(self):
o = OpenWrt({
"general": {
"hostname": "test"
}
})
o.write(name='test', path='/tmp')
tar = tarfile.open('/tmp/test.tar.gz', mode='r')
self.assertEqual(len(tar.getmembers()), 1)
tar.close()
os.remove('/tmp/test.tar.gz')

def test_templates_type_error(self):
config = {
"general": {
Expand Down

0 comments on commit 6f8380d

Please sign in to comment.