其他分享
首页 > 其他分享> > day73-drfwork

day73-drfwork

作者:互联网

views

import rest_framework
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.exceptions import APIException
from rest_framework.pagination import PageNumberPagination
from rest_framework.settings import APISettings
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser
from rest_framework.filters import OrderingFilter
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework import status

from django.http import JsonResponse

class BookAPIView(APIView):
    # 局部配置解析类:只使用当前视图类
    parser_classes = [JSONParser, FormParser,]
    # 局部配置渲染类:只适用当前视图类
    renderer_classes = [JSONRenderer, BrowsableAPIRenderer]

    def get(self, request, *args, **kwargs):
        # a
        print(args.get('pk'))
        response = Response(
            data = {
            'msg':'apiview get ok'
            },
            status = status.HTTP_404_NOT_FOUND
        )

        print(response.data)

        return response

    def post(self, request, *args, **kwargs):

        print(request._request.method,1)
        print(request.method,2)
        print(request.query_params,3)
        print(request.data,4)

        return Response({
            'msg':'apiview post ok'
        })

urls

from django.conf.urls import url
from . import views
urlpatterns = [

    url(r'^books/$',views.BookAPIView.as_view()),
    url(r'^books/(?P<pk>\d+)/$',views.BookAPIView.as_view()),
]

models

from django.db import models

# Create your models here.

class Books(models.Model):

    title = models.CharField(max_length=32)

    price = models.DecimalField(max_digits=5,decimal_places=2)

exception

from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.response import Response
def exception_handler(exc, context):
    print(111)
    response = drf_exception_handler(exc, context)
    detail = '%s - %s - %s'%(context.get('view'), context.get('request').method, exc)

    if not response:
        response = Response({'detail':detail})

    else:
        response.data = {'detail':detail}


    return response

标签:framework,request,drfwork,rest,day73,print,import,response
来源: https://www.cnblogs.com/shenblog/p/12103820.html