使用者注冊後端邏輯
1. 接收參數
username = request.POST.get('username')
password = request.POST.get('password')
password2 = request.POST.get('password2')
mobile = request.POST.get('mobile')
allow = request.POST.get('allow')
2. 校驗參數
from django import http
import re
# 判斷參數是否齊全
if not all([username, password, password2, mobile, allow]):
return http.HttpResponseBadRequest('缺少必傳參數')
# 判斷使用者名是否是5-20個字元
if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
return http.HttpResponseBadRequest('請輸入5-20個字元的使用者名')
# 判斷密碼是否是8-20個數字
if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
return http.HttpResponseBadRequest('請輸入8-20位的密碼')
# 判斷兩次密碼是否一緻
if password != password2:
return http.HttpResponseBadRequest('兩次輸入的密碼不一緻')
# 判斷手機号是否合法
if not re.match(r'^1[3-9]\d{9}$', mobile):
return http.HttpResponseBadRequest('請輸入正确的手機号碼')
# 判斷是否勾選使用者協定
if allow != 'on':
return http.HttpResponseBadRequest('請勾選使用者協定')
這裡校驗的參數,前端已經校驗過,如果此時參數還是出錯,說明該請求是非正常管道發送的,是以直接禁止掉。
3. 儲存注冊資料
from django.db import DatabaseError
# 儲存注冊資料
try:
User.objects.create_user(username=username, password=password, mobile=mobile)
except DatabaseError:
return render(request, 'register.html', {'register_errmsg': '注冊失敗'})
# 響應注冊結果
return http.HttpResponse('注冊成功,重定向到首頁')
示例:重定向
from django.shortcuts import redirect
from django.urls import reverse
# 響應注冊結果
return redirect(reverse('contents:index'))
狀态保持
1. login()方法介紹
- 狀态保持:
- 将通過認證的使用者的唯一辨別資訊(比如:使用者ID)寫入到目前session會話中
- login()方法:
- Django使用者認證系統提供了
方法login()
- 封裝了寫入session的操作,幫助我們快速實作狀态保持
- Django使用者認證系統提供了
- login()位置:
-
檔案中django.contrib.auth.__init__.py
login(request, user)
-
2. login()方法使用
# 儲存注冊資料
try:
user = User.objects.create_user(username=username, password=password, mobile=mobile)
except DatabaseError:
return render(request, 'register.html', {'register_errmsg': '注冊失敗'})
# 實作狀态保持
login(request, user)
# 響應注冊結果
return redirect(reverse('contents:index'))
使用者名或手機号重複注冊邏輯:
1.請求方式
選項 | 方案 |
---|---|
請求方法 | GET |
請求位址 | /usernames/(?P<username>[a-zA-Z0-9_]{5,20})/count/ |
使用者名重複注冊後端邏輯(通過filter過濾是否有重名使用者,count傳回0或1,0說明沒注冊過,手機号重複注冊邏輯相同)
from utils.response_code import RETCODE
class UsernameCountView(View):
"""判斷使用者名是否重複注冊"""
def get(self, request, username):
"""
:param request: 請求對象
:param username: 使用者名
:return: JSON
"""
count = User.objects.filter(username=username).count()
return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
前端邏輯:
//檢測使用者名是否存在
if (this.error_username == false) {
//拼接請求url
let url = '/usernames/' + this.username + '/count/';
axios.get(url,{
responseType: 'json'
})
.then(response => {
//請求成功的判斷
if (response.data.count == 1) {
this.error_username_message = '使用者名已存在';
this.error_username = true;
} else {
this.error_username = false;
}
})
.catch(error => {
//請求失敗顯示錯誤
console.log(error.response);
})
}
多思考也是一種努力,做出正确的分析和選擇,因為我們的時間和精力都有限,是以把時間花在更有價值的地方。