Skip to content

Commit fb3c296

Browse files
committedSep 9, 2023
crud rest api with class based views
1 parent 05e6a01 commit fb3c296

16 files changed

+336
-0
lines changed
 

‎core/__init__.py

Whitespace-only changes.

‎core/asgi.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
ASGI config for core project.
3+
4+
It exposes the ASGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.asgi import get_asgi_application
13+
14+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
15+
16+
application = get_asgi_application()

‎core/settings.py

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
"""
2+
Django settings for core project.
3+
4+
Generated by 'django-admin startproject' using Django 4.2.5.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/4.2/topics/settings/
8+
9+
For the full list of settings and their values, see
10+
https://docs.djangoproject.com/en/4.2/ref/settings/
11+
"""
12+
13+
from pathlib import Path
14+
15+
# Build paths inside the project like this: BASE_DIR / 'subdir'.
16+
BASE_DIR = Path(__file__).resolve().parent.parent
17+
18+
19+
# Quick-start development settings - unsuitable for production
20+
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
21+
22+
# SECURITY WARNING: keep the secret key used in production secret!
23+
SECRET_KEY = 'django-insecure-6!vjpw+e(0=3!%(di3d49@5kf_99ut((!yez(+@6wbc9645(=3'
24+
25+
# SECURITY WARNING: don't run with debug turned on in production!
26+
DEBUG = True
27+
28+
ALLOWED_HOSTS = []
29+
30+
31+
# Application definition
32+
33+
INSTALLED_APPS = [
34+
'django.contrib.admin',
35+
'django.contrib.auth',
36+
'django.contrib.contenttypes',
37+
'django.contrib.sessions',
38+
'django.contrib.messages',
39+
'django.contrib.staticfiles',
40+
41+
# custom apps
42+
'rest_framework',
43+
'recipe_manager',
44+
]
45+
46+
MIDDLEWARE = [
47+
'django.middleware.security.SecurityMiddleware',
48+
'django.contrib.sessions.middleware.SessionMiddleware',
49+
'django.middleware.common.CommonMiddleware',
50+
'django.middleware.csrf.CsrfViewMiddleware',
51+
'django.contrib.auth.middleware.AuthenticationMiddleware',
52+
'django.contrib.messages.middleware.MessageMiddleware',
53+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
54+
]
55+
56+
ROOT_URLCONF = 'core.urls'
57+
58+
TEMPLATES = [
59+
{
60+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
61+
'DIRS': [],
62+
'APP_DIRS': True,
63+
'OPTIONS': {
64+
'context_processors': [
65+
'django.template.context_processors.debug',
66+
'django.template.context_processors.request',
67+
'django.contrib.auth.context_processors.auth',
68+
'django.contrib.messages.context_processors.messages',
69+
],
70+
},
71+
},
72+
]
73+
74+
WSGI_APPLICATION = 'core.wsgi.application'
75+
76+
77+
# Database
78+
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
79+
80+
DATABASES = {
81+
'default': {
82+
'ENGINE': 'django.db.backends.sqlite3',
83+
'NAME': BASE_DIR / 'db.sqlite3',
84+
}
85+
}
86+
87+
88+
# Password validation
89+
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
90+
91+
AUTH_PASSWORD_VALIDATORS = [
92+
{
93+
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
94+
},
95+
{
96+
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
97+
},
98+
{
99+
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
100+
},
101+
{
102+
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
103+
},
104+
]
105+
106+
107+
# Internationalization
108+
# https://docs.djangoproject.com/en/4.2/topics/i18n/
109+
110+
LANGUAGE_CODE = 'en-us'
111+
112+
TIME_ZONE = 'UTC'
113+
114+
USE_I18N = True
115+
116+
USE_TZ = True
117+
118+
119+
# Static files (CSS, JavaScript, Images)
120+
# https://docs.djangoproject.com/en/4.2/howto/static-files/
121+
122+
STATIC_URL = 'static/'
123+
124+
# Default primary key field type
125+
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
126+
127+
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

‎core/urls.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
"""
2+
URL configuration for core project.
3+
4+
The `urlpatterns` list routes URLs to views. For more information please see:
5+
https://docs.djangoproject.com/en/4.2/topics/http/urls/
6+
Examples:
7+
Function views
8+
1. Add an import: from my_app import views
9+
2. Add a URL to urlpatterns: path('', views.home, name='home')
10+
Class-based views
11+
1. Add an import: from other_app.views import Home
12+
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
13+
Including another URLconf
14+
1. Import the include() function: from django.urls import include, path
15+
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
16+
"""
17+
from django.contrib import admin
18+
from django.urls import path, include
19+
20+
urlpatterns = [
21+
path('admin/', admin.site.urls),
22+
path('api/', include('recipe_manager.urls'))
23+
]

‎core/wsgi.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""
2+
WSGI config for core project.
3+
4+
It exposes the WSGI callable as a module-level variable named ``application``.
5+
6+
For more information on this file, see
7+
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
8+
"""
9+
10+
import os
11+
12+
from django.core.wsgi import get_wsgi_application
13+
14+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
15+
16+
application = get_wsgi_application()

‎manage.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#!/usr/bin/env python
2+
"""Django's command-line utility for administrative tasks."""
3+
import os
4+
import sys
5+
6+
7+
def main():
8+
"""Run administrative tasks."""
9+
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
10+
try:
11+
from django.core.management import execute_from_command_line
12+
except ImportError as exc:
13+
raise ImportError(
14+
"Couldn't import Django. Are you sure it's installed and "
15+
"available on your PYTHONPATH environment variable? Did you "
16+
"forget to activate a virtual environment?"
17+
) from exc
18+
execute_from_command_line(sys.argv)
19+
20+
21+
if __name__ == '__main__':
22+
main()

‎recipe_manager/__init__.py

Whitespace-only changes.

‎recipe_manager/admin.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.contrib import admin
2+
3+
# Register your models here.

‎recipe_manager/apps.py

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
from django.apps import AppConfig
2+
3+
4+
class RecipeManagerConfig(AppConfig):
5+
default_auto_field = 'django.db.models.BigAutoField'
6+
name = 'recipe_manager'
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Generated by Django 4.2.5 on 2023-09-08 14:09
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
8+
initial = True
9+
10+
dependencies = [
11+
]
12+
13+
operations = [
14+
migrations.CreateModel(
15+
name='Recipe',
16+
fields=[
17+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18+
('recipe_name', models.CharField(max_length=255)),
19+
('ingredients', models.TextField()),
20+
('instructions', models.TextField()),
21+
],
22+
),
23+
]

‎recipe_manager/migrations/__init__.py

Whitespace-only changes.

‎recipe_manager/models.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# models.py
2+
from django.db import models
3+
4+
class Recipe(models.Model):
5+
recipe_name = models.CharField(max_length=255)
6+
ingredients = models.TextField()
7+
instructions = models.TextField()
8+

‎recipe_manager/serializers.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# serializers.py
2+
from rest_framework import serializers
3+
4+
from .models import Recipe
5+
6+
class RecipeSerializer(serializers.ModelSerializer):
7+
class Meta:
8+
model = Recipe
9+
fields = ('recipe_name', 'ingredients', 'instructions')
10+

‎recipe_manager/tests.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from django.test import TestCase
2+
3+
# Create your tests here.

‎recipe_manager/urls.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from django.urls import path
2+
from . import views
3+
4+
urlpatterns = [
5+
# List and Create view
6+
path('recipes/', views.RecipeListCreateAPIView.as_view(), name='recipe-list-create'),
7+
8+
# Retrieve, Update, and Delete view
9+
path('recipes/<int:pk>/', views.RecipeRetrieveUpdateDeleteAPIView.as_view(), name='recipe-retrieve-update-destroy'),
10+
]
11+
12+
# uncomment below to avoid DRY
13+
"""
14+
urlpatterns = [
15+
# List view (Read all)
16+
path('recipes/', views.RecipeListView.as_view(), name='recipe-list'),
17+
18+
# Create view
19+
path('recipes/create/', views.RecipeCreateView.as_view(), name='recipe-create'),
20+
21+
# Retrieve view (Read one)
22+
path('recipes/<int:pk>/', views.RecipeRetrieveView.as_view(), name='recipe-retrieve'),
23+
24+
# Update view
25+
path('recipes/<int:pk>/update/', views.RecipeUpdateView.as_view(), name='recipe-update'),
26+
27+
# Delete view
28+
path('recipes/<int:pk>/delete/', views.RecipeDeleteView.as_view(), name='recipe-destroy'),
29+
]
30+
"""
31+
32+

‎recipe_manager/views.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from rest_framework.generics import (
2+
ListAPIView,
3+
CreateAPIView,
4+
RetrieveAPIView,
5+
UpdateAPIView,
6+
DestroyAPIView,
7+
ListCreateAPIView,
8+
RetrieveUpdateDestroyAPIView
9+
)
10+
11+
from .models import Recipe
12+
from .serializers import RecipeSerializer
13+
14+
class RecipeListCreateAPIView(ListCreateAPIView):
15+
serializer_class = RecipeSerializer
16+
queryset = Recipe.objects.all()
17+
18+
class RecipeRetrieveUpdateDeleteAPIView(RetrieveUpdateDestroyAPIView):
19+
serializer_class = RecipeSerializer
20+
queryset = Recipe.objects.all()
21+
22+
# uncomment below to avoid DRY
23+
"""
24+
# List view
25+
class RecipeListView(ListAPIView):
26+
serializer_class = RecipeSerializer
27+
queryset = Recipe.objects.all()
28+
29+
# Create view
30+
class RecipeCreateView(CreateAPIView):
31+
serializer_class = RecipeSerializer
32+
33+
# Retrieve view
34+
class RecipeRetrieveView(RetrieveAPIView):
35+
serializer_class = RecipeSerializer
36+
queryset = Recipe.objects.all()
37+
38+
# Update view
39+
class RecipeUpdateView(UpdateAPIView):
40+
serializer_class = RecipeSerializer
41+
queryset = Recipe.objects.all()
42+
43+
# Destroy view
44+
class RecipeDeleteView(DestroyAPIView):
45+
serializer_class = RecipeSerializer
46+
queryset = Recipe.objects.all()
47+
"""

0 commit comments

Comments
 (0)
Please sign in to comment.