Start recipe app. Api serializers, views & urls

This commit is contained in:
devfzn 2023-10-09 03:25:09 -03:00
parent f4c53c0718
commit ba46c42fa7
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
12 changed files with 319 additions and 1 deletions

View File

@ -115,3 +115,171 @@ Migrations for 'core':
core/migrations/0002_recipe.py
- Create model Recipe
```
## Creación de app recipe
`docker compose run --rm app sh -c "python manage.py startapp recipe"`
```sh
[+] Creating 1/0
✔ Container recipes_api_django-db-1 Running 0.0s
```
- Se eliminan, directorio `migrations`, `test.py`, `admin.py` `models.py`
- Se crean directorio `reicpes/tests/` y su respecto `__init__.py`
- Añadir app `recipe` en [settings.py](./app/app/settings.py)
```py
INSTALLED_APPS = [
...
'recipe',
]
```
### Tests recipe API
[`recipe/tests/test_recipe_api.py`](./app/recipe/tests/test_recipe_api.py)
```py
...
RECIPES_URL = reverse('recipe:recipe-list')
def create_recipe(user, **params):
"""Create and return a sample recipe."""
defaults = {
'title': 'Titulo reseta de ejemplo',
'time_minutes': 31,
'price': Decimal('5.25'),
'description': 'Descripción de ejmplo',
'link': 'https://defzn.kickto.net/blog',
}
defaults.update(params)
recipe = Recipe.objects.create(user=user, **defaults)
return recipe
class PublicRecipeApiTests(TestCase):
"""Test unauthenticated API requests."""
def setUp(self):
self.client = APIClient()
def test_auth_required(self):
"""Test auth is required to call API."""
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateRecipeApiTests(TestCase):
"""Test authenticated API requests."""
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_user(
'user@example.com',
'testpass123',
)
self.client.force_authenticate(self.user)
def test_retrive_recipes(self):
"""Test retrieving a list of recipes."""
create_recipe(user=self.user)
create_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_recipe_list_limited_to_user(self):
"""Test list of recipes is limited to authenticated user."""
other_user = get_user_model().objects.create_user(
'other@example.com',
'password123',
)
create_recipe(user=other_user)
create_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
```
### Serializador para Recetas
[`recipe/serializer.py`](./app/recipe/serializers.py)
```py
from rest_framework import serializers
from core.models import Recipe
class RecipeSerializer(serializers.ModelSerializer):
"""Serializer for recipes."""
class Meta:
model = Recipe
fileds = ['id', 'title', 'time_minutes', 'price', 'link']
read_only_fields = ['id']
```
### Vista Recetas
[`recipe/views.py`](./app/recipe/views.py)
```py
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Recipe
from recipe import serializers
class RecipeViewSet(viewsets.ModelViewSet):
"""View for manage recipe APIs."""
serializer_class = serializers.RecipeSerializer
queryset = Recipe.objects.all()
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""Retrieve recipes for authenticated user."""
return self.queryset.filter(user=self.request.user).order_by('-id')
```
### URLs Recetas
[`recipe/urls.py`](./app/recipe/urls.py)
```py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from recipe import views
router = DefaultRouter()
router.register('recipes', views.RecipeViewSet)
app_name = 'recipe'
urlpatterns = [
path('', include(router.urls)),
]
```
[`app/urls.py`](./app/app/urls.py)
```py
...
urlpatterns = [
...
path('api/recipe', include('recipe.urls')),
]
```

View File

@ -42,6 +42,7 @@ INSTALLED_APPS = [
'rest_framework.authtoken',
'drf_spectacular',
'user',
'recipe',
]
MIDDLEWARE = [

View File

@ -26,4 +26,5 @@ urlpatterns = [
SpectacularSwaggerView.as_view(url_name='api-schema'),
name='api-docs'),
path('api/user/', include('user.urls')),
path('api/recipe', include('recipe.urls')),
]

View File

@ -8,6 +8,7 @@ from django.contrib.auth import get_user_model
from core import models
class ModelTests(TestCase):
"""Test models."""

0
app/recipe/__init__.py Normal file
View File

6
app/recipe/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class RecipeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'recipe'

15
app/recipe/serializers.py Normal file
View File

@ -0,0 +1,15 @@
"""
Serializers for recipe APIs
"""
from rest_framework import serializers
from core.models import Recipe
class RecipeSerializer(serializers.ModelSerializer):
"""Serializer for recipes."""
class Meta:
model = Recipe
fields = ['id', 'title', 'time_minutes', 'price', 'link']
read_only_fields = ['id']

View File

View File

@ -0,0 +1,87 @@
"""
Test for reicpe APIs.
"""
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase
from django. urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Recipe
from recipe.serializers import RecipeSerializer
RECIPES_URL = reverse('recipe:recipe-list')
def create_recipe(user, **params):
"""Create and return a sample recipe."""
defaults = {
'title': 'Titulo reseta de ejemplo',
'time_minutes': 31,
'price': Decimal('5.25'),
'description': 'Descripción de ejmplo',
'link': 'https://defzn.kickto.net/blog',
}
defaults.update(params)
recipe = Recipe.objects.create(user=user, **defaults)
return recipe
class PublicRecipeApiTests(TestCase):
"""Test unauthenticated API requests."""
def setUp(self):
self.client = APIClient()
def test_auth_required(self):
"""Test auth is required to call API."""
res = self.client.get(RECIPES_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateRecipeApiTests(TestCase):
"""Test authenticated API requests."""
def setUp(self):
self.client = APIClient()
self.user = get_user_model().objects.create_user(
'user@example.com',
'testpass123',
)
self.client.force_authenticate(self.user)
def test_retrive_recipes(self):
"""Test retrieving a list of recipes."""
create_recipe(user=self.user)
create_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.all().order_by('-id')
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_recipe_list_limited_to_user(self):
"""Test list of recipes is limited to authenticated user."""
other_user = get_user_model().objects.create_user(
'other@example.com',
'password123',
)
create_recipe(user=other_user)
create_recipe(user=self.user)
res = self.client.get(RECIPES_URL)
recipes = Recipe.objects.filter(user=self.user)
serializer = RecipeSerializer(recipes, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)

18
app/recipe/urls.py Normal file
View File

@ -0,0 +1,18 @@
"""
URL mappings for the recipe app.
"""
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from recipe import views
router = DefaultRouter()
router.register('recipes', views.RecipeViewSet)
app_name = 'recipe'
urlpatterns = [
path('', include(router.urls)),
]

21
app/recipe/views.py Normal file
View File

@ -0,0 +1,21 @@
"""
Views for the recipe APIs.
"""
from rest_framework import viewsets
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Recipe
from recipe import serializers
class RecipeViewSet(viewsets.ModelViewSet):
"""View for manage recipe APIs."""
serializer_class = serializers.RecipeSerializer
queryset = Recipe.objects.all()
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get_queryset(self):
"""Retrieve recipes for authenticated user."""
return self.queryset.filter(user=self.request.user).order_by('-id')