使用Django完成接口API的开发(REST)

使用Django实现REST

    • urls.py
    • views.py

urls.py

代码展示

from django.conf.urls import url

from . import views

urlpatterns = [
    # 列表视图的路由
    url(r'^books/$', views.BookListView.as_view()),
    # 详情视图的路由
    url(r'^books/(?P\d+)/$',views.BookDetailView.as_view()),
]

views.py

  • 导入的库
from django.views import View

from .models import BookInfo
from django.http import JsonResponse,HttpResponse
import json
  • 列表视图(包含了查询所有记录以及添加记录)
class BookListView(View):
    '''列表视图'''
    def get(self, request):
        '''查询所有图书接口'''
        bookList = []

        # 1. 查询出所有图书模型
        books = BookInfo.objects.all()
        # 2.遍历查询集,取出里面的每个书籍模型对象, 把模型对象转换成字典
        for book in books:
            bookList.append({
     
                'book_id' : book.id,
                'btitle' : book.btitle,
                'bpub_date' : book.bpub_date,
                'bread' : book.bread,
                'bcomment' : book.bcomment,
                'is_delete' : book.is_delete
            })
        # 3.响应
        return JsonResponse(bookList, safe=False)



    def post(self, request):
        '''新增图书接口'''
        # 1.获取前端传入的请求体数据
        json_str_bytes = request.body
        # 2.把bytes类型的json字符串转换成json_str, 利用json.loads将json字符串转换成json字典/列表
        json_str = json_str_bytes.decode()
        json_dict = json.loads(json_str)
        # 3.创建模型对象并保存
        book = BookInfo(
            btitle = json_dict['btitle'],
            bpub_date = json_dict['bpub_date']
        )
        book.save()
        # 第二种增加方法
        # BookInfo.objects.create(
        #     btitle=json_dict['btitle'],
        #     bpub_date=json_dict['bpub_date']
        # )

        # 4.新增的模型转换成字典
        book_dict = {
     
            'book_id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'is_delete': book.is_delete
        }
        # 5.响应新增的数据
        return JsonResponse(book_dict, safe=False)
  • 详情视图(查询单个记录,删除单个记录,修改单条记录)
class BookDetailView(View):
    '''详情视图'''

    def get(self,request, pk):
        '''查询所有图书接口'''
        # 1.获取指定pk的模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse({
     'message':'查询的数据不存在'}, status=404)
        # 2.模型对象转字典
        book_dict = {
     
            'book_id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'is_delete': book.is_delete
        }
        # 3.响应
        return JsonResponse(book_dict)

    def put(self, request, pk):
        '''修改指定图书接口'''
        # 1.查询要修改的模型对象
        book = BookInfo.objects.get(id=pk)
        # 2.获取前端传入的新数据(把数据转换成字典)
        # json_str_bytes = request.body
        # json_str = json_str_bytes.decode()
        # json_dict = json.loads(json_str)
        json_dict = json.loads(request.body.decode())

        # 3.重新给模型指定的属性赋值
        book.btitle = json_dict['btitle']
        book.bpub_date = json_dict['bpub_date']
        # 4.调用save保存
        book.save()
        # 5.把修改后的模型转换成字典
        book_dict = {
     
            'book_id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'is_delete': book.is_delete
        }
        # 6.响应
        return JsonResponse(book_dict, safe=False)



    def delete(self, request, pk):
        '''删除指定图书接口'''
        # 1. 查询指定的模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse({
     'message': '删除的数据不存在'}, status=404)
        # 2.删除指定的模型对象
        book.delete()   # 物理删除,在数据库里将记录删除

        # 逻辑删除,这里将字段更改了
        # book.is_delete = True
        # book.save()

        # 3.删除成功后有状态响应码,不可有状态响应体
        return HttpResponse(status=200)

谢谢观看~

使用Django完成接口API的开发(REST)_第1张图片

你可能感兴趣的:(后端,Python,rest,django,api)