圖書管理後端介面
阿新 • • 發佈:2020-10-29
1.圖書管理系統後端介面
1.1 books/models.py 中設定表
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 . import views
urlpatterns = [
path('book/', views.BooksView.as_view()),
]
1.3 book/views.py 檢視函式
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')
2.測試介面
2.1 測試獲取所有圖書介面
返回結果
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/books/book/
-
返回結果
{
"code": 0,
"msg": "success",
"books": [
{
"id": 4,
"btitle": "抗日神劇",
"bpub_date": "2020-08-11",
"bread": 1234,
"bcomment": 779
},
{
"id": 5,
"btitle": "qwe",
"bpub_date": "2020-09-09",
"bread": 123,
"bcomment": 5555
},
{
"id": 11,
"btitle": "三重門",
"bpub_date": "2020-02-12",
"bread": 100,
"bcomment": 0
}
]
}
2.2 測試建立圖書介面
http://127.0.0.1:8000/books/book/
-
postman測試提交資料
{
"btitle":"紅樓夢",
"bpub_date":"2018-02-04",
"bread":100,
"bcomment":0
}
2.3 測試修改圖書介面
http://127.0.0.1:8000/books/book/
-
postman測試提交資料
{
"id":15,
"btitle":"紅樓夢2",
"bpub_date":"2018-02-04",
"bread":100,
"bcomment":0
}