我在这里跟随本教程: https://realpython.com/test-driven-development-of-a-django-restful-api/
我已完成所有设置,API端点按预期工作: 当我打电话时: 本地主机/ api / v1 / puppies / 返回:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.0.0</version>
</dependency>
“细节”视图的主要问题也适用。 如果我致电:localhost / api / v1 / puppies / 2返回:
int32_t positive_modulo(int32_t number, int32_t modulo) {
return (number + ((int64_t)modulo << 32)) % modulo;
}
这很棒,我的所有put post删除操作也都可以,这里是代码:
models.py:
{
"name": "Bridgett",
"age": 3,
"breed": "Boxer",
"color": "White",
"created_at": "2018-10-03T17:28:21.333893Z",
"updated_at": "2018-10-03T17:34:13.899385Z"
},
{
"name": "Mia",
"age": 3,
"breed": "Mix",
"color": "Black",
"created_at": "2018-10-09T16:08:59.775685Z",
"updated_at": "2018-10-09T16:08:59.775685Z"
}
serializers.py
{
"name": "Bridgett",
"age": 3,
"breed": "Boxer",
"color": "White",
"created_at": "2018-10-03T17:28:21.333893Z",
"updated_at": "2018-10-03T17:34:13.899385Z"
}
views.py
# models.py
from django.db import models
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 __str__(self):
return self.name
def get_breed(self):
return self.name + ' belongs to ' + self.breed + ' breed.'
def __repr__(self):
return self.name + ' is added.'
urls.py
# serializers.py
from rest_framework import serializers
from .models import Puppy
class PuppySerializer(serializers.ModelSerializer):
class Meta:
model = Puppy
fields = ('name', 'age', 'breed', 'color', 'created_at', 'updated_at')
所有这一切都按预期工作,但是当我替换views.py和urls.py中的代码时,我遇到的问题是像使用基于类的视图一样,在详细视图api调用中我什么也没得到返回: v1 / puppies / 2返回:
from django.shortcuts import render
from rest_framework.decorators import api_view
# from rest_framework.decorators import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views.generic import TemplateView
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':
serializer = PuppySerializer(puppy)
return Response(serializer.data)
# update details of a single puppy
if request.method == 'PUT':
serializer = PuppySerializer(puppy, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# delete a single puppy
if request.method == 'DELETE':
puppy.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
@api_view(['GET', 'POST'])
def get_post_puppies(request):
# get all puppies
if request.method == 'GET':
puppies = Puppy.objects.all()
serializer = PuppySerializer(puppies, many=True)
return Response(serializer.data)
# insert a new record for a puppy
if request.method == 'POST':
data = {
'name': request.data.get('name'),
'age': int(request.data.get('age')),
'breed': request.data.get('breed'),
'color': request.data.get('color')
}
serializer = PuppySerializer(data=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)
更新的代码是这样的:
views.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^api/v1/puppies/(?P<pk>[0-9]+)$',
# views.PuppyDetail.as_view(),
views.get_delete_update_puppy,
name='get_delete_update_puppy'
),
url(
r'^api/v1/puppies/$',
# views.PuppyList.as_view(),
views.get_post_puppies,
name='get_post_puppies'
)
]
urls.py
{
"name": "",
"age": null,
"breed": "",
"color": ""
}
我的问题是,一旦实现基于类的视图,我的api调用不起作用的断开连接是什么?
调试打印后,我意识到我没有在get_object中添加返回值:
from django.shortcuts import render
# from rest_framework.decorators import api_view
from rest_framework.decorators import APIView
from rest_framework.response import Response
from rest_framework import status
from django.views.generic import TemplateView
from .models import Puppy
from .serializers import PuppySerializer
class PuppyDetail(APIView):
"""
Get, update, or delete a single puppy instance
"""
def get_object(self, pk):
try:
puppy = Puppy.objects.get(pk=pk)
except Puppy.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
def get(self, request, pk):
# get details of a single puppy
puppy = self.get_object(pk)
serializer = PuppySerializer(puppy)
return Response(serializer.data)
def put(self, request, pk):
# update details of a single puppy
puppy = self.get_object(pk)
serializer = PuppySerializer(puppy, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk):
puppy = self.get_object(pk)
puppy.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class PuppyList(APIView):
"""
List all puppies, or create a new puppy
"""
def get(self, request):
puppies = Puppy.objects.all()
serializer = PuppySerializer(puppies, many=True)
return Response(serializer.data)
def post(self, request):
serializer = PuppySerializer(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)
我丢失了要发送给函数调用的对象的返回。谢谢