Django Rest Framework--2

 

  1 from django.shortcuts import render,HttpResponse
  2 from django.views import View
  3 from blog.models import Book,Publish,Author
  4 from rest_framework.response import Response
  5 from rest_framework import serializers
  6 #为queryset,model对象做序列化
  7 class PublishSerializers(serializers.Serializer):
  8     name=serializers.CharField()
  9     email=serializers.CharField()
 10 
 11 # class BookSerializers(serializers.Serializer):
 12 #     title=serializers.CharField(max_length=32)
 13 #     price=serializers.IntegerField()
 14 #     pub_date=serializers.DateField()
 15 #     publish=serializers.CharField(source="publish.name")
 16 #     # authors=serializers.CharField(source="authors.all")
 17 #     authors = serializers.SerializerMethodField()
 18 #     def get_authors(self,obj):
 19 #         temp = []
 20 #         for author in obj.authors.all():
 21 #             temp.append(author.name)
 22 #         return temp
 23 class BookSerializers(serializers.ModelSerializer):
 24     class Meta:
 25         model = Book
 26         fields = "__all__"
 27         # depth = 1
 28     # publish=serializers.CharField(source="publish.pk",read_only=True)
 29     publish = serializers.HyperlinkedIdentityField(
 30         view_name='publish_detail',
 31         lookup_field="publish_id",
 32         lookup_url_kwarg="pk"
 33 
 34     )
 35     # authors=serializers.CharField(source="authors.all")
 36     # authors = serializers.SerializerMethodField()
 37     # def get_authors(self,obj):
 38     #     temp = []
 39     #     for author in obj.authors.all():
 40     #         temp.append(author.pk)
 41     #     return temp
 42 
 43     def create(self, validated_data):
 44         print("validated_data",validated_data)
 45         # authors = validated_data.pop('authors')
 46         # obj = Book.objects.create(**validated_data)
 47         # obj.authors.add(*authors)
 48         # return obj
 49         book=Book.objects.create(title=validated_data['title'],
 50                                  price=validated_data['price'],
 51                                  pub_date=validated_data['pub_date'],
 52                                  publish_id=validated_data['publish']['pk'])
 53         book.authors.add(*validated_data['authors'])
 54         return book
 55 
 56 # from django.utils.decorators import method_decorator
 57 from rest_framework.views import APIView
 58 # from rest_framework.response import Response
 59 
 60 class PublishesView(APIView):
 61     # def dispatch(self, request, *args, **kwargs):
 62     #     print("dispatch......")
 63     #     ret=super(LoginView,self).dispatch(self, request, *args, **kwargs)
 64     #     return ret
 65     def get(self,request,*args,**kwargs):
 66         print("GET", request.POST)
 67         print("body", request.body)
 68         return HttpResponse("get")
 69 
 70     def post(self,request,*args,**kwargs):
 71         # 原生的request支持的操作
 72         # print("POST",request.POST)
 73         # print("body",request.body)
 74         # # print(request)
 75         # print(type(request))
 76         # from django.core.handlers.wsgi import WSGIRequest
 77 
 78         # 新的request支持的操作
 79         #request._request.POST    #如果需要原来的request
 80         print("request.data  新的request",request.data)
 81 
 82 
 83 
 84         return HttpResponse("post")
 85 
 86 class PublishDetailViewSet(APIView):
 87     pass
 88 
 89 class BookView(APIView):
 90     def get(self,request):
 91         book_list=Book.objects.all()
 92         bs=BookSerializers(book_list,many=True,context={'request': request})
 93         # return HttpResponse(bs.data)
 94         return Response(bs.data)
 95 
 96     def post(self, request, *args, **kwargs):
 97 
 98         bs = BookSerializers(data=request.data, many=False)
 99         if bs.is_valid():
100             # print(bs.validated_data)
101             bs.save()
102             return Response(bs.data)
103         else:
104             # return HttpResponse(bs.errors)
105             return Response(bs.errors)
106 
107 class BookDetailViewSet(APIView):
108     def get(self,request,id):
109         book=Book.objects.filter(pk=id).first()
110         #quryset using many=True    or model_object nothing
111         bs = BookSerializers(book,context={'request': request})
112         return Response(bs.data)
113 
114     def put(self,request,id):
115         book = Book.objects.filter(pk=id).first()
116         bs=BookSerializers(book,data=request.data)
117         if bs.is_valid():
118             bs.save()
119             return Response(bs.data)
120         else:
121             return Response(bs.errors)
122     def delete(self,request,id):
123         Book.objects.filter(pk=id).first().delete()
124         return Response()
View
 1 """mysite1 URL Configuration
 2 
 3 The `urlpatterns` list routes URLs to views. For more information please see:
 4     https://docs.djangoproject.com/en/2.1/topics/http/urls/
 5 Examples:
 6 Function views
 7     1. Add an import:  from my_app import views
 8     2. Add a URL to urlpatterns:  path('', views.home, name='home')
 9 Class-based views
10     1. Add an import:  from other_app.views import Home
11     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
12 Including another URLconf
13     1. Import the include() function: from django.urls import include, path
14     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
15 """
16 from django.contrib import admin
17 from django.urls import path,re_path
18 from blog import views
19 urlpatterns = [
20     path('admin/', admin.site.urls,),
21     re_path("^publishes/", views.PublishesView.as_view(),name="publishes"),  # 用来调用CBV 调用类
22     re_path('^publishers/(?P<pk>\d+)$', views.PublishDetailViewSet.as_view(),name="publish_detail"),
23 
24     re_path("^books/$", views.BookView.as_view()),  # 用来调用CBV 调用类
25     re_path(r'^books/(\d+)/$', views.BookDetailViewSet.as_view(), name="book_detail"),
26 
27 ]
View Code
 1 from django.db import models
 2 
 3 # Create your models here.
 4 
 5 class Book(models.Model):
 6     title=models.CharField(max_length=32)
 7     price=models.IntegerField()
 8     pub_date=models.DateField(null=True)
 9     publish=models.ForeignKey("Publish",on_delete=models.CASCADE)
10     authors=models.ManyToManyField("Author")
11 
12 
13     def __str__(self):
14         return self.title
15 class Publish(models.Model):
16     name=models.CharField(max_length=32)
17     email=models.EmailField()
18     def __str__(self):
19         return self.name
20 
21 class Author(models.Model):
22     name=models.CharField(max_length=32)
23     age=models.IntegerField()
24 
25     def __str__(self):
26         return self.name
View Code
"""
Django settings for mysite1 project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cnclo%stfy&xw$oo58*5qm!2*7y1te57*dkx!9ci$yha-=s=-6'

# 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',
    'blog.apps.BlogConfig',
    '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 = 'mysite1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        '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 = 'mysite1.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.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/2.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/2.1/howto/static-files/

STATIC_URL = '/static/'



REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        # 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}
#
# 将设置里的'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'一句删除,重启项目再次访问,不在报错。
#
#   注:'rest_framewo

 

posted @ 2019-01-31 19:37  巨兽~墨菲特  阅读(173)  评论(0编辑  收藏  举报