socialwifi.RouterOS-api/routeros_api/sentence.py

82 lines
2.6 KiB
Python
Raw Normal View History

2014-06-13 16:49:17 +02:00
import re
from routeros_api import exceptions
2014-06-14 13:18:42 +02:00
from routeros_api import utils
2014-06-13 16:49:17 +02:00
from routeros_api import query
response_re = re.compile(b'^!(re|trap|fatal|done)$')
attribute_re = re.compile(b'^=([^=]+)=([^=]*)$')
tag_re = re.compile(b'^\.tag=([^=]*)$')
class ResponseSentence(object):
def __init__(self, type):
self.attributes = {}
self.type = type
self.tag = None
@classmethod
def parse(cls, sentence):
response_match = response_re.match(sentence[0])
if response_match:
2014-06-14 15:39:11 +02:00
response = cls(response_match.group(1).decode())
2014-06-13 16:49:17 +02:00
response.parse_attributes(sentence[1:])
else:
raise exceptions.RouterOsApiParsingError("Malformed sentence %s",
sentence)
return response
def parse_attributes(self, serialized_attributes):
for serialized in serialized_attributes:
attribute_match = attribute_re.match(serialized)
tag_match = tag_re.match(serialized)
if attribute_match:
key, value = attribute_match.groups()
2014-06-14 15:39:11 +02:00
self.attributes[key.decode()] = self.process_value(value)
2014-06-13 16:49:17 +02:00
elif tag_match:
2014-06-14 15:39:11 +02:00
self.tag = tag_match.group(1).decode()
2014-06-13 16:49:17 +02:00
else:
raise exceptions.RouterOsApiParsingError(
"Malformed attribute %s", serialized)
2014-06-14 15:39:11 +02:00
def process_value(self, value):
return value
2014-06-13 16:49:17 +02:00
class CommandSentence(object):
def __init__(self, path, command, tag=None):
2014-06-14 13:18:42 +02:00
self.path = utils.get_bytes(path)
self.command = utils.get_bytes(command)
2014-06-13 16:49:17 +02:00
self.attributes = {}
self.api_attributes = {}
self.queries = set()
2014-06-14 15:39:11 +02:00
self.tag = utils.get_bytes(tag)
2014-06-13 16:49:17 +02:00
def get_api_format(self):
formated = [self.path + self.command]
for key, value in self.attributes.items():
formated.append(b'=' + key + b'=' + value)
for query in self.queries:
formated.extend(query.get_api_format())
if self.tag is not None:
formated.append(b'.tag=' + self.tag)
return formated
def set(self, key, value):
2014-06-14 13:18:42 +02:00
self.attributes[utils.get_bytes(key)] = utils.get_bytes(value)
2014-06-13 16:49:17 +02:00
def filter(self, *args, **kwargs):
for arg in args:
if hasattr(arg, 'get_api_format'):
self.queries.add(arg)
else:
self.queries.add(query.HasValueQuery(arg))
for key, value in kwargs.items():
self.queries.add(query.IsEqualQuery(key, value))
2014-06-26 13:34:06 +02:00
def __str__(self):
2014-06-26 14:16:38 +02:00
return str(b' '.join(self.get_api_format()))