You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.9 KiB
53 lines
1.9 KiB
from rest_framework.decorators import api_view |
|
from rest_framework.response import Response |
|
from rest_framework import status |
|
|
|
from django.http import Http404 |
|
from django.views.decorators.cache import cache_page |
|
|
|
from apps.goods.models import * |
|
from apps.goods.serializers import * |
|
|
|
|
|
@api_view(['GET', 'POST', 'PUT', 'DELETE']) |
|
@cache_page(60*1) # 缓存1分钟 |
|
def goods_list(request, *args, **kwargs): |
|
if request.method == 'GET': |
|
# 获取数据 |
|
print(args) |
|
print(kwargs) |
|
print(request.query_params) |
|
if _id := request.query_params.get('id'): |
|
goods = Goods.objects.filter(id=_id) |
|
else: |
|
goods = Goods.objects.all()[:10] |
|
# 序列化 |
|
goods_json = GoodsSerializers(goods, many=True) |
|
print(goods_json.data) |
|
return Response(goods_json.data) |
|
elif request.method == 'POST': |
|
data = request.data |
|
print(data) |
|
serializer_data = GoodsSerializers(data=data, many=False) |
|
if serializer_data.is_valid(): |
|
goods = serializer_data.save() |
|
return Response(serializer_data.data, status=status.HTTP_201_CREATED) |
|
else: |
|
return Response(serializer_data.errors, status=status.HTTP_400_BAD_REQUEST) |
|
elif request.method == 'PUT': |
|
data = request.data |
|
print(data) |
|
try: |
|
goods = Goods.objects.get(id=kwargs.get('id')) |
|
except Goods.DoesNotExist: |
|
raise Http404 |
|
serializer_data = GoodsSerializers(goods, data=data, context={'request': request}) |
|
if serializer_data.is_valid(): |
|
goods = serializer_data.save() |
|
return Response(serializer_data.data) |
|
else: |
|
return Response(serializer_data.errors, status=status.HTTP_400_BAD_REQUEST) |
|
elif request.method == 'DELETE': |
|
goods = Goods.objects.filter(id=kwargs.get('id')) |
|
goods.delete() |
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
|
|