修改地址前后端逻辑(作业)
1. 修改地址接口设计和定义
1.请求方式
| 选项 | 方案 |
|---|---|
| 请求方法 | PUT |
| 请求地址 | /addresses/<address_id>/ |
2.请求参数:路径参数 和 JSON
| 参数名 | 类型 | 是否必传 | 说明 |
|---|---|---|---|
| address_id | string | 是 | 要修改的地址ID(路径参数) |
| receiver | string | 是 | 收货人 |
| province_id | string | 是 | 省份ID |
| city_id | string | 是 | 城市ID |
| district_id | string | 是 | 区县ID |
| place | string | 是 | 收货地址 |
| mobile | string | 是 | 手机号 |
| tel | string | 否 | 固定电话 |
| string | 否 | 邮箱 |
3.响应结果:JSON
| 字段 | 说明 |
|---|---|
| code | 状态码 |
| errmsg | 错误信息 |
| id | 地址ID |
| receiver | 收货人 |
| province | 省份名称 |
| city | 城市名称 |
| district | 区县名称 |
| place | 收货地址 |
| mobile | 手机号 |
| tel | 固定电话 |
| 邮箱 |
2. 修改地址后端逻辑实现
提示
- 删除地址后端逻辑和新增地址后端逻辑非常的相似。
- 都是更新用户地址模型类,需要保存用户地址信息。
class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
"""修改和删除地址"""
def put(self, request, address_id):
"""修改地址"""
# 接收参数
json_dict = json.loads(request.body.decode())
receiver = json_dict.get('receiver')
province_id = json_dict.get('province_id')
city_id = json_dict.get('city_id')
district_id = json_dict.get('district_id')
place = json_dict.get('place')
mobile = json_dict.get('mobile')
tel = json_dict.get('tel')
email = json_dict.get('email')
# 校验参数
if not all([receiver, province_id, city_id, district_id, place, mobile]):
return http.JsonResponse({'code': 400,
'errmsg': '缺少必传参数'})
if not re.match(r'^1[3-9]\d{9}$', mobile):
return http.JsonResponse({'code': 400,
'errmsg': '参数mobile有误'})
if tel:
if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
return http.JsonResponse({'code': 400,
'errmsg': '参数tel有误'})
if email:
if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
return http.JsonResponse({'code': 400,
'errmsg': '参数email有误'})
# 判断地址是否存在,并更新地址信息
try:
Address.objects.filter(id=address_id).update(
user = request.user,
title = receiver,
receiver = receiver,
province_id = province_id,
city_id = city_id,
district_id = district_id,
place = place,
mobile = mobile,
tel = tel,
email = email
)
except Exception as e:
logger.error(e)
return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})
# 构造响应数据
address = Address.objects.get(id=address_id)
address_dict = {
"id": address.id,
"title": address.title,
"receiver": address.receiver,
"province": address.province.name,
"city": address.city.name,
"district": address.district.name,
"place": address.place,
"mobile": address.mobile,
"tel": address.tel,
"email": address.email
}
# 响应更新地址结果
return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})