当前位置:网站首页>Rice mall registration
Rice mall registration
2022-07-23 11:16:00 【ZXY_ lucky】
1.settings To configure
# register
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # drf frame
'corsheaders', # Cross domain pip install cors
'users', # Register user subapplication subapplication
'goods', # Register product subapplication
]
# Cross domain
MIDDLEWARE = [
"middleware.Loginmiddleware.CheckUser",
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware', # Cross domain middleware
]
# Configuration database
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':'localhost',
'USER':'root',
'POST':3306,
"PASSWORD":'123123',
'NAME':"h2111_p5"
}
}
# Configure time
TIME_ZONE = 'Asia/Shanghai'
# Configure cross domain related configuration items
# notes : Words cannot be written wrong
CORS_ORIGIN_WHITELIST = [ # To configure ip White list
"http://127.0.0.1:8080",
"http://localhost:8080",
"http://127.0.0.1:8000",
"http://127.0.0.1:8866"
]
CORS_ALLOW_CREDENTIALS = True # allow cookie
CORS_ALLOW_METHODS = ("*") # Configure the allowed request methods
CORS_ALLOW_HEADERS = ("*") # Configure the allowed request headers
2. mount this database
import pymysql
pymysql.install_as_MySQLdb()
3. Routing distribution
Main route
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path("user/",include("users.urls")),
path("goods/",include("goods.urls"))
]
Create... Under sub application urls.py file
from django.urls import path
from users import views
urlpatterns = [
path("check/username/<str:username>/",views.CheckUserNameView.as_view()), # Check the user name
path("check/mobile/<str:mobile>/",views.CheckMobileView.as_view()), # Check your cell phone number
path("check/password/",views.CheckPasswordView.as_view()), # Detect password
path("check/password2/",views.CheckPasswordView2.as_view()), # Check to enter the password again
path("check/image/<str:uuid>/",views.VerImageView.as_view()), # Generate verification code
path("check/img/code/",views.CheckCodeView.as_view()), # Check the verification code
path("reg/",views.RegView.as_view()), # register
path("login/",views.LoginView.as_view()), # Sign in
path("index/images/",views.IndexImageView.as_view()), # picture
path("info/",views.UserInfoView.as_view()), # Get user information
path("addr/",views.AddrView.as_view()), # User receiving address information
path("pwd/change/",views.ChangePwdView.as_view()), # Change Password
]
4. Create model classes
Create model classes as required
# The user model
class User(models.Model):
username = models.CharField(" user name ",max_length=32,unique=True)
password = models.CharField(" password ",max_length=32)
mobile = models.CharField(" cell-phone number ",max_length=16)
class Meta:
verbose_name = ' User table '
verbose_name_plural = verbose_name
def __str__(self):
return "%s (%s)" % (self.username,self.mobile)
5. Judge user name
Back end
from rest_framework.response import Response
from rest_framework.views import APIView
from users.models import User,IndexImage,Addr
from django.http import HttpResponse
# Define a class that checks user names to try
class CheckUserNameView(APIView):
def get(self,request,username):
# Judge whether the user name is entered , No input username = NULL
if not username:
return Response({
"code":400,
"msg":' The user didn't type '
})
# Check the length of user name
if not (6<= len(username) <= 32):
return Response({
"code":400,
"msg":' User length does not match '
})
# Check whether the user name exists
# Query whether the database has the current user name
user_count = User.objects.filter(username=username).count()
if user_count:
# The number of users queried according to the user name is not 0
return Response({
"code":400,
"msg":' The user already exists '
})
return Response({
"code":200,
"msg":' User input succeeded '
})
front end
// Verification method of user name
let validateName = (rule, value, callback) => {
console.log(" Verify username , The rules ", rule, " user name ", value, " Callback function ", callback)
// TODO Verify username
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
let url = "/user/check/username/" + value + "/";
this.$axios.get(url).then((result) => {
if (result.data.code == 200){
return callback();
}else{
return callback(new Error(result.data.msg));
}
}).catch((err) => {
console.log(err)
alert(' Wrong judgment ')
});
};
6. Judge the cell phone number
Back end
import re
# Cell phone number verification
class CheckMobileView(APIView):
def get(self,request,mobile):
rule = r'^1[3-9][0-9]{9}$' # Define the regular mobile number
rs = re.findall(rule,mobile) # The result is a list
if not rs:
return Response({
"code":400,
"msg":' The format of mobile phone is wrong '
})
# The format of mobile phone number is correct , Uniqueness verification is required
mobile_count = User.objects.filter(mobile=mobile).count()
if mobile_count:
return Response({
"code":400,
"msg":" Cell phone number already exists "
})
return Response({
"code":200,
"msg":" Correct input of mobile phone number "
})
front end
// Verification method of mobile phone number
let validateMobile = (rule, value, callback) => {
console.log(" Check cell phone number , The rules ", rule, " cell-phone number ", value, " Callback function ", callback)
// TODO Check cell phone number
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
let url = "/user/check/mobile/" + value + "/";
this.$axios.get(url).then((resp)=>{
if (resp.data.code == 200){
return callback();
}else{
return callback(new Error(resp.data.msg))
}
}).catch((err)=>{
console.log(err)
alert(" Report errors ")
})
};
7. Check the password
Back end
# password verifiers
class CheckPasswordView(APIView):
def post(self,request):
pwd = request.data.get("pwd")
# check
if not (6<= len(pwd) <= 32):
return Response({
"code":400,
"msg":' The length of the password doesn't match '
})
return Response({
"code":200,
"msg":' Password entered successfully '
})
front end
// Verification method of password
let validatePass = (rule, value, callback) => {
console.log(" Check the password , The rules ", rule, " password ", value, " Callback function ", callback)
// TODO Check the password
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
let url = "/user/check/password/"
this.$axios.post(url,{
"pwd":value}).then((resp)=>{
if (resp.data.code == 200){
return callback();
}else{
return callback(new Error(resp.data.msg))
}
}).catch((err)=>{
console.log(err)
alert(" Report errors ")
})
};
8. Confirm the password
Back end
# Verify whether the passwords entered twice are consistent
class CheckPasswordView2(APIView):
def post(self,request):
pwd = request.data.get('pwd') # password
pwd1 = request.data.get("pwd1") # Enter the password again
if pwd != pwd1:
return Response({
"code":400,
"msg":" Password inconsistency "
})
return Response({
"code":200,
"msg":" The password is the same "
})
front end
// Confirm the verification method of password
let validateConfirmPass = (rule, value, callback) => {
console.log(" Verify the confirmation password , The rules ", rule, " Second input password ", value, " Callback function ", callback)
// TODO Verify the confirmation password
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
let url = '/user/check/password2/';
this.$axios.post(url,{
"pwd":this.RegisterUser.pass,"pwd1":value})
.then((resp)=>{
if(resp.data.code==200){
return callback();
}else{
return callback(new Error(resp.data.msg))
}
}).catch((err)=>{
console.log(err)
alert(' Report errors ')
})
};
9. Generate verification code / Verification code
Back end
# Generate verification code
import random
class VerImageView(APIView):
def get(self,request,uuid):
# 1. Generate the string needed to create the verification code random
code = str(random.randint(1000,9999))
# 2. According to the string into a picture
from captcha.image import ImageCaptcha
img = ImageCaptcha() # Instantiate the class of the verification code
img_pic = img.generate(code) # The generator generates a verification code image
print(' The resulting image is ', img_pic) # The return value is night song IO Byte stream
# return HttpResponse(img_pic,content_type="image/png")
# Save the CAPTCHA to redis
import redis
r = redis.Redis(host="127.0.0.1",port=6379,password='123123')
r.set(uuid,code,ex=60 * 5) # Failure time 5 minute
print(uuid)
print(code)
return HttpResponse(img_pic, content_type="image/png")
class CheckCodeView(APIView):
def post(self,request):
code = request.data.get("code") # The verification code entered by the user
uuid = request.data.get("uuid") # Unique identifier of the user
# 1. Connect to database , Take out uuid, The corresponding verification code
import redis
r = redis.Redis(host='127.0.0.1',password="123123")
sys_code = r.get(uuid)
# If uuid The corresponding data is empty , Description verification code has expired
if not sys_code:
return Response({
"code":400,
"msg":" The verification code has expired "
})
# take code Convert to string
sys_code_str = sys_code.decode()
# 2. The verification code entered by the user is compared with the verification code of the database
if sys_code_str != code:
# If it's not consistent , Verification code error
return Response({
"code":400,
"msg":" Verification code error ",
})
# If the same , The life verification code passed
return Response({
"code":200,
"msg":" Check by "
})
front end
// Generate image verification code address
genImageCode() {
// Generate a uuid
this.imageCodeID = uuid4()
// Generate a picture verification code address
this.iamgeCodeUrl = "user/check/image/" + this.imageCodeID + "/"
},
// Check the picture verification code
let validateImageCode = (rule, value, callback) => {
console.log(" Verification code , The rules ", rule, " 2. Verification code ", value, " Callback function ", callback)
// TODO Verification code
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
this.$axios.post('/user/check/img/code/',{
"uuid":this.imageCodeID,"code":value}).then((resp)=>{
if(resp.data.code==200){
return callback();
}else{
return callback(new Error(resp.data.msg))
}
}).catch((err)=>{
console.log(err)
alert(" Page error reporting ")
})
};
10. register
Back end
class RegView(APIView):
def post(self,request):
username = request.data.get('username')
password = request.data.get('password')
mobile = request.data.get('mobile')
agree = request.data.get('agree')
# Judge whether the user has checked the agreement
if not int(agree):
print(agree)
return Response({
"code":400,
"msg":" Please check the agreement "
})
# Judge whether the user input information is correct
if not username or not password or not mobile:
return Response({
"code":400,
"msg":" Wrong parameter input "
})
# TODO Verify user name 、 password 、 cell-phone number
# The calibration is finished , Write to database
try:
User.objects.create(
username=username,
password=password,
mobile=mobile
)
return Response({
"code" :200,
"msg":" Registered successfully "
})
except Exception as e:
return Response({
"code":400,
"msg":" Registration failed "
})
front end
// User registration
Register() {
// Whether to agree with the user agreement
if (!this.aggree) {
this.flag = true
return
}
// Checked , Then the prompt message will not be displayed
this.flag = false
// adopt element Custom form validation rules , Verify the user information entered by the user
this.$refs["ruleForm"].validate((valid) => {
if (valid) {
// TODO Registered users
this.$axios.post('/user/reg/',{
'username':this.RegisterUser.name,
'password':this.RegisterUser.pass,
'mobile':this.RegisterUser.mobile,
'agree':this.aggree,
}).then((resp)=>{
if(resp.data.code == 200){
// alert(' Registered successfully ')
// Empty data
this.RegisterUser.name = ""
this.RegisterUser.pass = ""
this.RegisterUser.mobile = ""
this.RegisterUser.confirmPass = "",
this.RegisterUser.imageCode = "",
this.aggree = false
// Close the registration pop-up
this.isRegister = false
this.notifySucceed(resp.data.msg)
}else{
// alert(' Registration failed ')
this.notifyError(resp.data.msg)
}
}).catch((err)=>{
console.log(err)
alert(' Page error reporting ')
})
} else {
return false;
}
});
},
边栏推荐
猜你喜欢

Web server failed to start. Port 8080 was already in use.

从零开始的pytorch小白使用指北

图片模糊处理批量生产模糊数据集

How to merge the website content with video and audio separated? How to write batch download code?

大厂面试机器学习算法(6)时间序列分析
![[pytho-flask筆記5]藍圖簡單使用](/img/0a/00b259f42e2fa83d4871263cc5f184.png)
[pytho-flask筆記5]藍圖簡單使用

JDBC database connection pool

主从同步步骤读写分离+自遇错误分享

Master slave synchronization step read / write separation + self encountered error sharing

牛客刷题记录--Mysql
随机推荐
Anr error encountered
【无标题】
Basic concepts of software testing
Keras保存训练过程中的最好模型
Summary of common commands of vim
ShardingSphere分库分表方案
sprintboot中使用缓存时候,数据加载不出来
Pycharm occupies C disk
知识点回顾
Pywinauto+某应用程序(学习至第9讲)--受阻
項目部署(簡版)
面试必备之数据库专题
3. Threads in flask
【无标题】
【Pyradiomics】提取的影像组学特征值不正常(很多0和1)
Matrix vector derivation in machine learning
【无标题】
【无标题】
MySQL-8.0.28 用户操作 or 用户权限操作
IO should know and should know