app.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from flask import Flask, request, redirect, render_template, url_for, send_file
  2. from parsers.CSV_to_RDF_generico import parse, parsefromfile
  3. from parsers.get_form_fields import getFormFields
  4. app = Flask(__name__)
  5. @app.route('/', methods=['POST','GET'])
  6. def main():
  7. appath = app.root_path + '/'
  8. configurationFolder = 'parsers/configuration_files/'
  9. configurationFileName = 'configuration.json'
  10. confFilePath = appath + configurationFolder + configurationFileName
  11. try:
  12. formFields = getFormFields(confFilePath)
  13. except:
  14. return redirect(url_for('error', message='no valid config file found'))
  15. if request.method == 'POST':
  16. try:
  17. outputFolder = appath + 'samples/RDF/'
  18. fileFromRequest = request.files['FILE']
  19. filename = fileFromRequest.filename
  20. # If a file was uploaded, read data from file
  21. if filename != '':
  22. outFileName = filename.replace('.csv', '') + '.ttl'
  23. outFilePath = outputFolder + outFileName
  24. inFile = fileFromRequest.read()
  25. # try to create list of dictionaries keyed by header row
  26. parsefromfile(confFilePath, formFields, inFile, outFilePath)
  27. # Else read data from form
  28. else:
  29. data = {}
  30. for field in formFields:
  31. data[field] = request.form[field]
  32. check = [val for val in data.values() if val!='']
  33. if len(check)>0:
  34. outFileName = 'form_output.ttl'
  35. outFilePath = outputFolder + outFileName
  36. parse(confFilePath, formFields, [data], outFilePath)
  37. else:
  38. raise Exception("No data")
  39. except:
  40. return redirect(url_for('error', message='no CSV data, or CSV input file missing required data'))
  41. return redirect(url_for('main', download=outFileName))
  42. return render_template('index.html.j2', data=formFields)
  43. @app.route('/error/', methods=['POST','GET'])
  44. def error():
  45. if request.method == 'POST':
  46. return redirect(url_for('main'))
  47. else:
  48. return render_template('error.html.j2', message=request.args.get('message'))
  49. @app.route('/download/', methods=['POST', 'GET'])
  50. def download():
  51. appath = app.root_path + '/'
  52. outFileName = request.args.get('filename')
  53. outFilePath = appath + 'samples/RDF/' + outFileName
  54. return send_file(outFilePath, as_attachment=True)
  55. if __name__ == '__main__':
  56. app.run()