前言
- 本篇来学习使用Django开发REST 接口
列表视图
""" GET/books/提供所有记录 POST/books/新增一条记录 GET/books/<pk>/提供指定id的记录 PUT/books/<pk>/修改指定id的记录 DELETE/books/<pk>/删除指定id的记录 """ # 列表视图:路由后面没有pk/id class BooksAPIVIew(View): """ 查询所有图书、增加图书 """ def get(self, request): """ 查询所有图书 路由:GET /books/ """ queryset = BookInfo.objects.all() book_list = [] for book in queryset: book_list.append({ 'id': book.id, 'btitle': book.name, 'bpub_date': book.pub_date, 'bread': book.readcount, 'bcomment': book.commentcount, }) return JsonResponse(book_list, safe=False) def post(self, request): """ 新增图书 路由:POST /books/ """ json_bytes = request.body json_str = json_bytes.decode() book_dict = json.loads(json_str) book = BookInfo.objects.create( name=book_dict.get('name'), pub_date=datetime.strptime(book_dict.get('pub_date'), '%Y-%m-%d').date() ) book.save() rsp_json = { 'id': book.id, 'btitle': book.name, 'bpub_date': book.pub_date, 'bread': book.readcount, 'bcomment': book.commentcount, } return JsonResponse(rsp_json, status=201)
- 查询所有书籍 http://127.0.0.1:8000/books/
- 新增书籍
curl --location --request POST 'http://127.0.0.1:8000/books/' \ --header 'Content-Type: application/json' \ --data-raw '{ "name":"测试开发秘籍", "pub_date":"2022-09-24" }'
- 查看数据库
详情视图
# 详情视图:路由后面pk/id class BookAPIView(View): def get(self, request, pk): """ 获取单个图书信息 路由: GET /books/<pk>/ """ try: book = BookInfo.objects.get(pk=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) return JsonResponse({ 'id': book.id, 'btitle': book.name, 'bpub_date': book.pub_date, 'bread': book.readcount, 'bcomment': book.commentcount }) def put(self, request, pk): """ 修改图书信息 路由: PUT /books/<pk> """ try: book = BookInfo.objects.get(pk=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) json_bytes = request.body json_str = json_bytes.decode() book_dict = json.loads(json_str) # 此处详细的校验参数省略 book.name = book_dict.get('name') book.pub_date = datetime.strptime(book_dict.get('pub_date'), '%Y-%m-%d').date() book.save() return JsonResponse({ 'id': book.id, 'btitle': book.name, 'bpub_date': book.pub_date, 'bread': book.readcount, 'bcomment': book.commentcount }) def delete(self, request, pk): """ 删除图书 路由: DELETE /books/<pk>/ """ try: book = BookInfo.objects.get(pk=pk) except BookInfo.DoesNotExist: return HttpResponse(status=404) book.delete() return HttpResponse(status=204)
- 查询单个书籍
curl --location --request GET 'http://127.0.0.1:8000/books/7' \ --header 'Content-Type: application/json' \ --data-raw '{ "name":"MySQL从删库到跑路", "pub_date":"2022-09-25" }'
- 修改书籍
curl --location --request PUT 'http://127.0.0.1:8000/books/7/' \ --header 'Content-Type: application/json' \ --data-raw '{ "name":"MySQL从删库到跑路", "pub_date":"2022-09-25" }'
- 删除单个书籍
curl --location --request DELETE 'http://127.0.0.1:8000/books/8/'