A better solution
Andrew Z
formisc at gmail.com
Sat Mar 17 01:36:07 EDT 2018
Hello,
im not entirely happy with my solution and would love to hear your
suggestions on how to improve the solution.
I simplified the task while keeping the code working.
Task:
financial accounts are described by XML documents. I want to architecture
the code to be easily extendible ( easy to add more accounts) and with
minimum repetitive code in each class.
All XML documents have a few common (SSN, first/last, sex, etc.) and unique
fields. Both common and unique fields may or may not be present in the
passed parameters.
I came up with the following solution:
one class as a common "account" with children that have specific
functionality for their specific fields.
What i _really_ don't like is the a repetitive code in each _init_ and
"update" method.
Code:
-----start ----
from flask import Flask, jsonify, request
import xml_oper
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World!"
@app.route('/INT/API/1.0/Accounts/IRA_Simple', methods =['POST'])
def post_IRA_Simple():
json = request.get_json()
account = xml_oper.account_type['IRA']
account.update_xml(output_file_name='IRA.xml',json=json)
return jsonify( 'all good ), 201
if __name__ == '__main__':
app.run(debug=True)
xml_oper,py
from lxml import etree
from bs4 import BeautifulSoup as Soup
class Account():
'''
Parent for all account types
'''
_file_path_source = 'XXX/XML_Docs/Sample_ApplicationXML/'
_file_path_dest = 'XXXXX/src/XML/'
def __init__(self):
pass
def _open_xml(self, file_name):
self._soup = Soup(open(Account._file_path_source + file_name,
'r'), 'lxml')
def _write_xml(self, file_name):
f = open(Account._file_path_dest + file_name, 'w')
f.write(self._soup.prettify())
f.close()
def _update(self, json):
# update only common fields
self._soup.application.customer['email'] = 'bla at email.com'
class IRA(Account):
def __init__(self, source_file_name):
super().__init__()
super()._open_xml(file_name=source_file_name)
def update_xml(self, output_file_name, json):
super()._update(json= json)
# update specific to IRA account fields
# values may or may not exit
super()._write_xml(file_name=output_file_name)
class Checking(Account):
def __init__(self, source_file_name):
super().__init__()
super()._open_xml(file_name=source_file_name)
def update_xml(self, output_file_name, json):
super()._update(json= json)
# update specific to CHK account fields
# values may or may not exit
super()._write_xml(file_name=output_file_name)
account_type = {
'IRA' : IRA('IRA_Sample.xml'),
'Checking' : Checking('Checking_Sample.xml')
}
--- end----
Thank you.
More information about the Python-list
mailing list