Advertisement
teslariu

admin resto sqlite

Sep 8th, 2023
1,199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.41 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. Script que implemente un menu para administrar un restaurante. Vamos a
  6. implementar dos tablas: categorias y platos
  7. EJ: categorias: ensaladas, entradas, guarniciones, plato principal, postre
  8. platos: milanesa, ravioles, fideos, flan, empanada, ensalada cesar, etc.
  9. Vamos a hacer un menu que implemente por ejemplo:
  10. 1. Agregar categoria
  11. 2. Agregar plato
  12. 3. Mostrar menu
  13. 4. Salir
  14.  
  15. """
  16. import os
  17. import sqlite3
  18. from tabulate import tabulate
  19.  
  20. def borrar_pantalla():
  21.     if os.name == "posix":
  22.         os.system ("clear")
  23.    
  24.     else:
  25.         os.system ("cls")
  26.  
  27.  
  28. def menu_de_opciones():
  29.     return """
  30.        Menú de categorías y platos
  31.    *--------------------------------*
  32.        1. Agregar categoría
  33.        2. Agregar plato
  34.        3. Mostrar menú
  35.        4. Salir
  36.    *--------------------------------*
  37.    """
  38.    
  39. def agregar_categoria():
  40.     nombre = input("Ingrese el nombre de la categoría: ")
  41.     try:
  42.         conn.execute("INSERT INTO categorias VALUES(null,?)",(nombre,))
  43.     except sqlite3.IntegrityError:
  44.         print(f"Error: ya existe la categoría '{nombre}'")
  45.     else:
  46.         print("Categoría añadida")
  47.         conn.commit()
  48.    
  49.    
  50.  
  51. def agregar_plato():
  52.     tabla = []
  53.     try:
  54.         cursor.execute("SELECT * FROM categorias ORDER BY id")
  55.     except sqlite3.OperationalError:
  56.         print("No se pudo ejecutar la consulta")
  57.     else:
  58.         categorias = cursor.fetchall()
  59.         if categorias:
  60.             id_categoria = [] # almacenará los id de las categorías YA CREADAS
  61.             for categoria in categorias:
  62.                 tabla.append(categoria)
  63.                 id_categoria.append(categoria[0])
  64.             print(tabulate(
  65.                 tabla,
  66.                 headers = ["ID de categoría", "categoría"],
  67.                 tablefmt = "grid",
  68.                 colalign = ["center", "left"]
  69.                 )
  70.             )            
  71.             # valido que el usuario ingrese un id de categoría válido
  72.             while True:
  73.                 try:
  74.                     ID = int(input("\nSeleccione un id: "))
  75.                 except ValueError:
  76.                     print("El ID debe ser un nro entero")
  77.                 else:
  78.                     if ID in id_categoria:
  79.                         break
  80.                     print(f"No existe el id '{ID}'")
  81.                    
  82.             # Creo el plato
  83.             nombre_plato = input("Ingrese el nombre del plato: ")
  84.             try:
  85.                 conn.execute("INSERT INTO platos VALUES(null,?,?)",(nombre_plato,ID))
  86.             except sqlite3.IntegrityError:
  87.                 print(f"Error: ya existe el plato '{nombre_plato}'")
  88.             else:
  89.                 print("Plato añadido")
  90.                 conn.commit()
  91.         else:
  92.             print("No existen categorías de platos")
  93.    
  94.    
  95.    
  96. def menu():
  97.     tabla = []
  98.     query = "SELECT categorias.id, categorias.nombre, platos.id, platos.nombre FROM categorias\
  99.            LEFT JOIN platos\
  100.            ON platos.id_categoria = categorias.id\
  101.            ORDER BY categorias.id, platos.id"
  102.            
  103.            
  104.     try:
  105.         cursor.execute(query)
  106.     except sqlite3.OperationalError:
  107.         return "No existen categorías y/o platos"
  108.     else:
  109.         platos = cursor.fetchall()
  110.         if platos:
  111.             for plato in platos:
  112.                 tabla.append(plato)
  113.             return tabulate(
  114.                     tabla,
  115.                     headers = ["ID de categoría", "Categoría", "ID del plato", "Plato"],
  116.                     tablefmt = "grid",
  117.                     colalign = ["center", "left", "center", "left"]
  118.                     )
  119.         else:
  120.             return "No existe ningún plato en el menú"
  121.  
  122.  
  123.  
  124.    
  125. conn = sqlite3.connect("restaurante.db")
  126. cursor = conn.cursor()
  127.  
  128. while True:
  129.    
  130.     borrar_pantalla()
  131.     print(menu_de_opciones())
  132.    
  133.     opcion = input("Ingrese su opción: ")
  134.    
  135.     if opcion == "1":
  136.         agregar_categoria()
  137.         input()
  138.        
  139.     elif opcion == "2":
  140.         agregar_plato()
  141.         input()
  142.        
  143.     elif opcion == "3":
  144.         print(menu())
  145.         input()
  146.        
  147.     elif opcion == "4":
  148.         conn.close()
  149.         print("Hasta luego...")
  150.         break
  151.        
  152.     else:
  153.         print("Opción incorrecta")
  154.         input()
  155.    
  156.    
  157.    
  158.    
  159.    
  160.    
  161.    
  162.    
  163.    
  164.    
  165.    
  166.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement