From 13d0fe5fcdefa50d14574c89d150205068dabb82 Mon Sep 17 00:00:00 2001 From: Celestino Rey Date: Tue, 4 Feb 2025 07:30:16 +0100 Subject: [PATCH] Api para lyrics --- ReyMotaAppsDj/K8S/Makefile | 2 +- .../reymota/lyrics/management/__init__.py | 0 .../management/commands/importa_album.py | 23 ------- .../management/commands/importa_artista.py | 23 ------- .../management/commands/importa_song.py | 26 -------- .../management/commands/importar_albumes.py | 48 +++++++++++++++ .../management/commands/importar_artistas.py | 42 +++++++++++++ .../management/commands/importar_canciones.py | 50 +++++++++++++++ ReyMotaAppsDj/reymota/lyrics/serializers.py | 20 ++++++ ReyMotaAppsDj/reymota/lyrics/urls.py | 12 ++++ ReyMotaAppsDj/reymota/lyrics/views.py | 61 +++++++++++++++++++ 11 files changed, 234 insertions(+), 73 deletions(-) create mode 100644 ReyMotaAppsDj/reymota/lyrics/management/__init__.py delete mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importa_album.py delete mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importa_artista.py delete mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importa_song.py create mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importar_albumes.py create mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importar_artistas.py create mode 100644 ReyMotaAppsDj/reymota/lyrics/management/commands/importar_canciones.py create mode 100644 ReyMotaAppsDj/reymota/lyrics/serializers.py diff --git a/ReyMotaAppsDj/K8S/Makefile b/ReyMotaAppsDj/K8S/Makefile index 92d4c4f..54e8fbd 100644 --- a/ReyMotaAppsDj/K8S/Makefile +++ b/ReyMotaAppsDj/K8S/Makefile @@ -1,7 +1,7 @@ export ARQUITECTURA := $(shell lscpu |grep itectur | tr -d ' '| cut -f2 -d':') #export REGISTRY=registry.cube.local export REGISTRY=registry.reymota.es -export IMG_VERSION = 0.45 +export IMG_VERSION = 0.48 export IMG_NGINX_VERSION = 1.0 # limpia todo diff --git a/ReyMotaAppsDj/reymota/lyrics/management/__init__.py b/ReyMotaAppsDj/reymota/lyrics/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_album.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_album.py deleted file mode 100644 index 0bb6bae..0000000 --- a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_album.py +++ /dev/null @@ -1,23 +0,0 @@ -from django.core.management.base import BaseCommand, CommandError -from lyrics.models import Album, Artista, Song -import csv -import argparse -from datetime import datetime - - -class Command(BaseCommand): - help = "Importa la lista de letras" - - def add_arguments(self, parser): - parser.add_argument("fichero_csv", type=str, help='Ruta al fichero csv') - - def handle(self, *args, **options): - fichero = options["fichero_csv"] - with open(fichero, 'r') as file: - reader = csv.DictReader(file) - for row in reader: - name = row['name'], - artist = row['artist'], - year = row['year'], - cover_image = row['cover_image'] - print(name, ",", artist, ",", year, ",", cover_image) diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_artista.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_artista.py deleted file mode 100644 index 0bb6bae..0000000 --- a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_artista.py +++ /dev/null @@ -1,23 +0,0 @@ -from django.core.management.base import BaseCommand, CommandError -from lyrics.models import Album, Artista, Song -import csv -import argparse -from datetime import datetime - - -class Command(BaseCommand): - help = "Importa la lista de letras" - - def add_arguments(self, parser): - parser.add_argument("fichero_csv", type=str, help='Ruta al fichero csv') - - def handle(self, *args, **options): - fichero = options["fichero_csv"] - with open(fichero, 'r') as file: - reader = csv.DictReader(file) - for row in reader: - name = row['name'], - artist = row['artist'], - year = row['year'], - cover_image = row['cover_image'] - print(name, ",", artist, ",", year, ",", cover_image) diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_song.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_song.py deleted file mode 100644 index 0659fdd..0000000 --- a/ReyMotaAppsDj/reymota/lyrics/management/commands/importa_song.py +++ /dev/null @@ -1,26 +0,0 @@ -from django.core.management.base import BaseCommand, CommandError -from lyrics.models import Album, Artista, Song -import csv -import argparse -from datetime import datetime -import pandas as pd - - -class Command(BaseCommand): - help = "Importa la lista de letras" - - def add_arguments(self, parser): - parser.add_argument("fichero_csv", type=str, help='Ruta al fichero csv') - - def handle(self, *args, **options): - fichero = options["fichero_csv"] - contenido = pd.read_csv(fichero) - - for fila in contenido.iterrows(): - print(fila[1].title, ", ", fila[1].artist, ", ", fila[1].album) - - artista = Artista.objects.get(nombre=fila[1].artist) - album = Album.objects.get(pk=fila[1].album) - - cancion = Song(title=fila[1].title, artist=artista, album=album, pista=fila[1].pista, lyrics=fila[1].lyrics) - cancion.save() diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_albumes.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_albumes.py new file mode 100644 index 0000000..be3f4ba --- /dev/null +++ b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_albumes.py @@ -0,0 +1,48 @@ +import json +from django.core.management.base import BaseCommand +from lyrics.models import Album, Artista + + +class Command(BaseCommand): + help = "Importa albumes desde un archivo JSON" + + def add_arguments(self, parser): + parser.add_argument('archivo_json', type=str, help="Ruta del archivo JSON") + + def handle(self, *args, **kwargs): + archivo_json = kwargs['archivo_json'] + + try: + with open(archivo_json, 'r', encoding='utf-8') as file: + datos = json.load(file) + + self.stdout.write(self.style.WARNING(f"\nSe encontraron {len(datos)} albumes en el archivo '{archivo_json}'.")) + confirmar = input("¿Deseas continuar con la importación? (s/n): ").strip().lower() + + if confirmar != 's': + self.stdout.write(self.style.ERROR("Importación cancelada.")) + return + + albumes_creados = 0 + for album_data in datos: + try: + artista = Artista.objects.get(id=album_data["artist"]) + + creado = Album.objects.create( + artista_id=artista.id, + name=album_data['name'], + year=album_data['year'], + cover_image=album_data['cover_image'], + ) + if creado: + albumes_creados += 1 + + except Artista.DoesNotExist: + self.stderr.write(self.style.ERROR(f"Artista '{album_data['artista']}' no encontrado.")) + + self.stdout.write(self.style.SUCCESS(f'Se importaron {albumes_creados} albumes correctamente.')) + + except FileNotFoundError: + self.stderr.write(self.style.ERROR(f"El archivo {archivo_json} no se encontró.")) + except json.JSONDecodeError: + self.stderr.write(self.style.ERROR("Error al leer el archivo JSON. Asegúrate de que el formato sea correcto.")) diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_artistas.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_artistas.py new file mode 100644 index 0000000..a027340 --- /dev/null +++ b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_artistas.py @@ -0,0 +1,42 @@ +import json +from django.core.management.base import BaseCommand +from lyrics.models import Artista + + +class Command(BaseCommand): + help = "Importa artistas desde un archivo JSON" + + def add_arguments(self, parser): + parser.add_argument('archivo_json', type=str, help="Ruta del archivo JSON") + + def handle(self, *args, **kwargs): + archivo_json = kwargs['archivo_json'] + + try: + with open(archivo_json, 'r', encoding='utf-8') as file: + datos = json.load(file) + + self.stdout.write(self.style.WARNING(f"\nSe encontraron {len(datos)} artistas en el archivo '{archivo_json}'.")) + confirmar = input("¿Deseas continuar con la importación? (s/n): ").strip().lower() + + if confirmar != 's': + self.stdout.write(self.style.ERROR("Importación cancelada.")) + return + + artistas_creados = 0 + for artista_data in datos: + creado = Artista.objects.create( + id=artista_data['id'], + nombre=artista_data['nombre'], + biografia=artista_data['biografia'], + foto=artista_data['foto'] + ) + if creado: + artistas_creados += 1 + + self.stdout.write(self.style.SUCCESS(f'Se importaron {artistas_creados} artistas correctamente.')) + + except FileNotFoundError: + self.stderr.write(self.style.ERROR(f"El archivo {archivo_json} no se encontró.")) + except json.JSONDecodeError: + self.stderr.write(self.style.ERROR("Error al leer el archivo JSON. Asegúrate de que el formato sea correcto.")) diff --git a/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_canciones.py b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_canciones.py new file mode 100644 index 0000000..3e26630 --- /dev/null +++ b/ReyMotaAppsDj/reymota/lyrics/management/commands/importar_canciones.py @@ -0,0 +1,50 @@ +import json +from django.core.management.base import BaseCommand +from lyrics.models import Cancion, Album + + +class Command(BaseCommand): + help = "Importa canciones desde un archivo JSON" + + def add_arguments(self, parser): + parser.add_argument('archivo_json', type=str, help="Ruta del archivo JSON") + + def handle(self, *args, **kwargs): + archivo_json = kwargs['archivo_json'] + + try: + with open(archivo_json, 'r', encoding='utf-8') as file: + datos = json.load(file) + + self.stdout.write(self.style.WARNING(f"\nSe encontraron {len(datos)} canciones en el archivo '{archivo_json}'.")) + confirmar = input("¿Deseas continuar con la importación? (s/n): ").strip().lower() + + if confirmar != 's': + self.stdout.write(self.style.ERROR("Importación cancelada.")) + return + + canciones_creados = 0 + for cancion_data in datos: + try: + album = Album.objects.get(id=cancion_data["album"]) + + creado = Cancion.objects.create( + album_id=album.id, + title=cancion_data['title'], + artist=cancion_data['artist'], + year=cancion_data['year'], + lyrics=cancion_data['lyrics'], + pista=cancion_data['pista'], + ) + if creado: + canciones_creados += 1 + + except Album.DoesNotExist: + self.stderr.write(self.style.ERROR(f"Album '{cancion_data['album']}' no encontrado.")) + + self.stdout.write(self.style.SUCCESS(f'Se importaron {canciones_creados} canciones correctamente.')) + + except FileNotFoundError: + self.stderr.write(self.style.ERROR(f"El archivo {archivo_json} no se encontró.")) + except json.JSONDecodeError: + self.stderr.write(self.style.ERROR("Error al leer el archivo JSON. Asegúrate de que el formato sea correcto.")) diff --git a/ReyMotaAppsDj/reymota/lyrics/serializers.py b/ReyMotaAppsDj/reymota/lyrics/serializers.py new file mode 100644 index 0000000..5ba68cc --- /dev/null +++ b/ReyMotaAppsDj/reymota/lyrics/serializers.py @@ -0,0 +1,20 @@ +from rest_framework import serializers +from .models import Artista, Album, Song + + +class ArtistaSerializer(serializers.ModelSerializer): + class Meta: + model = Artista + fields = '__all__' # Incluir todos los campos del modelo + + +class AlbumSerializer(serializers.ModelSerializer): + class Meta: + model = Album + fields = '__all__' # Incluir todos los campos del modelo + + +class CancionSerializer(serializers.ModelSerializer): + class Meta: + model = Song + fields = '__all__' # Incluir todos los campos del modelo diff --git a/ReyMotaAppsDj/reymota/lyrics/urls.py b/ReyMotaAppsDj/reymota/lyrics/urls.py index dc60b53..a931c57 100644 --- a/ReyMotaAppsDj/reymota/lyrics/urls.py +++ b/ReyMotaAppsDj/reymota/lyrics/urls.py @@ -2,6 +2,9 @@ from django.urls import path from . import views +from .views import api_lista_artistas, api_detalle_artista +from .views import api_lista_albumes, api_detalle_album +from .views import api_lista_canciones, api_detalle_cancion app_name = 'lyrics' @@ -24,4 +27,13 @@ urlpatterns = [ path('song//', views.detalle_song, name='detalle_song'), path('song//editar/', views.editar_song, name='editar_song'), path('song//eliminar/', views.eliminar_song, name='eliminar_song'), + + path('api/artistas/', api_lista_artistas, name='api_lista_artistas'), + path('api/artistas//', api_detalle_artista, name='api_detalle_artista'), + + path('api/albumes/', api_lista_albumes, name='api_lista_albumes'), + path('api/albumes//', api_detalle_album, name='api_detalle_album'), + + path('api/canciones/', api_lista_canciones, name='api_lista_canciones'), + path('api/canciones//', api_detalle_cancion, name='api_detalle_cancion'), ] diff --git a/ReyMotaAppsDj/reymota/lyrics/views.py b/ReyMotaAppsDj/reymota/lyrics/views.py index 9c1ab61..1b6b5d7 100644 --- a/ReyMotaAppsDj/reymota/lyrics/views.py +++ b/ReyMotaAppsDj/reymota/lyrics/views.py @@ -2,8 +2,12 @@ from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required +from rest_framework.response import Response +from rest_framework.decorators import api_view + from .models import Artista, Album, Song from .forms import ArtistaForm, AlbumForm, SongForm +from .serializers import ArtistaSerializer, AlbumSerializer, CancionSerializer import logging logger = logging.getLogger(__name__) @@ -188,3 +192,60 @@ def eliminar_song(request, song_id): song = get_object_or_404(Song, pk=song_id) song.delete() return redirect('lyrics:lista_songs') + + +@api_view(['GET']) +def api_lista_artistas(request): + """Devuelve la lista de todos los artistas.""" + artistas = Artista.objects.all() + serializer = ArtistaSerializer(artistas, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_artista(request, artista_id): + """Devuelve los detalles de un artista específico.""" + try: + artista = Artista.objects.get(id=artista_id) + serializer = ArtistaSerializer(artista) + return Response(serializer.data) + except Artista.DoesNotExist: + return Response({'error': 'Artista no encontrado'}, status=404) + + +@api_view(['GET']) +def api_lista_albumes(request): + """Devuelve la lista de todos los albumes.""" + albumes = Album.objects.all() + serializer = AlbumSerializer(albumes, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_album(request, album_id): + """Devuelve los detalles de un album específico.""" + try: + album = Album.objects.get(id=album_id) + serializer = AlbumSerializer(album) + return Response(serializer.data) + except Album.DoesNotExist: + return Response({'error': 'Album no encontrado'}, status=404) + + +@api_view(['GET']) +def api_lista_canciones(request): + """Devuelve la lista de todos los canciones.""" + canciones = Song.objects.all() + serializer = CancionSerializer(canciones, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_cancion(request, cancion_id): + """Devuelve los detalles de un cancion específica.""" + try: + cancion = Song.objects.get(id=cancion_id) + serializer = CancionSerializer(cancion) + return Response(serializer.data) + except Song.DoesNotExist: + return Response({'error': 'Canción no encontrada'}, status=404)