简单学习了RDF的APIVIEW

main
RogerWork 1 year ago
parent 247f0f6722
commit c1ae3201ea
  1. 27
      apps/goods/drf_customer_renderer.py
  2. 4
      apps/goods/test.http
  3. 6
      apps/goods/urls.py
  4. 19
      apps/goods/views_api.py
  5. 54
      apps/goods/views_apiview.py
  6. 0
      apps/goods/views_generics.py
  7. 0
      apps/goods/views_mixin.py
  8. 12
      myshop_back/settings.py

@ -0,0 +1,27 @@
from rest_framework.renderers import JSONRenderer
class CustomRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
print('render11111111111111111111')
if renderer_context:
if isinstance(data, dict):
msg = data.pop('msg', 'success')
code = data.pop('code', 200)
if 'status' in data.keys():
del data['status']
data = data['data']
else:
data = data
return_data = {
'msg': msg,
'code': code,
'data': {
'list': data,
'total': len(data)
}
}
return super().render(return_data, accepted_media_type, renderer_context)
else:
return super().render(data, accepted_media_type, renderer_context)

@ -0,0 +1,4 @@
GET http://127.0.0.1:8000/goods/goods_api_d
Accept: application/json
###

@ -16,8 +16,7 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path
from apps.goods import views
from apps.goods import views_api
from apps.goods import views, views_api, views_apiview
urlpatterns = [
# path('cate_index/', views.GoodCateView.as_view(), name='cate_index'),
@ -28,4 +27,7 @@ urlpatterns = [
path('goods_api/', views.GoodsView.as_view()),
path('goods_model_api/', views.GoodsModelView.as_view()),
path('goods_api_d/', views_api.goods_list),
path('goods_api_d/<int:id>/', views_api.goods_list),
path('goods_apiview/', views_apiview.GoodsAPIView.as_view()),
path('goods_apiview/<int:id>/', views_apiview.GoodsAPIView.as_view()),
]

@ -2,6 +2,8 @@ from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import Http404
from apps.goods.models import *
from apps.goods.serializers import *
@ -30,3 +32,20 @@ def goods_list(request, *args, **kwargs):
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)

@ -0,0 +1,54 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from apps.goods.models import *
from apps.goods.serializers import *
class GoodsAPIView(APIView):
def get(self, request, *args, **kwargs):
query_data = Goods.objects.all()[:10]
goods_json = GoodsSerializers(query_data, many=True)
print(goods_json.data)
print(goods_json)
r = Response(data=goods_json.data, status=status.HTTP_200_OK)
print(r.data)
print(r.status_code)
print(r)
return Response(data=goods_json.data, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs):
data = request.data
print(request)
print(data)
goods_serializer = GoodsSerializers(data=data, many=False)
print(goods_serializer)
if goods_serializer.is_valid():
d = goods_serializer.validated_data
print('validated_data', d)
Goods.objects.create(**d)
return Response(goods_serializer.data, status=status.HTTP_200_OK)
else:
return Response(goods_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def put(self, request, *args, **kwargs):
data = request.data
params = kwargs
print(data)
print(params)
_id = params.get('id')
serializer_goods = GoodsSerializers(data=data, many=False)
if serializer_goods.is_valid():
if goods_obj := Goods.objects.filter(id=_id):
goods_obj.update(**serializer_goods.validated_data)
return Response(serializer_goods.data, status=status.HTTP_200_OK)
return Response(serializer_goods.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, *args, **kwargs):
del_id = request.data.get('id')
if del_id:
goods_obj = Goods.objects.filter(id=del_id)
goods_obj.delete()
return Response(status=status.HTTP_200_OK)
return Response(status=status.HTTP_400_BAD_REQUEST)

@ -11,6 +11,7 @@ https://docs.djangoproject.com/en/4.2/ref/settings/
"""
from pathlib import Path
from rest_framework.renderers import JSONRenderer
import sys, os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
@ -134,8 +135,7 @@ STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] # 需要手动设置stati
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
CKEDITOR_UPLOAD_PATH = 'upload/full_text'
CKEDITOR_UPLOAD_PATH = 'upload/full_text'
"""
遇到此报错后需要修改用户验证的model
@ -144,3 +144,11 @@ auth.User.groups: (fields.E304) Reverse accessor 'Group.user_set' for 'auth.User
HINT: Add or change a related_name argument to the definition for 'auth.User.groups' or 'user.MyUser.groups'.
"""
AUTH_USER_MODEL = 'user.Myuser'
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
# 'rest_framework.renderers.JSONRenderer',
'apps.goods.drf_customer_renderer.CustomRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}

Loading…
Cancel
Save