· 7 years ago · Oct 06, 2018, 07:36 AM
1from flask import Flask, views, request, render_template, send_file
2import os, csv, codecs
3from xml.sax.saxutils import escape
4from xml.dom.minidom import Document
5
6#-----------------------------
7# App Configuration
8
9class Config:
10 ALLOWED_EXTENSIONS = set(['txt', 'csv'])
11 SECRET_KEY = 'oQFoCABw458y&%GS'
12 DEBUG = False
13
14
15class DevConfig(Config):
16 DEBUG = True
17
18def allowed_file(filename):
19 return '.' in filename and \
20 filename.rsplit('.', 1)[1] in Config.ALLOWED_EXTENSIONS
21
22#-----------------------------
23# CSV parsing
24
25def parse_csv(csv_file):
26 if csv_file and allowed_file(csv_file.filename):
27 data = csv.reader(csv_file)
28
29 doc = Document()
30 dataEle = doc.createElement('data')
31 doc.appendChild(dataEle)
32
33 rownum = 0
34 for row in data:
35 if rownum == 0:
36 header = row
37 else:
38 rowEle = doc.createElement('row')
39 dataEle.appendChild(rowEle)
40
41 colnum = 0
42 for col in row:
43 tagEle = doc.createElement(escape_csv_text(header[colnum]))
44 rowEle.appendChild(tagEle)
45
46 tagText = doc.createTextNode(escape_csv_text(col))
47 tagEle.appendChild(tagText)
48
49 colnum += 1
50 rownum += 1
51 return doc
52
53
54def escape_csv_text(data):
55 return escape(data.strip().decode('utf-8'))
56
57#-----------------------------
58# App
59
60app = Flask(__name__)
61app.config.from_object(Config)
62
63
64@app.route('/csvtoxml/')
65def form():
66 return render_template('csvtoxml.html')
67
68
69@app.route('/csvtoxml/', methods=['POST'])
70def process_csv():
71 csv_file = request.files['formFile']
72 parsedXml = parse_csv(csv_file)
73
74 fileName = 'output.xml'
75 xmlFile=codecs.open(fileName, 'w', 'utf-8')
76 parsedXml.writexml(xmlFile)
77 xmlFile.close()
78
79 return send_file(fileName, 'text/xml', True, 'output.xml')
80
81
82@app.route('/')
83def index():
84 return render_template('index.html')