completed using libraries

This commit is contained in:
2023-04-19 01:10:19 +02:00
parent 63f8501818
commit a79c7b431b

View File

@@ -1,9 +1,12 @@
""" Mini-Challenge """ """ Mini-Challenge"""
from os.path import join
from xml.etree import ElementTree as ET
from twisted.internet import defer from twisted.internet import defer
class Adapter():
""" Adapter class class Adapter:
"""Adapter class
Aufgabe: Asynchron XML-Daten lesen, konvertieren und zurückliefern. Aufgabe: Asynchron XML-Daten lesen, konvertieren und zurückliefern.
""" """
@@ -11,14 +14,30 @@ class Adapter():
def __init__(self, path): def __init__(self, path):
self.path = path self.path = path
def _read(self, name):
with open(join(self.path, name + ".xml")) as f:
return f.read()
def _parse(self, xml_data):
root = ET.fromstring(xml_data)
token = root.find("{*}Token").text
return token
def _convert(self, token):
return '{"token": %s}' % token
def retrieve_token(self, name): def retrieve_token(self, name):
""" """
Retrieve the content from file name.xml in adapters path directory Retrieve the content from file name.xml in adapters path directory
in a synchronous way, extract the DataReceived/Token and return it in a synchronous way, extract the DataReceived/Token and return it
as a JSON-Object (stringified) '{"token": value}'. as a JSON-Object (stringified) '{"token": value}'.
""" """
# return '{"token": 42}' - don't do this, just a test try:
raise NotImplementedError xml_data = self._read(name)
token = self._parse(xml_data)
return self._convert(token)
except Exception as e:
raise ValueError("Could not retrieve token: %s" % e)
def retrieve_token_async(self, name): def retrieve_token_async(self, name):
""" """
@@ -31,5 +50,20 @@ class Adapter():
Hint: The simple way is to use defer.succeed(), bonus points for doing Hint: The simple way is to use defer.succeed(), bonus points for doing
it with a callback chain read->parse->convert. it with a callback chain read->parse->convert.
""" """
#return defer.succeed('{"token": 42}') - don't do this, just a test d = defer.Deferred()
raise NotImplementedError
def on_success(xml_data):
try:
token = self._parse(xml_data)
converted = self._convert(token)
d.callback(converted)
except Exception as e:
d.errback(e)
def on_error(error):
d.errback(error)
deferred = defer.maybeDeferred(self._read, name)
deferred.addCallbacks(on_success, on_error)
return d