P7-day04

逮鯊魚去了發表於2020-11-24

restful

	一個url路由 對應一個功能,操作,絕大多數的操作都是針對資料庫的增刪改查
	前後端分離,都是ajax axios,所有的介面都是接收json,返回json
	Api 介面是提供給程式訪問的 ,提供了許可權和限流認證
	restful 攜帶token 需要在請求頭中  用鍵值對的方式攜帶token
	可以通過restful-jwt 提供的認證檢視來處理 使用者認證
在 app.urls中配置路由
from rest_framework_jwt.views import obtain_jwt_token
 path('login/', obtain_jwt_token)
在settings.py中配置 許可權認證配置
REST_FRAMEWORK = {
	# 限流限制
    'DEFAULT_THROTTLE_RATES': {
        'user': '10/hour',
        'anon': '5/day'
    },
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication'  # 介面的認證器
    ]
}
JWT_AUTH = {
    'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler',
    # headers中 Authorization鍵對應的值得字首 類似於 : jwt xxxxxx
    'JWT_AUTH_HEADER_PREFIX': 'JWT',
    # 有效期7天
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
    # 允許重新整理
    'JWT_ALLOW_REFRESH': True,
    # token在24小時過期
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24)
}
permission_classes = (AllowAny,)  # 處理許可權的類 ,允許所有人訪問
permission_classes = (IsAuthenticated,)  # 處理許可權的類 ,允許認證使用者訪問
throttle_classes = [AnonRateThrottle] # 處理介面的限流

在settings.py中配置限流次數
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_RATES':{
        'user':'10/hour',
        'anon':'5/day'
    }
}
# 函式檢視
def book_view(request):
    if request.method == 'GET':
        books = BookInfo.objects.all()
        book_list = []
        for book in books:
            # 組裝資料
            book_data = {
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment
            }
            book_list.append(book_data)
        return JsonResponse(book_list, safe=False)
    if request.method == 'POST':
        # 從請求獲取資料
        btitle = request.POST.get('btitle')
        bpub_date = request.POST.get('bpub_date')
        bread = request.POST.get('bread')
        bcomment = request.POST.get('bcomment')
        if all([btitle, bpub_date]):
            pass
        else:
            return JsonResponse({'code': 400, 'msg': '缺少引數'})
        # 根據資料建立模型
        book = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        # 校驗資料
        book.save()
        # 組裝資料
        book_data = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        }
        return JsonResponse(book_data)

# 類檢視
class BookView(View):
    def get(self, request):
        books = BookInfo.objects.all()
        book_list = []
        for book in books:
            # 組裝資料
            book_data = {
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment
            }
            book_list.append(book_data)
        return JsonResponse(book_list, safe=False)

    def post(self, request):

        # # 從請求獲取資料
        # btitle = request.POST.get('btitle')
        # bpub_date = request.POST.get('bpub_date')
        # bread = request.POST.get('bread')
        # bcomment = request.POST.get('bcomment')
        # 從body中獲取資料
        data = json.loads(request.body.decode())
        btitle = data.get('btitle')
        bpub_date = data.get('bpub_date')
        if all([btitle, bpub_date]):
            pass
        else:
            return JsonResponse({'code': 400, 'msg': '缺少引數'})
        # 根據資料建立模型
        book = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        book.save()
        book_data = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        }
        return JsonResponse(book_data)

# APIView
class BookAPIView(APIView):
    # permission_classes = (AllowAny,)  # 處理許可權的類 ,允許所有人訪問
    permission_classes = (IsAuthenticated,)  # 處理許可權的類 ,允許認證使用者訪問
    throttle_classes = [AnonRateThrottle] # 處理介面的限流
    def get(self, request):
        books = BookInfo.objects.all()
        book_list = []
        for book in books:
            # 組裝資料
            book_data = {
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment
            }
            book_list.append(book_data)
        return Response(book_list)

    def post(self, request):

        # 從body中獲取資料

        btitle = request.data.get('btitle')
        bpub_date = request.data.get('bpub_date')
        if all([btitle, bpub_date]):
            pass
        else:
            return Response({'code': 400, 'msg': '缺少引數'})
        # 根據資料建立模型
        book = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        book.save()
        book_data = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        }
        return Response(book_data)