Functions/historico/handler.py
2023-05-16 12:38:37 -03:00

67 lines
1.9 KiB
Python

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"]}
"""
nombres = []
try:
nombres = loads(req)
nombres = nombres["i"].split(",")
nombres = [remove_accents(x.strip().lower()) for x in nombres]
nombres = [n for n in nombres if n]
except Exception:
pass
if not nombres:
nombres = ["maria", "juan"]
chart = pygal.Line(
height=200, fill=True, human_readable=True, show_minor_x_labels=False
)
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)]
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})
datos.update({r["anio"]: r["contador"] for r in cursor.fetchall()})
chart.add(nombre.title(), [datos[x] for x in range(1922, 2015)])
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"}