main.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import io
  2. import csv
  3. import pymysql
  4. from app import app
  5. from db import mysql
  6. from flask import Flask, Response, render_template
  7. @app.route('/')
  8. def download():
  9. return render_template('download.html')
  10. @app.route('/download/report/csv')
  11. def download_report():
  12. conn = None
  13. cursor = None
  14. try:
  15. conn = mysql.connect()
  16. cursor = conn.cursor(pymysql.cursors.DictCursor)
  17. cursor.execute("SELECT emp_id, emp_first_name, emp_last_name, emp_designation FROM employee")
  18. result = cursor.fetchall()
  19. output = io.StringIO()
  20. writer = csv.writer(output)
  21. line = ['Emp Id, Emp First Name, Emp Last Name, Emp Designation']
  22. writer.writerow(line)
  23. for row in result:
  24. line = [str(row['emp_id']) + ',' + row['emp_first_name'] + ',' + row['emp_last_name'] + ',' + row['emp_designation']]
  25. writer.writerow(line)
  26. output.seek(0)
  27. return Response(output, mimetype="text/csv", headers={"Content-Disposition":"attachment;filename=employee_report.csv"})
  28. except Exception as e:
  29. print(e)
  30. finally:
  31. cursor.close()
  32. conn.close()
  33. if __name__ == "__main__":
  34. app.run()