Compare commits
7 Commits
bae94e09b4
...
7310f1818c
Author | SHA1 | Date |
---|---|---|
Jason Zhu | 7310f1818c | |
Jason Zhu | 762296b276 | |
Jason Zhu | e207585bb7 | |
Jason Zhu | d03f9c7a5b | |
Jason Zhu | ca1c096013 | |
Jason Zhu | 74972967dc | |
Jason Zhu | 21233d337f |
|
@ -0,0 +1,5 @@
|
|||
env
|
||||
.vscode
|
||||
**db.sqlite3**
|
||||
**__pycache__**
|
||||
**migrations**
|
12
README.md
12
README.md
|
@ -2,3 +2,15 @@
|
|||
|
||||
This is a practice repository following [Test Driven Development of a Django RESTful API](https://realpython.com/test-driven-development-of-a-django-restful-api/)
|
||||
|
||||
## RESTful Structure
|
||||
|
||||
In a RESTful API, endpoints (URLs) define the structure of the API and how end users access data from our application using the HTTP methods - GET, POST, PUT, DELETE. Endpoints should be logically organized around collections and elements, both of which are resources.
|
||||
|
||||
In our case, we have one single resource, puppies, so we will use the following URLS - /puppies/ and /puppies/<id> for collections and elements, respectively
|
||||
|
||||
## Routes and TDD
|
||||
|
||||
Process for development:
|
||||
1. Create skeleton code that doomed to fail
|
||||
2. Add a unit test for failure
|
||||
3. Update the code to make it pass the test.
|
|
@ -0,0 +1,22 @@
|
|||
#!/usr/bin/env python
|
||||
"""Django's command-line utility for administrative tasks."""
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
"""Run administrative tasks."""
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'puppy_store.settings')
|
||||
try:
|
||||
from django.core.management import execute_from_command_line
|
||||
except ImportError as exc:
|
||||
raise ImportError(
|
||||
"Couldn't import Django. Are you sure it's installed and "
|
||||
"available on your PYTHONPATH environment variable? Did you "
|
||||
"forget to activate a virtual environment?"
|
||||
) from exc
|
||||
execute_from_command_line(sys.argv)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
|
@ -0,0 +1,3 @@
|
|||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PuppiesConfig(AppConfig):
|
||||
name = 'puppies'
|
|
@ -0,0 +1,22 @@
|
|||
from django.db import models
|
||||
from django.db.models.deletion import Collector
|
||||
|
||||
class Puppy(models.Model):
|
||||
"""
|
||||
Puppy Model
|
||||
Defines the attributes of a puppy
|
||||
"""
|
||||
name = models.CharField(max_length=255)
|
||||
age = models.IntegerField()
|
||||
breed = models.CharField(max_length=255)
|
||||
color = models.CharField(max_length=255)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
def get_breed(self):
|
||||
return self.name + ' belongs to ' + self.breed + ' breed.'
|
||||
|
||||
def __repr__(self):
|
||||
return self.name + ' is added.'
|
||||
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
from rest_framework import serializers
|
||||
from rest_framework.exceptions import MethodNotAllowed
|
||||
from .models import Puppy
|
||||
|
||||
class PuppySerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
In the above snippet we defined a ModelSerializer for our puppy model, validating all the mentioned fields. In short, if you have a one-to-one relationship between your API endpoints and your models - which you probably should if you’re creating a RESTful API - then you can use a ModelSerializer to create a Serializer.
|
||||
"""
|
||||
class Meta:
|
||||
model = Puppy
|
||||
fields = ('name', 'age', 'breed', 'color', 'created_at', 'updated_at')
|
|
@ -0,0 +1,31 @@
|
|||
from django.test import TestCase
|
||||
from ..models import Puppy
|
||||
|
||||
class PuppyTest(TestCase):
|
||||
"""
|
||||
Test module for Puppy model
|
||||
"""
|
||||
|
||||
def setUp(self) -> None:
|
||||
Puppy.objects.create(
|
||||
name='Casper',
|
||||
age=3,
|
||||
breed='Bull Dog',
|
||||
color='Black'
|
||||
)
|
||||
Puppy.objects.create(
|
||||
name='Muffin',
|
||||
age=1,
|
||||
breed='Gradane',
|
||||
color='Brown'
|
||||
)
|
||||
|
||||
def test_puppy_get_breed(self):
|
||||
puppy_casper = Puppy.objects.get(name='Casper')
|
||||
puppy_muffin = Puppy.objects.get(name='Muffin')
|
||||
self.assertEqual(
|
||||
puppy_casper.get_breed(), "Casper belongs to Bull Dog breed."
|
||||
)
|
||||
self.assertEqual(
|
||||
puppy_muffin.get_breed(), "Muffin belongs to Gradane breed."
|
||||
)
|
|
@ -0,0 +1,10 @@
|
|||
import json
|
||||
from rest_framework import status
|
||||
from django.test import TestCase, Client
|
||||
from django.urls import reverse
|
||||
|
||||
from ..models import Puppy
|
||||
from ..serializers import PuppySerializer
|
||||
|
||||
# initialize the APIClient app
|
||||
client = Client()
|
|
@ -0,0 +1,16 @@
|
|||
from django.conf.urls import url
|
||||
from . import views
|
||||
|
||||
urlpatterns = [
|
||||
# suppose this is the django1's code style, check django REST framework for django3.1
|
||||
url(
|
||||
r'^api/v1/puppies/(?P<pk>[0-9]+)$',
|
||||
views.get_delete_update_puppy,
|
||||
name='get_delete_update_puppy'
|
||||
),
|
||||
url(
|
||||
r'^api/v1/puppies/$',
|
||||
views.get_post_puppies,
|
||||
name='get_post_puppies'
|
||||
)
|
||||
]
|
|
@ -0,0 +1,34 @@
|
|||
from django.shortcuts import render
|
||||
from django.test.client import RequestFactory
|
||||
from rest_framework.decorators import api_view
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
|
||||
from .models import Puppy
|
||||
from .serializers import PuppySerializer
|
||||
|
||||
@api_view(['GET', 'DELETE', 'PUT'])
|
||||
def get_delete_update_puppy(request, pk):
|
||||
try:
|
||||
puppy = Puppy.objects.get(pk=pk)
|
||||
except Puppy.DoesNotExist:
|
||||
return Response(status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
# get details of a single puppy
|
||||
if request.method == 'GET':
|
||||
return Response({})
|
||||
# delete a single puppy
|
||||
elif request.method == 'DELETE':
|
||||
return Response({})
|
||||
# update details of a single puppy
|
||||
elif request.method == 'PUT':
|
||||
return Response({})
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def get_post_puppies(request):
|
||||
# get all puppies
|
||||
if request.method == 'GET':
|
||||
return Response({})
|
||||
# insert a new record for a puppy
|
||||
elif request.method == 'POST':
|
||||
return Response({})
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
ASGI config for puppy_store project.
|
||||
|
||||
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'puppy_store.settings')
|
||||
|
||||
application = get_asgi_application()
|
|
@ -0,0 +1,131 @@
|
|||
"""
|
||||
Django settings for puppy_store project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 3.1.2.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.1/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/3.1/ref/settings/
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
# Quick-start development settings - unsuitable for production
|
||||
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = 'fu7gsn*!os!_spww%da59y6!+u(75@el^8#qc(u=xa1=6+7umu'
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
# 1st party
|
||||
'puppies',
|
||||
# 3rd party
|
||||
'rest_framework',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'puppy_store.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [],
|
||||
'APP_DIRS': True,
|
||||
'OPTIONS': {
|
||||
'context_processors': [
|
||||
'django.template.context_processors.debug',
|
||||
'django.template.context_processors.request',
|
||||
'django.contrib.auth.context_processors.auth',
|
||||
'django.contrib.messages.context_processors.messages',
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
WSGI_APPLICATION = 'puppy_store.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
|
||||
|
||||
AUTH_PASSWORD_VALIDATORS = [
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||
},
|
||||
{
|
||||
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
# Internationalization
|
||||
# https://docs.djangoproject.com/en/3.1/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'en-us'
|
||||
|
||||
TIME_ZONE = 'UTC'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_L10N = True
|
||||
|
||||
USE_TZ = True
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/3.1/howto/static-files/
|
||||
|
||||
STATIC_URL = '/static/'
|
||||
|
||||
# REST_FRAMEWORK = {
|
||||
# # Use Django's standard `django.contrib.auth` permission
|
||||
# # or allow read-only access for unauthenticated users.
|
||||
# 'DEFAULT_PERMISSION_CLASSES': [],
|
||||
# 'TEST_REQUEST_DEFAULT_FORMAT': 'json'
|
||||
# }
|
|
@ -0,0 +1,27 @@
|
|||
"""puppy_store URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/3.1/topics/http/urls/
|
||||
Examples:
|
||||
Function views
|
||||
1. Add an import: from my_app import views
|
||||
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||
Class-based views
|
||||
1. Add an import: from other_app.views import Home
|
||||
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||
Including another URLconf
|
||||
1. Import the include() function: from django.urls import include, path
|
||||
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||
"""
|
||||
from django.contrib import admin
|
||||
from django.urls import path
|
||||
from django.conf.urls import include, url # for django 1.x
|
||||
|
||||
urlpatterns = [
|
||||
url(r'^', include('puppies.urls')),
|
||||
url(
|
||||
r'^api-auth/',
|
||||
include('rest_framework.urls', namespace='rest_framework')
|
||||
),
|
||||
path('admin/', admin.site.urls),
|
||||
]
|
|
@ -0,0 +1,16 @@
|
|||
"""
|
||||
WSGI config for puppy_store project.
|
||||
|
||||
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'puppy_store.settings')
|
||||
|
||||
application = get_wsgi_application()
|
|
@ -0,0 +1,5 @@
|
|||
asgiref==3.2.10
|
||||
Django==3.1.2
|
||||
djangorestframework==3.12.1
|
||||
pytz==2020.1
|
||||
sqlparse==0.4.1
|
Loading…
Reference in New Issue