Functions/nombres/historico/handler.py

66 lines
1.9 KiB
Python
Raw Normal View History

2022-07-19 11:56:46 -03: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
2022-07-19 16:14:40 -03:00
[nombre1, nombre2, ... nombreN]
2022-07-19 11:56:46 -03:00
"""
2022-07-19 16:14:40 -03:00
nombres = []
2022-07-19 11:56:46 -03:00
try:
2022-07-19 16:14:40 -03:00
nombres = loads(req)
nombres = [remove_accents(x.strip().lower()) for x in nombres]
nombres = [n for n in nombres if n]
2022-07-19 11:56:46 -03:00
except Exception:
2022-07-19 16:14:40 -03:00
pass
if not nombres:
2022-07-19 11:56:46 -03:00
nombres = ["maria", "juan"]
chart = pygal.Line(
height=200, fill=True, human_readable=True, show_minor_x_labels=False
)
2022-07-20 11:27:49 -03: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 11:56:46 -03: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 11:56:46 -03: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 11:56:46 -03: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"}