Files
challenge/challenge.py

77 lines
2.3 KiB
Python

""" Mini-Challenge"""
from os.path import join
from xml.dom import minidom
from twisted.internet import defer
class Adapter:
"""Adapter class
Aufgabe: Asynchron XML-Daten lesen, konvertieren und zurückliefern.
"""
def __init__(self, path):
self.path = path
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}'.
"""
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).
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.
"""
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