Compare commits

2 Commits

Author SHA1 Message Date
d6fe66d2ec Umstieg auf minidom für Kompatibilität 2023-04-21 16:17:54 +02:00
a79c7b431b completed using libraries 2023-04-19 01:10:19 +02:00

View File

@@ -1,9 +1,12 @@
""" Mini-Challenge """
""" Mini-Challenge"""
from os.path import join
from xml.dom import minidom
from twisted.internet import defer
class Adapter():
""" Adapter class
class Adapter:
"""Adapter class
Aufgabe: Asynchron XML-Daten lesen, konvertieren und zurückliefern.
"""
@@ -13,23 +16,61 @@ class Adapter():
def retrieve_token(self, name):
"""
Retrieve the content from file name.xml in adapters path directory
in a synchronous way, extract the DataReceived/Token and return it
as a JSON-Object (stringified) '{"token": value}'.
Retrieve the content from file name.xml in adapters path directory
in a synchronous way, extract the DataReceived/Token and return it
as a JSON-Object (stringified) '{"token": value}'.
"""
# return '{"token": 42}' - don't do this, just a test
raise NotImplementedError
try:
with open(join(self.path, name + ".xml")) as f:
xml_data = f.read()
dom = minidom.parseString(xml_data)
token = dom.getElementsByTagName("Token")[0].firstChild.data
return '{"token": %s}' % token
except Exception as e:
raise ValueError("Could not retrieve token: %s" % e)
def retrieve_token_async(self, name):
"""
Retrieve the content from file name.xml in adapters path directory
in an asynchronous way, extract the DataReceived/Token and return it
as a Deferred which ends up in a JSON-Object (as above).
Retrieve the content from file name.xml in adapters path directory
in an asynchronous way, extract the DataReceived/Token and return it
as a Deferred which ends up in a JSON-Object (as above).
see: https://twistedmatrix.com/documents/8.0.0/api/twisted.internet.defer.Deferred.html
see: https://twistedmatrix.com/documents/8.0.0/api/twisted.internet.defer.Deferred.html
Hint: The simple way is to use defer.succeed(), bonus points for doing
it with a callback chain read->parse->convert.
Hint: The simple way is to use defer.succeed(), bonus points for doing
it with a callback chain read->parse->convert.
"""
#return defer.succeed('{"token": 42}') - don't do this, just a test
raise NotImplementedError
d = defer.Deferred()
def read_file():
try:
with open(join(self.path, name + ".xml")) as f:
xml_data = f.read()
return xml_data
except Exception as e:
d.errback(e)
def parse_xml(xml_data):
try:
dom = minidom.parseString(xml_data)
token = dom.getElementsByTagName("Token")[0].firstChild.data
return token
except Exception as e:
d.errback(e)
def convert_to_json(token):
try:
json_string = '{"token": %s}' % token
d.callback(json_string)
except Exception as e:
d.errback(e)
defer.execute(read_file).addCallback(parse_xml).addCallback(
convert_to_json
).addErrback(d.errback)
return d