mirror of
https://github.com/socialwifi/RouterOS-api.git
synced 2025-08-31 15:19:25 +02:00
Update api_structure.py
This commit is contained in:
parent
d56f3d77b8
commit
d3ea42486f
1 changed files with 75 additions and 0 deletions
|
@ -1,4 +1,7 @@
|
|||
import collections
|
||||
import datetime
|
||||
import ipaddress
|
||||
import re
|
||||
|
||||
|
||||
class StringField(object):
|
||||
|
@ -26,4 +29,76 @@ class BooleanField:
|
|||
return bytes in (b'yes', b'true')
|
||||
|
||||
|
||||
class IntegerField:
|
||||
def get_mikrotik_value(self, number):
|
||||
return str(number).encode()
|
||||
|
||||
def get_python_value(self, bytes):
|
||||
return int(bytes.decode())
|
||||
|
||||
|
||||
class TimedeltaField:
|
||||
def get_mikrotik_value(self, timedelta):
|
||||
if timedelta is None:
|
||||
return b'none'
|
||||
else:
|
||||
seconds = int(timedelta.total_seconds())
|
||||
return '{}s'.format(seconds).encode()
|
||||
|
||||
def get_python_value(self, bytes):
|
||||
if bytes == b'none':
|
||||
return None
|
||||
else:
|
||||
return parse_mikrotik_timedelta(bytes.decode())
|
||||
|
||||
|
||||
def parse_mikrotik_timedelta(time_string):
|
||||
new_timedelta_format = (
|
||||
r'^((?P<weeks>\d+)w)?((?P<days>\d+)d)?'
|
||||
r'((?P<hours>\d+)h)?((?P<minutes>\d+)m)?((?P<seconds>\d+)s)?'
|
||||
r'((?P<milliseconds>\d+)ms)?$')
|
||||
old_timedelta_format = (
|
||||
r'^((?P<weeks>\d+)w)?((?P<days>\d+)d)?'
|
||||
r'(?P<hours>\d+):(?P<minutes>\d+):(?P<seconds>\d+)'
|
||||
r'(\.(?P<milliseconds>\d+))?$')
|
||||
|
||||
match = re.match(new_timedelta_format, time_string)
|
||||
if not match:
|
||||
match = re.match(old_timedelta_format, time_string)
|
||||
if match:
|
||||
groups = dict((k, int(v)) for k, v in match.groupdict('0').items())
|
||||
return datetime.timedelta(**groups)
|
||||
else:
|
||||
raise ValueError('{} does not match any mikrotik uptime format'
|
||||
.format(time_string))
|
||||
|
||||
|
||||
class IpNetworkField:
|
||||
def get_mikrotik_value(self, ip_network):
|
||||
if ip_network:
|
||||
return str(ip_network).encode()
|
||||
else:
|
||||
return b''
|
||||
|
||||
def get_python_value(self, bytes):
|
||||
if bytes:
|
||||
return ipaddress.ip_network(bytes.decode())
|
||||
else:
|
||||
return None
|
||||
|
||||
class ListField:
|
||||
def __init__(self, subfield):
|
||||
self.subfield=subfield
|
||||
|
||||
def get_mikrotik_value(self, objects):
|
||||
return b','.join(
|
||||
self.subfield.get_mikrotik_value(obj) for obj in objects)
|
||||
|
||||
def get_python_value(self, bytes):
|
||||
separator = b',' if b';' not in bytes else b';'
|
||||
return [
|
||||
self.subfield.get_python_value(serialized)
|
||||
for serialized in bytes.split(separator)]
|
||||
|
||||
|
||||
default_structure = collections.defaultdict(StringField)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue