From 00f5f12f7cbb711eae7e19b5e315c91d64cd91b9 Mon Sep 17 00:00:00 2001 From: AlejandroJose2001 Date: Sun, 22 Feb 2026 09:53:58 +0100 Subject: [PATCH] Add: initial implementation of BeautifulSoup exercise 4 with SSL, config, database, and UI setup --- .../beautifulsoup/ej4/data/src/__ssl.py | 5 + .../beautifulsoup/ej4/data/src/config.py | 6 + ejercicios/beautifulsoup/ej4/data/src/db.py | 141 ++++++++++++++++++ ejercicios/beautifulsoup/ej4/data/src/main.py | 85 +++++++++++ ejercicios/beautifulsoup/ej4/data/src/ui.py | 79 ++++++++++ 5 files changed, 316 insertions(+) create mode 100644 ejercicios/beautifulsoup/ej4/data/src/__ssl.py create mode 100644 ejercicios/beautifulsoup/ej4/data/src/config.py create mode 100644 ejercicios/beautifulsoup/ej4/data/src/db.py create mode 100644 ejercicios/beautifulsoup/ej4/data/src/main.py create mode 100644 ejercicios/beautifulsoup/ej4/data/src/ui.py diff --git a/ejercicios/beautifulsoup/ej4/data/src/__ssl.py b/ejercicios/beautifulsoup/ej4/data/src/__ssl.py new file mode 100644 index 0000000..475f052 --- /dev/null +++ b/ejercicios/beautifulsoup/ej4/data/src/__ssl.py @@ -0,0 +1,5 @@ +def init_ssl(): + import os, ssl + if (not os.environ.get('PYTHONHTTPSVERIFY', '') and + getattr(ssl, '_create_unverified_context', None)): + ssl._create_default_https_context = ssl._create_unverified_context diff --git a/ejercicios/beautifulsoup/ej4/data/src/config.py b/ejercicios/beautifulsoup/ej4/data/src/config.py new file mode 100644 index 0000000..ccde50e --- /dev/null +++ b/ejercicios/beautifulsoup/ej4/data/src/config.py @@ -0,0 +1,6 @@ +from pathlib import Path + +BASE_URL = "https://www.recetasgratis.net" +RECIPES_URL = BASE_URL + "/Recetas-de-Aperitivos-tapas-listado_receta-1_1.html/" +DATA_DIR = Path(__file__).parent.parent / "data" +DB_PATH = DATA_DIR / "recetas.bd" \ No newline at end of file diff --git a/ejercicios/beautifulsoup/ej4/data/src/db.py b/ejercicios/beautifulsoup/ej4/data/src/db.py new file mode 100644 index 0000000..88bd2b4 --- /dev/null +++ b/ejercicios/beautifulsoup/ej4/data/src/db.py @@ -0,0 +1,141 @@ +import sqlite3 +from pathlib import Path + + +class DBAttr: + def __init__(self, name, type_, modifier=""): + self.name = name + self.type_ = type_ + self.modifier = modifier + + def sql(self): + parts = [self.name, self.type_] + if self.modifier: + parts.append(self.modifier) + return " ".join(parts) + + +class DBManager: + _instance = None + + def __new__(cls, *args, **kwargs): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__(self, path): + self.path = Path(path) + self.conn = sqlite3.connect(self.path) + self.conn.row_factory = sqlite3.Row + + def create_table(self, table_name, attributes: list[DBAttr]): + columns_sql = ",\n ".join(attr.sql() for attr in attributes) + + query = f""" + CREATE TABLE IF NOT EXISTS {table_name} ( + {columns_sql} + ); + """ + + try: + with self.conn: + self.conn.execute(query) + except Exception as e: + print("Error creating table:", e) + + def get_all(self, table_name): + try: + cursor = self.conn.execute(f"SELECT * FROM {table_name};") + return [dict(row) for row in cursor.fetchall()] + except Exception as e: + print("Error selecting:", e) + return [] + + def get_singleton(self, singleton_table): + try: + cursor = self.conn.execute(f"SELECT * FROM {singleton_table}") + return [row[0] for row in cursor.fetchall()] + except Exception as e: + print("Error selecting:", e) + return [] + + def get_by(self, table_name, column, value): + try: + query = f"SELECT * FROM {table_name} WHERE {column} = ?;" + cursor = self.conn.execute(query, (value,)) + return [dict(row) for row in cursor.fetchall()] + except Exception as e: + print("Error selecting:", e) + return [] + + def insert(self, table_name, data: dict): + keys = ", ".join(data.keys()) + placeholders = ", ".join("?" for _ in data) + values = tuple(data.values()) + + query = f""" + INSERT INTO {table_name} ({keys}) + VALUES ({placeholders}); + """ + + try: + with self.conn: + self.conn.execute(query, values) + except Exception as e: + print("Error inserting:", e) + + def update(self, table_name, data: dict, where_column, where_value): + set_clause = ", ".join(f"{key} = ?" for key in data.keys()) + values = list(data.values()) + values.append(where_value) + + query = f""" + UPDATE {table_name} + SET {set_clause} + WHERE {where_column} = ?; + """ + + try: + with self.conn: + self.conn.execute(query, tuple(values)) + except Exception as e: + print("Error updating:", e) + + def delete(self, table_name, where_column, where_value): + query = f"DELETE FROM {table_name} WHERE {where_column} = ?;" + + try: + with self.conn: + self.conn.execute(query, (where_value,)) + except Exception as e: + print("Error deleting:", e) + + def clear(self, table_name): + query = f"DELETE FROM {table_name};" + + try: + with self.conn: + self.conn.execute(query) + except Exception as e: + print("Error clearing table: ", e) + + def exists(self, table_name, where_column, where_value): + query = f"SELECT 1 FROM {table_name} WHERE {where_column} = ? LIMIT 1;" + + try: + cursor = self.conn.execute(query, (where_value,)) + return cursor.fetchone() is not None + except Exception as e: + print("Error checking existence:", e) + return False + + def count(self, table_name): + try: + cursor = self.conn.execute(f"SELECT COUNT(*) as total FROM {table_name};") + return cursor.fetchone()["total"] + except Exception as e: + print("Error counting:", e) + return 0 + + def close(self): + self.conn.close() \ No newline at end of file diff --git a/ejercicios/beautifulsoup/ej4/data/src/main.py b/ejercicios/beautifulsoup/ej4/data/src/main.py new file mode 100644 index 0000000..39cd575 --- /dev/null +++ b/ejercicios/beautifulsoup/ej4/data/src/main.py @@ -0,0 +1,85 @@ +from bs4 import BeautifulSoup +import re +from tkinter import Tk +from tkinter import messagebox +import urllib.request +from datetime import datetime + +from db import DBManager, DBAttr +from ui import WinesUI +from __ssl import init_ssl +from config import * + +init_ssl() + +dbm = DBManager(DB_PATH) + +def create_tables(): + movies_attr = [ + DBAttr("title", "TEXT", "NOT NULL"), + DBAttr("original_title", "TEXT", "NOT NULL"), + DBAttr("country", "TEXT", "NOT NULL"), + DBAttr("date", "DATE", "NOT NULL"), + DBAttr("director", "TEXT", "NOT NULL"), + DBAttr("genres", "TEXT", "NOT NULL") + ] + + genres_attr = [ + DBAttr("genre", "TEXT") + ] + + dbm.create_table("movies", movies_attr) + dbm.create_table("genres", genres_attr) + +def parse_duration(duration): + duration.strip() + res = 0 + if duration[-1] == "h": + duration.replace("h","") + res = int(duration) * 60 + elif "h" in duration: + duration.replace("h","") + duration.replace("m","") + res = int(duration[0]) + int(duration[1:]) + else: + duration.replace("m","") + res = int(duration) + return res + +def main(): + create_tables() + root = Tk() + ui = WinesUI(root) + + + def handle_action(action): + match(action): + case "cargar": + resp = messagebox.askyesno(title="Cargar", message="Quieres cargar todos los datos de nuevo?") + if resp: + dbm.clear("movies") + dbm.clear("genres") + movies_count = persit_recetas() + ui.info(f"Hay {movies_count} recetas") + case "Recetas": + recetas = dbm.get_all("recetas") + ui.show_list(recetas, ["titulo", "dificultad", "comensales", "duracion", "autor", "fecha"]) + case "Receta por autor": + def search_title(title): + movies = [movie for movie in dbm.get_all("recetas") if title.lower() in movie["titulo"].lower()] + ui.show_list(recetas, ["titulo", "dificultad", "comensales", "duracion", "autor", "fecha"]) + ui.ask_text("Buscar por autor: ", search_title) + case "Receta por fecha": + def search_date(date): + d = datetime.strptime(date, "%d-%m-%Y") + movies = [movie for movie in dbm.get_all("movies") + if d < datetime.strptime(movie["date"], "%Y-%m-%d %H:%M:%S")] + ui.show_list(movies, ["title", "date"]) + ui.ask_text("Buscar por fecha: ", search_date) + + ui.callback = handle_action + root.mainloop() + dbm.close() + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/ejercicios/beautifulsoup/ej4/data/src/ui.py b/ejercicios/beautifulsoup/ej4/data/src/ui.py new file mode 100644 index 0000000..d1cc79a --- /dev/null +++ b/ejercicios/beautifulsoup/ej4/data/src/ui.py @@ -0,0 +1,79 @@ +import tkinter as tk +from tkinter import ttk, messagebox +from tkinter.scrolledtext import ScrolledText + +class WinesUI(): + def __init__(self, root, title = "AII"): + self.root = root + self.root.title(title) + self.root.geometry("900x600") + + # Menu Principal + self.menu = tk.Menu(self.root) + self.root.config(menu=self.menu) + + # Menu Datos + datos_menu = tk.Menu(self.menu, tearoff=0) + datos_menu.add_command(label="Cargar", command=lambda: self.callback("cargar")) + datos_menu.add_separator() + datos_menu.add_command(label="Salir", command=self.root.quit) + self.menu.add_cascade(label="Datos", menu=datos_menu) + + # Menu Listar + listar_menu = tk.Menu(self.menu, tearoff=0) + listar_menu.add_command(label= "Recetas", command = lambda: self.callback("listar_recetas")) + + # Menu Buscar + buscar_menu = tk.Menu(self.menu, tearoff=0) + buscar_menu.add_command(label="Receta por autor", command=lambda: self.callback("buscar_autor")) + buscar_menu.add_command(label="Receta por fecha", command=lambda: self.callback("buscar_fecha")) + + self.menu.add_cascade(label="Buscar", menu=buscar_menu) + + # Callback externo desde el punto de entrada + self.callback = None + + def show_list(self, items, fields, title="Listado"): + mw = tk.Toplevel(self.root) + mw.title(title) + listbox = tk.Listbox(mw, width=80, height=20) + listbox.pack(side="left", fill="both", expand=True) + scrollbar = tk.Scrollbar(mw) + scrollbar.pack(side="right", fill="y") + listbox.config(yscrollcommand=scrollbar.set) + scrollbar.config(command=listbox.yview) + + for item in items: + row = " | ".join(str(item[field]) for field in fields) + listbox.insert("end", row) + + def ask_text(self, label, callback): + mw = tk.Toplevel(self.root) + mw.title(label) + tk.Label(mw, text=label).pack(pady=5) + entry = ttk.Entry(mw) + entry.pack(pady=5) + ttk.Button(mw, text="Aceptar", command= + lambda: [callback(entry.get()), mw.destroy()]).pack(pady=10) + + def ask_spinbox(self, label, options, callback): + mw = tk.Toplevel(self.root) + mw.title(label) + tk.Label(mw, text=label).pack(pady=5) + spinbox = ttk.Spinbox(mw, values=options, state="readonly", width=40) + spinbox.pack(pady=5) + ttk.Button(mw, text="Aceptar", command= + lambda: [callback(spinbox.get()), mw.destroy()]).pack(pady=10) + + def ask_radiobutton(self, label, options, callback): + mw = tk.Toplevel(self.root) + mw.title(label) + tk.Label(mw, text=label).pack(pady=5) + sv = tk.StringVar(value=options[0]) + for option in options: + tk.Radiobutton(mw, text=option, variable=sv, value=option).pack(anchor="w") + ttk.Button(mw, text="Aceptar", command= + lambda: [callback(sv.get()), mw.destroy()]).pack(pady=10) + + def info(slef, message): + messagebox.showinfo("Información", message) \ No newline at end of file