Functions/historico/handler.py

67 lines
1.9 KiB
Python
Raw Normal View History

2022-07-19 14:56:46 +00:00
import unicodedata
import urllib
from collections import defaultdict as ddict
from dataclasses import dataclass
from json import loads
import pygal
import pyrqlite.dbapi2 as dbapi2
import requests
connection = dbapi2.connect(
host="10.61.0.1",
user="root",
port=4001,
password="",
)
def remove_accents(input_str):
nfkd_form = unicodedata.normalize("NFKD", input_str)
return "".join([c for c in nfkd_form if not unicodedata.combining(c)])
def handle(req):
"""handle a request to the function
Args:
req (str): request body
{"i": ["nombre1, nombre2"]}
2022-07-19 14:56:46 +00:00
"""
2022-07-19 19:14:40 +00:00
nombres = []
2022-07-19 14:56:46 +00:00
try:
2022-07-19 19:14:40 +00:00
nombres = loads(req)
nombres = nombres["i"].split(",")
2022-07-19 19:14:40 +00:00
nombres = [remove_accents(x.strip().lower()) for x in nombres]
nombres = [n for n in nombres if n]
2022-07-19 14:56:46 +00:00
except Exception:
2022-07-19 19:14:40 +00:00
pass
if not nombres:
2022-07-19 14:56:46 +00:00
nombres = ["maria", "juan"]
chart = pygal.Line(
height=200, fill=True, human_readable=True, show_minor_x_labels=False
)
2022-07-20 14:27:49 +00:00
chart.x_labels = [str(x) for x in range(1922, 2015)]
chart.x_labels_major = [str(x) if x % 10 == 0 else "" for x in range(1922, 2015)]
2022-07-19 14:56:46 +00:00
for nombre in nombres:
datos = ddict(int)
with connection.cursor() as cursor:
sql = """
SELECT anio, contador, nombre
FROM nombres
WHERE nombre = :nombre
ORDER BY anio
"""
cursor.execute(sql, {"nombre": nombre})
2022-07-19 14:56:46 +00:00
datos.update({r["anio"]: r["contador"] for r in cursor.fetchall()})
chart.add(nombre.title(), [datos[x] for x in range(1922, 2015)])
2022-07-19 14:56:46 +00:00
chart.x_labels = [str(n) for n in range(1922, 2015)]
chart.x_labels_major = [str(n) for n in range(1920, 2020, 10)]
# return Response(chart.render(is_unicode=True), mimetype="image/svg+xml")
return chart.render(is_unicode=True), 200, {"Content-Type": "image/svg+xml"}