Coverage for hexonet/apiconnector/responseparser.py: 100%
36 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 09:07 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-11-09 09:07 +0000
1# -*- coding: utf-8 -*-
2"""
3 hexonet.apiconnector.responseparser
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 This module covers all necessary functionality to
6 parse a raw Backend API response and to serialize it back.
7 :copyright: © 2018 by HEXONET GmbH.
8 :license: MIT, see LICENSE for more details.
9"""
11import re
14def parse(raw):
15 """
16 Returns the response as a string
17 """
18 r = {}
19 re1 = re.compile(r"^([^\=]*[^\t\= ])[\t ]*=[\t ]*(.*)$")
20 re2 = re.compile(r"^property\[([^\]]*)\]", re.IGNORECASE)
22 raw = raw.replace("\r\n", "\n")
23 for line in raw.split("\n"):
24 m1 = re1.match(line)
25 if not m1:
26 continue
27 attr = m1.group(1)
28 value = m1.group(2)
29 value = re.sub(r"[\t ]*$", "", value)
31 m2 = re2.match(attr)
32 if m2:
33 prop = m2.group(1).upper()
34 prop = re.sub(r"\s", "", prop)
35 if "PROPERTY" not in r:
36 r["PROPERTY"] = {}
37 if prop not in r["PROPERTY"]:
38 r["PROPERTY"][prop] = []
39 r["PROPERTY"][prop].append(value)
40 else:
41 r[attr.upper()] = value
42 return r
45def serialize(r):
46 """
47 Returns the dictionary represenation serialized back to plain text
48 """
49 d = ""
50 if "PROPERTY" in r:
51 keys = sorted(r["PROPERTY"].keys())
52 for key in keys:
53 for index, val in enumerate(r["PROPERTY"][key]):
54 d += ("\r\nPROPERTY[{0}][{1}]={2}").format(key, index, val)
55 for prop in ["CODE", "DESCRIPTION", "QUEUETIME", "RUNTIME"]:
56 if prop in r:
57 d += ("\r\n{0}={1}").format(prop, r[prop])
58 return ("[RESPONSE]{0}\r\nEOF\r\n").format(d)