美文网首页
RESTful API笔记(三):django项目应用RESTf

RESTful API笔记(三):django项目应用RESTf

作者: warmsirius | 来源:发表于2019-08-16 17:13 被阅读0次

    1、对于FBV

    from django.http import JsonResponse
    from django.views.decorators.csrf import csrf_exempt
    from api.models import Book
    
    
    @csrf_exempt
    def books(request):
        if request.method == 'GET':
            book_list = Book.objects.all()
            book_list_json = []
            for book in book_list:
                book_list_json.append(book.to_dict())
            data = {
                'status': 200,
                'message': 'ok',
                'data': book_list_json
            }
            return JsonResponse(data)
        elif request.method == 'POST':
            b_name = request.POST.get('b_name')
            b_price = request.POST.get('b_price')
    
            book = Book()
            book.b_name = b_name
            book.b_price = b_price
            book.save()
    
            data = {"status": 201,
                    "message": 'add success',
                    'data': book.to_dict()
    
                    }
            return JsonResponse(data, status=201)
    
    @csrf_exempt
    def book(request, book_id):
        if request.method == 'GET':
            book = Book.objects.get(pk=book_id)
            data = {
                'status': 200,
                'message': 'ok',
                'data': book.to_dict()
            }
            return JsonResponse(data=data)
        elif request.method == 'DELETE':
            book_obj = Book.objects.get(pk=book_id)
            book_obj.delete()
            data = {
                'message': 'delete success',
                'status': 204,
            }
            return JsonResponse(data=data, status=204)
    

    2、对于CBV

    待补充~

    相关文章

      网友评论

          本文标题:RESTful API笔记(三):django项目应用RESTf

          本文链接:https://www.haomeiwen.com/subject/ciatsctx.html