Browse Source

Api para obtención de datos y comandos de importación

main
Celestino Rey 10 months ago
parent
commit
990afd1bba
18 changed files with 443 additions and 0 deletions
  1. +0
    -0
      lyrics/management/__init__.py
  2. +48
    -0
      lyrics/management/commands/importar_albumes.py
  3. +42
    -0
      lyrics/management/commands/importar_artistas.py
  4. +51
    -0
      lyrics/management/commands/importar_canciones.py
  5. +12
    -0
      lyrics/urls.py
  6. +61
    -0
      lyrics/views.py
  7. +0
    -0
      repostajes/management/__init__.py
  8. +0
    -0
      repostajes/management/commands/__init__.py
  9. +53
    -0
      repostajes/management/commands/importar_repostajes.py
  10. +43
    -0
      repostajes/management/commands/importar_vehiculos.py
  11. +6
    -0
      repostajes/urls.py
  12. +42
    -0
      repostajes/views.py
  13. +2
    -0
      reymota/urls.py
  14. +0
    -0
      reymotausers/management/__init__.py
  15. +0
    -0
      reymotausers/management/commands/__init__.py
  16. +48
    -0
      reymotausers/management/commands/importar_usuarios.py
  17. +9
    -0
      reymotausers/urls.py
  18. +26
    -0
      reymotausers/views.py

+ 0
- 0
lyrics/management/__init__.py View File


+ 48
- 0
lyrics/management/commands/importar_albumes.py View File

@ -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."))

+ 42
- 0
lyrics/management/commands/importar_artistas.py View File

@ -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."))

+ 51
- 0
lyrics/management/commands/importar_canciones.py View File

@ -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."))

+ 12
- 0
lyrics/urls.py View File

@ -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/<int:song_id>/', views.detalle_song, name='detalle_song'),
path('song/<int:song_id>/editar/', views.editar_song, name='editar_song'),
path('song/<int:song_id>/eliminar/', views.eliminar_song, name='eliminar_song'),
path('api/artistas/', api_lista_artistas, name='api_lista_artistas'),
path('api/artistas/<int:artista_id>/', api_detalle_artista, name='api_detalle_artista'),
path('api/albumes/', api_lista_albumes, name='api_lista_albumes'),
path('api/albumes/<int:album_id>/', api_detalle_album, name='api_detalle_album'),
path('api/canciones/', api_lista_canciones, name='api_lista_canciones'),
path('api/canciones/<int:cancion_id>/', api_detalle_cancion, name='api_detalle_cancion'),
]

+ 61
- 0
lyrics/views.py View File

@ -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)

+ 0
- 0
repostajes/management/__init__.py View File


+ 0
- 0
repostajes/management/commands/__init__.py View File


+ 53
- 0
repostajes/management/commands/importar_repostajes.py View File

@ -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."))

+ 43
- 0
repostajes/management/commands/importar_vehiculos.py View File

@ -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."))

+ 6
- 0
repostajes/urls.py View File

@ -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/<int:repostaje_id>/', views.detalle_repostaje, name='detalle_repostaje'),
path('repostajes/<int:repostaje_id>/editar/', views.editar_repostaje, name='editar_repostaje'),
path('repostajes/<int:repostaje_id>/eliminar/', views.eliminar_repostaje, name='eliminar_repostaje'),
path('api/vehiculos/', api_lista_vehiculos, name='api_lista_vehiculos'),
path('api/vehiculos/<int:vehiculo_id>/', api_detalle_vehiculo, name='api_detalle_vehiculo'),
path('api/repostajes/', api_lista_repostajes, name='api_lista_repostajes'),
path('api/repostajes/<int:repostaje_id>/', api_detalle_repostaje, name='api_detalle_repostaje'),
]

+ 42
- 0
repostajes/views.py View File

@ -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)

+ 2
- 0
reymota/urls.py View File

@ -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)

+ 0
- 0
reymotausers/management/__init__.py View File


+ 0
- 0
reymotausers/management/commands/__init__.py View File


+ 48
- 0
reymotausers/management/commands/importar_usuarios.py View File

@ -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."))

+ 9
- 0
reymotausers/urls.py View File

@ -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/<int:usuario_id>/', api_detalle_usuario, name='api_detalle_usuario'),
]

+ 26
- 0
reymotausers/views.py View File

@ -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)

Loading…
Cancel
Save