# 03.基于APIView类的视图
[toc]{type: "ol", level: [2, 3, 4, 5]}
### 创建路由
```python
### shop.urls
# 基于APIView类的视图
path('category/list/apiview/', CategoryListAPIView.as_view(), name='categoryListAPIView'),
re_path(r'^category/detail/apiview/(\d+)/$', CategoryDetailAPIView.as_view(), name='categoryDetailAPIView'),
```
<br><br>
### 创建视图
#### 导入模块
APIView封装了View,并重写了as_view方法
```python
### shop.views
from rest_framework.views import APIView
from django.shortcuts import get_object_or_404
```
#### 多个对象
```python
### shop.views
class CategoryListAPIView(APIView):
def get(self, request):
# rest_framework.request.Request
# 写法与函数categoryList一致 instance:从数据库中获取数据
seria = CategorySerializer(instance=Category.objects.all(), many=True)
return Response(seria.data, status=status.HTTP_200_OK)
def post(self, request):
# data:从请求中获取数据
# 方式1:
seria = CategorySerializer(data=request.data)
if seria.is_valid():
seria.save()
return Response(seria.data, status=status.HTTP_201_CREATED)
else:
return Response(seria.errors, status=status.HTTP_400_BAD_REQUEST)
# # 方式2:
# seria = CategorySerializer(data=request.data)
# # 校验失败,False则抛异常
# seria.is_valid(raise_exception=True)
# return Response(seria.data, status=status.HTTP_201_CREATED)
```
#### 单个对象
```python
### shop.views
class CategoryDetailAPIView(APIView):
def get(self, request, cid):
seria = CategorySerializer(instance=get_object_or_404(Category, pk=cid))
return Response(seria.data, status=status.HTTP_200_OK)
def put(self, request, cid):
seria = CategorySerializer(instance=get_object_or_404(Category, pk=cid), data=request.data)
if seria.is_valid():
seria.save()
return Response(seria.data, status.HTTP_200_OK)
else:
return Response(seria.errors, status.HTTP_400_BAD_REQUEST)
def patch(self, request, cid):
seria = CategorySerializer(instance=get_object_or_404(Category, pk=cid), data=request.data)
if seria.is_valid():
seria.save()
return Response(seria.data, status.HTTP_200_OK)
else:
return Response(seria.errors, status.HTTP_400_BAD_REQUEST)
def delete(self, request, cid):
get_object_or_404(Category, pk=cid).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
```
<br><br>