圖書管理系統後端介面
阿新 • • 發佈:2020-10-29
from django.db import models class Books(models.Model): btitle = models.CharField(max_length= 20 ) bpub_date = models.DateField() bread = models.IntegerField() bcomment = models.IntegerField() is_delete = models.BooleanField(default=False)
1.2 urls.py 中設定路由
from django.urls import path
from books.views import * urlpatterns = [ path('book/', BooksView.as_view()), ]
from django.http import JsonResponse
class BooksView(View): def get(self, request): books = Books.objects.filter(is_delete=False) book_list= books.values('id','btitle','bpub_date','bread','bcomment') book_list = list(book_list) data = { "code": 0 , "msg": "success", "books": book_list } return JsonResponse(data) def post(self, request): body_json = request.body.decode() body_dict= json.loads(body_json) btitle = body_dict.get('btitle') bpub_date = body_dict.get('bpub_date') bread = body_dict.get('bread') bcomment = body_dict.get('bcomment') book = Books(btitle=btitle, bpub_date=bpub_date, bread=bread, bcomment=bcomment) book.save() return JsonResponse({"code": 0 , "msg": "success"}) def put(self, request): body_json = request.body.decode() body_dict = json.loads(body_json) id = body_dict.get('id') btitle = body_dict.get('btitle') bpub_date = body_dict.get('bpub_date') bread = body_dict.get('bread') bcomment = body_dict.get('bcomment') book = Books.objects.get(id=id) book.btitle = btitle book.bpub_date = bpub_date book.bread = bread book.bcomment = bcomment book.save() return JsonResponse({"code": 0, "msg": "success"}) def delete(self, request): body_json = request.body.decode() body_dict = json.loads(body_json) id = body_dict.get('id') book = Books.objects.get(id=id) book.is_delete = True book.save() return JsonResponse({"code": 0, "msg": "success"})
2.測試介面
2.1 測試獲取所有圖書介面
http://127.0.0.1:8000/book/
返回結果
http://127.0.0.1:8000/book/
.postman測試提交資料
{
"btitle":"紅樓夢",
"bpub_date":"2018-02-04",
"bread": 100 ,
"bcomment": 0
}
結果
2.3 測試修改圖書介面
http://127.0.0.1:8000/books/postman測試提交資料 { "id":5, "btitle":"紅樓夢", "bpub_date":"2018-02-04", "bread":100, "bcomment":0 }
結果
http://127.0.0.1:8000/books/ postman測試提交資料 { "id":15 }