diff --git a/app/libros/urls.py b/app/libros/urls.py new file mode 100644 index 0000000..8afa40c --- /dev/null +++ b/app/libros/urls.py @@ -0,0 +1,10 @@ +# app/libros/urls.py + +from django.urls import path +from app.libros.views import ping, LibrosList + + +urlpatterns = [ + path("ping/", ping, name="ping"), + path("api/libros/", LibrosList.as_view()), +] \ No newline at end of file diff --git a/app/libros/views.py b/app/libros/views.py index 5178c63..c840f93 100644 --- a/app/libros/views.py +++ b/app/libros/views.py @@ -1,11 +1,22 @@ +# app/libros/views.py + from django.http import JsonResponse -from django.http import JsonResponse +from rest_framework.views import APIView # nuevo +from rest_framework.response import Response # nuevo +from rest_framework import status # nuevo +from .serializers import LibroSerializer # nuevo def ping(request): data = {"ping": "pong!"} return JsonResponse(data) -def ping(request): - data = {"ping": "pong!"} - return JsonResponse(data) \ No newline at end of file + +class LibrosList(APIView): + + def post(self, request): + serializer = LibroSerializer(data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) \ No newline at end of file diff --git a/proyecto/urls.py b/proyecto/urls.py index 4170ec6..e880062 100644 --- a/proyecto/urls.py +++ b/proyecto/urls.py @@ -1,10 +1,9 @@ +# proyecto/urls.py + from django.contrib import admin -from django.urls import path - -from app.libros.views import ping - +from django.urls import path, include urlpatterns = [ - path('admin/', admin.site.urls), - path('ping/', ping, name="ping"), + path("admin/", admin.site.urls), + path("", include("app.libros.urls")), ] \ No newline at end of file diff --git a/tests/libros/test_views.py b/tests/libros/test_views.py new file mode 100644 index 0000000..e20a632 --- /dev/null +++ b/tests/libros/test_views.py @@ -0,0 +1,30 @@ +# tests/libros/test_views.py + +import pytest +from app.libros.models import Libros + + +@pytest.mark.django_db +def test_add_movie(client): + # Given + libros = Libros.objects.all() + assert len(libros) == 0 + + # When + resp = client.post( + "/api/libros/", + { + "title": "El fin de la eternidad", + "genre": "Ciencia Ficción", + "author": "Isaac Asimov", + "year": "1955", + }, + content_type="application/json" + ) + + # Then + assert resp.status_code == 201 + assert resp.data["title"] == "El fin de la eternidad" + + libros = Libros.objects.all() + assert len(libros) == 1 \ No newline at end of file diff --git a/tests/libros/test_ejemplo.py b/tests/test_ejemplo.py similarity index 100% rename from tests/libros/test_ejemplo.py rename to tests/test_ejemplo.py diff --git a/tests/libros/test_ping.py b/tests/test_ping.py similarity index 100% rename from tests/libros/test_ping.py rename to tests/test_ping.py