models.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. from flask import jsonify, render_template, make_response
  2. from flask_restful import Resource
  3. from database import e
  4. from json import dumps
  5. class Demandas_Meta(Resource):
  6. def get(self):
  7. #Connect to database
  8. conn = e.connect()
  9. #Perform query and return JSON data
  10. query = conn.execute("select distinct PAIS from GENERACION_EOR_TR")
  11. result = query.cursor.fetchall()
  12. data = {'paises' : [row[0] for row in result]}
  13. return jsonify(data)
  14. class Demandas(Resource):
  15. def get(self):
  16. #Connect to database
  17. conn = e.connect()
  18. #Perform query and return JSON data
  19. query = conn.execute("select * from DEMANDA_MER")
  20. columns = query.keys()
  21. data = []
  22. result = query.cursor.fetchall()
  23. for row in result:
  24. data.append(dict(zip(columns, row)))
  25. #List of Dicts to Dict of List (LD to DL)
  26. v = dict(zip(data[0], zip(*[d.values() for d in data])))
  27. response = jsonify({'data' : v})
  28. #Response is List of Dicts (LD)
  29. #response = jsonify({'data' : data})
  30. return response
  31. class Demanda_Max(Resource):
  32. def get(self, pais):
  33. #Connect to database
  34. conn = e.connect()
  35. #Perform query and return JSON data
  36. query = conn.execute("""SELECT
  37. FECHA_HORA,
  38. LTRIM(RTRIM(PAIS)) PAIS,
  39. DEMANDA
  40. FROM
  41. GENERACION_EOR_TR
  42. WHERE
  43. DEMANDA =
  44. (
  45. SELECT
  46. MAX(DEMANDA)
  47. FROM
  48. GENERACION_EOR_TR
  49. WHERE
  50. PAIS = '{0}'
  51. AND FECHA_HORA >= DATEADD(DAY, - 1, GETDATE())
  52. )
  53. AND PAIS = '{0}'
  54. AND FECHA_HORA >= DATEADD(DAY, - 1, GETDATE())""".format(pais.upper()))
  55. columns = query.keys()
  56. data = []
  57. result = query.cursor.fetchall()
  58. #print(result)
  59. for row in result:
  60. data.append(dict(zip(columns, row)))
  61. response = jsonify({'data' : data[0]})
  62. return response
  63. class Home_Page(Resource):
  64. def get(self):
  65. headers = {'Content-Type' : 'text/html'}
  66. return make_response(render_template('home.html', title = 'API MER Data'),200,headers)