హలో,我是Charlie!
在Day12當中,我們完成了商品詳情顯示的API,而今天我們將完成後端的購物車總商品顯示跟加入購物車的API。
================================◉‿◉=================================
首先在keyboardmarket\urls.py中新增usercart的urlpattern:
url('usercart',include('usercart.urls'))
接著在usercart中新增urls.py,並且新增urlpattern:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$',views.usercart)
]
接著在views.py當中新增usercart def,因為購物車的各種操作都需要token,所以使用logincheck來裝飾視圖函數:
from tools.R import R
from tools.login_check import logincheck
from .models import Cart
@logincheck('GET','POST','PUT','DELETE')
def usercart(request):
return R.ok("API reachable")
首先是新增購物車的方法,新增購物車的話會需要幾個東西:
所以接收到的JSON必須包含這三個,才能從user跟product當中撈取正確的用戶跟商品,amount則是加入購物車的數量。
所以首先我們先創立用來處理購物車請求的model:
import json
class CartModel:
def __init__(self,product_id = 0,username = "",amount = 0):
self.product_id = product_id
self.username = username
self.amount = amount
def fromJson(self,data):
jsondata = json.loads(data)
self.product_id = jsondata["pid"]
self.username = jsondata["username"]
self.amount = jsondata["amount"]
接著在views.py當中分別引入Cart model、Product model、User model、CartStatus Enum:
from .models import Cart
from tools.models.cartModel import CartModel
from product.models import Product
from users.models import User
from tools.db import CartStatus
然後判斷request method為POST,判斷如果商品存在、數量合理則可加入購物車,如果商品存在的話就加上數量,如果商品不存在的話則創建:
if request.method == "POST":
req = request.body
ucart = CartModel()
ucart.fromJson(req)
if ucart.amount == 0:
return R.badRequest("Add cart amount can not be 0")
product = Product.objects.filter(id = ucart.product_id)
if not product:
return R.badRequest("Product does not exist")
product = product[0]
if ucart.amount > product.stored_amount:
return R.badRequest("Add cart amount reach maximum stored amount")
user = User.objects.filter(name = ucart.username)
if not user:
return R.badRequest("User does not exist")
user = user[0]
dbcart = Cart.objects.filter(user = user).filter(product = product)
if dbcart:
dbcart[0].amount += ucart.amount
dbcart[0].save()
else:
cart = Cart.objects.create(
product = product,
user = user,
amount = ucart.amount,
status = CartStatus.activate.value
)
cart.save()
用POSTMAN測試:
還有購物車的總商品顯示,先在Cart model當中新增toJson方法:
def toJson(self):
data = {}
data["id"] = self.id
data["product"] = self.product.toJson()
data["username"] = self.user.name
data["amount"] = self.amount
data["status"] = self.status
data["created_time"] = self.created_time
data["modified_time"] = self.modified_time
return data
在urls.py中新增路徑:
url(r'/(?P<username>[\w]{1,55})$',views.usercart),
並且在usercart中新增參數跟方法:
@logincheck('GET','POST','PUT','DELETE')
def usercart(request,username = None):
if request.method == "GET":
user = User.objects.filter(name = username)
if not user:
return R.badRequest("User does not exist")
user = user[0]
carts = Cart.objects.filter(user = user)
return R.ok(carts)
測試:
================================◉‿◉=================================
Day13結束了!在今天我們完成了購物車的商品顯示跟加入購物車,明天我們將完成前端的部分,See ya next day!