diff --git a/lyrics/management/__init__.py b/lyrics/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lyrics/management/commands/importar_albumes.py b/lyrics/management/commands/importar_albumes.py new file mode 100644 index 0000000..e748e15 --- /dev/null +++ b/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( + artist_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/lyrics/management/commands/importar_artistas.py b/lyrics/management/commands/importar_artistas.py new file mode 100644 index 0000000..a027340 --- /dev/null +++ b/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/lyrics/management/commands/importar_canciones.py b/lyrics/management/commands/importar_canciones.py new file mode 100644 index 0000000..7856e40 --- /dev/null +++ b/lyrics/management/commands/importar_canciones.py @@ -0,0 +1,51 @@ +import json +from django.core.management.base import BaseCommand +from lyrics.models import Song, Album, Artista + + +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"]) + artista = Artista.objects.get(id=cancion_data["artist"]) + + creado = Song.objects.create( + album_id=album.id, + title=cancion_data['title'], + artist_id=artista.id, + 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/lyrics/urls.py b/lyrics/urls.py index dc60b53..a931c57 100644 --- a/lyrics/urls.py +++ b/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/lyrics/views.py b/lyrics/views.py index 9c1ab61..1b6b5d7 100644 --- a/lyrics/views.py +++ b/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) diff --git a/repostajes/management/__init__.py b/repostajes/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/repostajes/management/commands/__init__.py b/repostajes/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/repostajes/management/commands/importar_repostajes.py b/repostajes/management/commands/importar_repostajes.py new file mode 100644 index 0000000..e3bccd1 --- /dev/null +++ b/repostajes/management/commands/importar_repostajes.py @@ -0,0 +1,53 @@ +import json +from django.core.management.base import BaseCommand +from repostajes.models import Repostaje, Vehiculo + + +class Command(BaseCommand): + help = "Importa repostajes 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)} repostajes 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 + + repostajes_creados = 0 + for repostaje_data in datos: + try: + vehiculo = Vehiculo.objects.get(id=repostaje_data["vehiculo"]) + + creado = Repostaje.objects.create( + vehiculo_id=vehiculo.id, + fecha=repostaje_data['fecha'], + kms=repostaje_data['kms'], + litros=repostaje_data['litros'], + descuento=repostaje_data['descuento'], + importe=repostaje_data['importe'], + precioxlitro=repostaje_data['precioxlitro'], + kmsrecorridos=repostaje_data['kmsrecorridos'], + consumo=repostaje_data['consumo'] + ) + if creado: + repostajes_creados += 1 + + except Vehiculo.DoesNotExist: + self.stderr.write(self.style.ERROR(f"Vehiculo '{repostaje_data['vehiculo']}' no encontrado.")) + + self.stdout.write(self.style.SUCCESS(f'Se importaron {repostajes_creados} repostajes 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/repostajes/management/commands/importar_vehiculos.py b/repostajes/management/commands/importar_vehiculos.py new file mode 100644 index 0000000..861cf2c --- /dev/null +++ b/repostajes/management/commands/importar_vehiculos.py @@ -0,0 +1,43 @@ +import json +from django.core.management.base import BaseCommand +from repostajes.models import Vehiculo + + +class Command(BaseCommand): + help = "Importa vehiculos 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)} vehiculos 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 + + vehiculos_creados = 0 + for vehiculo_data in datos: + creado = Vehiculo.objects.create( + id=vehiculo_data['id'], + marca=vehiculo_data['marca'], + modelo=vehiculo_data['modelo'], + matricula=vehiculo_data['matricula'], + foto=vehiculo_data['foto'] + ) + if creado: + vehiculos_creados += 1 + + self.stdout.write(self.style.SUCCESS(f'Se importaron {vehiculos_creados} vehiculos 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/repostajes/urls.py b/repostajes/urls.py index 0b5ba04..578548a 100644 --- a/repostajes/urls.py +++ b/repostajes/urls.py @@ -1,6 +1,8 @@ from django.urls import path from . import views +from .views import api_lista_vehiculos, api_detalle_vehiculo +from .views import api_lista_repostajes, api_detalle_repostaje app_name = 'repostajes' @@ -17,4 +19,8 @@ urlpatterns = [ path('repostajes//', views.detalle_repostaje, name='detalle_repostaje'), path('repostajes//editar/', views.editar_repostaje, name='editar_repostaje'), path('repostajes//eliminar/', views.eliminar_repostaje, name='eliminar_repostaje'), + path('api/vehiculos/', api_lista_vehiculos, name='api_lista_vehiculos'), + path('api/vehiculos//', api_detalle_vehiculo, name='api_detalle_vehiculo'), + path('api/repostajes/', api_lista_repostajes, name='api_lista_repostajes'), + path('api/repostajes//', api_detalle_repostaje, name='api_detalle_repostaje'), ] diff --git a/repostajes/views.py b/repostajes/views.py index 29c6800..bb82618 100644 --- a/repostajes/views.py +++ b/repostajes/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 Vehiculo, Repostaje from .forms import VehiculoForm, RepostajeForm +from .serializers import VehiculoSerializer, RepostajeSerializer @login_required @@ -143,3 +147,41 @@ def eliminar_repostaje(request, repostaje_id): repostaje = Repostaje.objects.get(pk=repostaje_id) repostaje.delete() return redirect('repostajes:lista_repostajes') + + +@api_view(['GET']) +def api_lista_vehiculos(request): + """Devuelve la lista de todos los vehiculos.""" + vehiculos = Vehiculo.objects.all() + serializer = VehiculoSerializer(vehiculos, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_vehiculo(request, vehiculo_id): + """Devuelve los detalles de un vehiculo específico.""" + try: + vehiculo = Vehiculo.objects.get(id=vehiculo_id) + serializer = VehiculoSerializer(vehiculo) + return Response(serializer.data) + except Vehiculo.DoesNotExist: + return Response({'error': 'Vehiculo no encontrado'}, status=404) + + +@api_view(['GET']) +def api_lista_repostajes(request): + """Devuelve la lista de todos los repostajes.""" + repostajes = Repostaje.objects.all() + serializer = RepostajeSerializer(repostajes, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_repostaje(request, repostaje_id): + """Devuelve los detalles de un repostaje específico.""" + try: + repostaje = Repostaje.objects.get(id=repostaje_id) + serializer = RepostajeSerializer(repostaje) + return Response(serializer.data) + except Repostaje.DoesNotExist: + return Response({'error': 'Repostaje no encontrado'}, status=404) diff --git a/reymota/urls.py b/reymota/urls.py index a8e1cc8..de553ca 100644 --- a/reymota/urls.py +++ b/reymota/urls.py @@ -38,4 +38,6 @@ urlpatterns = [ path('entorno/', views.ver_variables_entorno, name='ver_variables_entorno'), + path('usuarios/', include("reymotausers.urls")), + ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/reymotausers/management/__init__.py b/reymotausers/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/reymotausers/management/commands/__init__.py b/reymotausers/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/reymotausers/management/commands/importar_usuarios.py b/reymotausers/management/commands/importar_usuarios.py new file mode 100644 index 0000000..bfe07ce --- /dev/null +++ b/reymotausers/management/commands/importar_usuarios.py @@ -0,0 +1,48 @@ +import json +from django.core.management.base import BaseCommand +from reymotausers.models import ReyMotaUser + + +class Command(BaseCommand): + help = "Importa usuarios 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)} usuarios 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 + + usuarios_creados = 0 + for usuario_data in datos: + creado = ReyMotaUser.objects.create( + foto=usuario_data['foto'], + password=usuario_data['password'], + is_superuser=usuario_data['is_superuser'], + is_staff=usuario_data['is_staff'], + is_active=usuario_data['is_active'], + nombre=usuario_data['nombre'], + email=usuario_data['email'], + groups=usuario_data['groups'], + user_permissions=usuario_data['user_permissions'], + last_login=usuario_data['last_login'] + ) + if creado: + usuarios_creados += 1 + + self.stdout.write(self.style.SUCCESS(f'Se importaron {usuarios_creados} usuarios 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/reymotausers/urls.py b/reymotausers/urls.py new file mode 100644 index 0000000..3207722 --- /dev/null +++ b/reymotausers/urls.py @@ -0,0 +1,9 @@ +from django.urls import path + +from . import views +from .views import api_lista_usuarios, api_detalle_usuario + +urlpatterns = [ + path('api/usuarios/', api_lista_usuarios, name='api_lista_usuarios'), + path('api/usuarios//', api_detalle_usuario, name='api_detalle_usuario'), +] diff --git a/reymotausers/views.py b/reymotausers/views.py index 91ea44a..0f86359 100644 --- a/reymotausers/views.py +++ b/reymotausers/views.py @@ -1,3 +1,29 @@ from django.shortcuts import render +from rest_framework.response import Response +from rest_framework.decorators import api_view + +from .serializers import ReyMotaUserSerializer + +from .models import ReyMotaUser + # Create your views here. + + +@api_view(['GET']) +def api_lista_usuarios(request): + """Devuelve la lista de todos los usuarios.""" + usuarios = ReyMotaUser.objects.all() + serializer = ReyMotaUserSerializer(usuarios, many=True) + return Response(serializer.data) + + +@api_view(['GET']) +def api_detalle_usuario(request, usuario_id): + """Devuelve los detalles de un usuario específico.""" + try: + usuario = ReyMotaUser.objects.get(id=usuario_id) + serializer = ReyMotaUserSerializer(usuario) + return Response(serializer.data) + except ReyMotaUser.DoesNotExist: + return Response({'error': 'Canción no encontrada'}, status=404)