Browse Source

Añado api a jugaralpadel

politica
Celestino Rey 10 months ago
parent
commit
bda608314c
19 changed files with 446 additions and 4 deletions
  1. +2
    -1
      JugarAlPadel/K8S/Makefile
  2. +2
    -2
      JugarAlPadel/K8S/env-prod-configmap.yaml
  3. +31
    -0
      JugarAlPadel/K8S/jugaralpadel-ingress.yaml
  4. +1
    -1
      JugarAlPadel/K8S/namespace.yaml
  5. +0
    -0
      JugarAlPadel/gestion_reservas/eventos/management/__init__.py
  6. +0
    -0
      JugarAlPadel/gestion_reservas/eventos/management/commands/__init__.py
  7. +45
    -0
      JugarAlPadel/gestion_reservas/eventos/management/commands/importar_eventos.py
  8. +49
    -0
      JugarAlPadel/gestion_reservas/eventos/management/commands/importar_listaespera.py
  9. +49
    -0
      JugarAlPadel/gestion_reservas/eventos/management/commands/importar_noticias.py
  10. +50
    -0
      JugarAlPadel/gestion_reservas/eventos/management/commands/importar_reservas.py
  11. +26
    -0
      JugarAlPadel/gestion_reservas/eventos/serializers.py
  12. +17
    -0
      JugarAlPadel/gestion_reservas/eventos/urls.py
  13. +83
    -0
      JugarAlPadel/gestion_reservas/eventos/views.py
  14. +0
    -0
      JugarAlPadel/gestion_reservas/reymotausers/management/__init__.py
  15. +0
    -0
      JugarAlPadel/gestion_reservas/reymotausers/management/commands/__init__.py
  16. +48
    -0
      JugarAlPadel/gestion_reservas/reymotausers/management/commands/importar_usuarios.py
  17. +8
    -0
      JugarAlPadel/gestion_reservas/reymotausers/serializers.py
  18. +9
    -0
      JugarAlPadel/gestion_reservas/reymotausers/urls.py
  19. +26
    -0
      JugarAlPadel/gestion_reservas/reymotausers/views.py

+ 2
- 1
JugarAlPadel/K8S/Makefile View File

@ -2,7 +2,7 @@ export ARQUITECTURA := $(shell lscpu |grep itectur | tr -d ' '| cut -f2 -d':')
#export REGISTRY=localhost:5000
export REGISTRY=registry.reymota.es
export IMG_VERSION = 0.44
export IMG_VERSION = 0.47
export IMG_NGINX_VERSION = 2.3
# limpia todo
@ -28,6 +28,7 @@ install:
-envsubst < jugaralpadel-deployment.yaml |kubectl create -f -
-envsubst < nginx-deployment.yaml |kubectl create -f -
-kubectl create -f nginx-service.yaml
-kubectl create -f jugaralpadel-ingress.yaml
clean:
-envsubst < nginx-deployment.yaml |kubectl delete -f -


+ 2
- 2
JugarAlPadel/K8S/env-prod-configmap.yaml View File

@ -2,8 +2,8 @@ apiVersion: v1
data:
DEBUG: "False"
ENTORNO: "Producción"
DJANGO_ALLOWED_HOSTS: "jugaralpadel.es jugaralpadel.ddns.net vmcluster k8s-server localhost 127.0.0.1 [::1]"
CSRF_TRUSTED_ORIGINS: "https://jugaralpadel.ddns.net https://jugaralpadel.es http://vmcluster"
DJANGO_ALLOWED_HOSTS: "jugaralpadel.rancher.my.org jugaralpadel.es jugaralpadel.ddns.net vmcluster k8s-server localhost 127.0.0.1 [::1]"
CSRF_TRUSTED_ORIGINS: "http://jugaralpadel.rancher.my.org https://jugaralpadel.ddns.net https://jugaralpadel.es http://vmcluster"
SECRET_KEY: change_me
SQL_DATABASE: jugaralpadel
SQL_ENGINE: django.db.backends.postgresql


+ 31
- 0
JugarAlPadel/K8S/jugaralpadel-ingress.yaml View File

@ -0,0 +1,31 @@
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
generation: 1
managedFields:
- apiVersion: networking.k8s.io/v1
fieldsType: FieldsV1
fieldsV1:
f:spec:
f:defaultBackend:
.: {}
f:service:
.: {}
f:name: {}
f:port: {}
f:rules: {}
manager: rancher
operation: Update
name: jugaralpadel
namespace: jugaralpadel
spec:
defaultBackend:
service:
name: nginx
port:
number: 1337
ingressClassName: nginx
rules:
- host: jugaralpadel.rancher.my.org
status:
loadBalancer: {}

+ 1
- 1
JugarAlPadel/K8S/namespace.yaml View File

@ -1,5 +1,5 @@
###################################################
# Namespace Vehículos
# Namespace jugaralpadel
###################################################
apiVersion: v1
kind: Namespace


+ 0
- 0
JugarAlPadel/gestion_reservas/eventos/management/__init__.py View File


+ 0
- 0
JugarAlPadel/gestion_reservas/eventos/management/commands/__init__.py View File


+ 45
- 0
JugarAlPadel/gestion_reservas/eventos/management/commands/importar_eventos.py View File

@ -0,0 +1,45 @@
import json
from django.core.management.base import BaseCommand
from repostajes.models import Evento
class Command(BaseCommand):
help = "Importa eventos 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)} eventos 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
eventos_creados = 0
for evento_data in datos:
creado = Evento.objects.create(
id=evento_data['id'],
nombre=evento_data['nombre'],
descripcion=evento_data['descripcion'],
fecha=evento_data['fecha'],
plazas_disponibles=evento_data['plazas_disponibles'],
pubicado=evento_data['pubicado'],
url_imagen=evento_data['url_imagen']
)
if creado:
eventos_creados += 1
self.stdout.write(self.style.SUCCESS(f'Se importaron {eventos_creados} eventos 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."))

+ 49
- 0
JugarAlPadel/gestion_reservas/eventos/management/commands/importar_listaespera.py View File

@ -0,0 +1,49 @@
import json
from django.core.management.base import BaseCommand
from eventos.models import ListaEspera, Evento
from reymotausers.models import ReyMotaUser
class Command(BaseCommand):
help = "Importa listaesperas 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)} listaesperas 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
listaesperas_creados = 0
for listaespera_data in datos:
try:
evento = Evento.objects.get(id=listaespera_data["evento"])
usuario = ReyMotaUser.objects.get(id=listaespera_data["usuario"])
creado = ListaEspera.objects.create(
evento_id=evento.id,
usuario_id=usuario.id,
fecha_apuntado=listaespera_data['fecha_apuntado'],
)
if creado:
listaesperas_creados += 1
except Evento.DoesNotExist:
self.stderr.write(self.style.ERROR(f"Evento '{listaespera_data['evento']}' no encontrado."))
self.stdout.write(self.style.SUCCESS(f'Se importaron {listaesperas_creados} listaesperas 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."))

+ 49
- 0
JugarAlPadel/gestion_reservas/eventos/management/commands/importar_noticias.py View File

@ -0,0 +1,49 @@
import json
from django.core.management.base import BaseCommand
from eventos.models import Noticia
from reymotausers.models import ReyMotaUser
class Command(BaseCommand):
help = "Importa noticias 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)} noticias 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
noticias_creados = 0
for noticia_data in datos:
try:
usuario = ReyMotaUser.objects.get(id=noticia_data["usuario"])
creado = Noticia.objects.create(
autor_id=usuario.id,
titulo=noticia_data['titulo'],
fecha_publicacion=noticia_data['fecha_publicacion'],
publicado=noticia_data['publicado']
)
if creado:
noticias_creados += 1
except ReyMotaUser.DoesNotExist:
self.stderr.write(self.style.ERROR(f"Usuario '{noticia_data['usuario']}' no encontrado."))
self.stdout.write(self.style.SUCCESS(f'Se importaron {noticias_creados} noticias 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."))

+ 50
- 0
JugarAlPadel/gestion_reservas/eventos/management/commands/importar_reservas.py View File

@ -0,0 +1,50 @@
import json
from django.core.management.base import BaseCommand
from eventos.models import Reserva, Evento
from reymotausers.models import ReyMotaUser
class Command(BaseCommand):
help = "Importa reservas 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)} reservas 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
reservas_creados = 0
for reserva_data in datos:
try:
evento = Evento.objects.get(id=reserva_data["evento"])
usuario = ReyMotaUser.objects.get(id=reserva_data["usuario"])
creado = Reserva.objects.create(
evento_id=evento.id,
usuario_id=usuario.id,
fecha_reserva=reserva_data['fecha_reserva'],
evento=reserva_data['evento']
)
if creado:
reservas_creados += 1
except Evento.DoesNotExist:
self.stderr.write(self.style.ERROR(f"Evento '{reserva_data['evento']}' no encontrado."))
self.stdout.write(self.style.SUCCESS(f'Se importaron {reservas_creados} reservas 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."))

+ 26
- 0
JugarAlPadel/gestion_reservas/eventos/serializers.py View File

@ -0,0 +1,26 @@
from rest_framework import serializers
from .models import Evento, Reserva, ListaEspera, Noticia
class EventoSerializer(serializers.ModelSerializer):
class Meta:
model = Evento
fields = '__all__' # Incluir todos los campos del modelo
class ReservaSerializer(serializers.ModelSerializer):
class Meta:
model = Reserva
fields = '__all__' # Incluir todos los campos del modelo
class ListaEsperaSerializer(serializers.ModelSerializer):
class Meta:
model = ListaEspera
fields = '__all__' # Incluir todos los campos del modelo
class NoticiaSerializer(serializers.ModelSerializer):
class Meta:
model = Noticia
fields = '__all__' # Incluir todos los campos del modelo

+ 17
- 0
JugarAlPadel/gestion_reservas/eventos/urls.py View File

@ -1,6 +1,11 @@
from django.urls import path
from . import views
from .views import api_lista_eventos, api_detalle_evento
from .views import api_lista_reservas, api_detalle_reserva
from .views import api_lista_listaespera, api_detalle_listaespera
from .views import api_lista_noticias, api_detalle_noticia
app_name = 'eventos'
urlpatterns = [
@ -17,4 +22,16 @@ urlpatterns = [
path('reservar/<int:evento_id>/',
views.reservar_evento, name='reservar_evento'),
path('api/eventos/', api_lista_eventos, name='api_lista_eventos'),
path('api/eventos/<int:evento_id>/', api_detalle_evento, name='api_detalle_evento'),
path('api/reservas/', api_lista_reservas, name='api_lista_reservas'),
path('api/reservas/<int:reserva_id>/', api_detalle_reserva, name='api_detalle_reserva'),
path('api/listaespera/', api_lista_listaespera, name='api_lista_listaespera'),
path('api/listaespera/<int:listaespera_id>/', api_detalle_listaespera, name='api_detalle_listaespera'),
path('api/noticias/', api_lista_noticias, name='api_lista_noticias'),
path('api/noticias/<int:noticia_id>/', api_detalle_noticia, name='api_detalle_noticia'),
]

+ 83
- 0
JugarAlPadel/gestion_reservas/eventos/views.py View File

@ -6,6 +6,9 @@ from django.conf import settings
from django.template.loader import render_to_string
from django.utils import timezone
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import EventoSerializer, ReservaSerializer, ListaEsperaSerializer, NoticiaSerializer
from .models import Evento, Reserva, ListaEspera, Noticia
from .forms import ListaEsperaForm, EventoForm
@ -209,3 +212,83 @@ def apuntar_lista_espera(request, evento_id):
form = ListaEsperaForm()
return render(request, 'eventos/apuntar_lista_espera.html', {'form': form, 'evento': evento})
#
# API
#
@api_view(['GET'])
def api_lista_eventos(request):
"""Devuelve la lista de todos los eventos."""
eventos = Evento.objects.all()
serializer = EventoSerializer(eventos, many=True)
return Response(serializer.data)
@api_view(['GET'])
def api_detalle_evento(request, evento_id):
"""Devuelve los detalles de un evento específico."""
try:
evento = Evento.objects.get(id=evento_id)
serializer = EventoSerializer(evento)
return Response(serializer.data)
except Evento.DoesNotExist:
return Response({'error': 'Evento no encontrado'}, status=404)
@api_view(['GET'])
def api_lista_reservas(request):
"""Devuelve la lista de todos los reservas."""
reservas = Reserva.objects.all()
serializer = ReservaSerializer(reservas, many=True)
return Response(serializer.data)
@api_view(['GET'])
def api_detalle_reserva(request, reserva_id):
"""Devuelve los detalles de un reserva específico."""
try:
reserva = Reserva.objects.get(id=reserva_id)
serializer = ReservaSerializer(reserva)
return Response(serializer.data)
except Reserva.DoesNotExist:
return Response({'error': 'Reserva no encontrado'}, status=404)
@api_view(['GET'])
def api_lista_listaespera(request):
"""Devuelve la lista de todos los listaespera."""
listaesperas = ListaEspera.objects.all()
serializer = ListaEsperaSerializer(listaesperas, many=True)
return Response(serializer.data)
@api_view(['GET'])
def api_detalle_listaespera(request, listaespera_id):
"""Devuelve los detalles de un listaespera específico."""
try:
listaespera = ListaEspera.objects.get(id=listaespera_id)
serializer = ListaEsperaSerializer(listaespera)
return Response(serializer.data)
except ListaEspera.DoesNotExist:
return Response({'error': 'ListaEspera no encontrado'}, status=404)
@api_view(['GET'])
def api_lista_noticias(request):
"""Devuelve la lista de todos los noticias."""
noticias = Noticia.objects.all()
serializer = NoticiaSerializer(noticias, many=True)
return Response(serializer.data)
@api_view(['GET'])
def api_detalle_noticia(request, noticia_id):
"""Devuelve los detalles de un noticia específico."""
try:
noticia = Noticia.objects.get(id=noticia_id)
serializer = NoticiaSerializer(noticia)
return Response(serializer.data)
except Noticia.DoesNotExist:
return Response({'error': 'Noticia no encontrado'}, status=404)

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


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


+ 48
- 0
JugarAlPadel/gestion_reservas/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."))

+ 8
- 0
JugarAlPadel/gestion_reservas/reymotausers/serializers.py View File

@ -0,0 +1,8 @@
from rest_framework import serializers
from .models import ReyMotaUser
class ReyMotaUserSerializer(serializers.ModelSerializer):
class Meta:
model = ReyMotaUser
fields = '__all__' # Incluir todos los campos del modelo

+ 9
- 0
JugarAlPadel/gestion_reservas/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
JugarAlPadel/gestion_reservas/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