latecomers/latecomers/serializer.py

51 lines
1.4 KiB
Python
Raw Permalink Normal View History

2022-08-24 12:43:32 +02:00
# -*- encoding: utf-8 -*-
import logging
2022-09-18 23:29:02 +02:00
import os.path
2022-08-24 12:43:32 +02:00
from tempfile import NamedTemporaryFile
import typing as T
from latecomers.parse import Details
2022-09-18 23:29:02 +02:00
from latecomers.helpers import logit, get_date
2022-08-24 12:43:32 +02:00
import pandas as pd
logger = logging.getLogger(__name__)
@logit(logger)
2022-09-18 23:29:02 +02:00
def to_excel(data: T.List[Details], dst: T.Optional[T.Text] = None) -> bytes:
2022-08-24 12:43:32 +02:00
"""
This function takes the list of parsed rows as input and returns
the bytes corresponding to the excel file derived from such lines.
"""
mapping = {
"th_arrival": "Arrivo teorico",
"real_arrival": "Arrivo reale",
"code": "Codice volo",
"origin": "Aeroporto di partenza",
"status": "Stato",
2022-09-07 23:44:53 +02:00
"fr24_landing_time": "Ora atterraggio (FlightRadar24)",
2022-08-24 12:43:32 +02:00
}
df = pd.DataFrame(data, columns=mapping)
2022-08-25 21:35:37 +02:00
df["status"] = df["status"].map(lambda x: x.value)
df.set_index("th_arrival", inplace=True)
2022-08-25 23:05:07 +02:00
df.rename(columns=mapping, inplace=True)
df = df.rename_axis(index=mapping["th_arrival"])
2022-08-24 12:43:32 +02:00
with NamedTemporaryFile() as tmp:
df.to_excel(tmp)
tmp.seek(0)
content = tmp.read()
2022-09-18 23:29:02 +02:00
if dst:
filepath = os.path.join(dst, f"{get_date()}.xlsx")
try:
with open(filepath, "wb") as out:
out.write(content)
except Exception as e:
logger.warning(f"Cannot save to path '{filepath}': {e}")
2022-08-24 12:43:32 +02:00
return content