0.效果展示
1.后端代码
# coding:utf-8from . import api
from flask import request, jsonify, current_app, session
from ihome.utils.response_code import RET
from ihome import redis_store, db, constants
from ihome.models import User
from sqlalchemy.exc import IntegrityError
import re@api.route("/users", methods=["POST"])
def register():"""注册请求的参数: 手机号、短信验证码、密码、确认密码参数格式:json"""# 获取请求的json数据,返回字典req_dict = request.get_json()mobile = req_dict.get("mobile")sms_code = req_dict.get("sms_code")password = req_dict.get("password")password2 = req_dict.get("password2")# 校验参数if not all([mobile, sms_code, password, password2]):return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")# 判断手机号格式if not re.match(r"1[34578]\d{9}", mobile):# 表示格式不对return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")if password != password2:return jsonify(errno=RET.PARAMERR, errmsg="两次密码不一致")# 从redis中取出短信验证码try:real_sms_code = redis_store.get("sms_code_%s" % mobile)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="读取真实短信验证码异常")# 判断短信验证码是否过期if real_sms_code is None:return jsonify(errno=RET.NODATA, errmsg="短信验证码失效")# 删除redis中的短信验证码,防止重复使用校验try:redis_store.delete("sms_code_%s" % mobile)except Exception as e:current_app.logger.error(e)# 判断用户填写短信验证码的正确性if real_sms_code != sms_code:return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")# 判断用户的手机号是否注册过# try:# user = User.query.filter_by(mobile=mobile).first()# except Exception as e:# current_app.logger.error(e)# return jsonify(errno=RET.DBERR, errmsg="数据库异常")# else:# if user is not None:# # 表示手机号已存在# return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")# 盐值 salt# 注册# 用户1 password="123456" + "abc" sha1 abc$hxosifodfdoshfosdhfso# 用户2 password="123456" + "def" sha1 def$dfhsoicoshdoshfosidfs## 用户登录 password ="123456" "abc" sha256 sha1 hxosufodsofdihsofho# 保存用户的注册数据到数据库中user = User(name=mobile, mobile=mobile)# user.generate_password_hash(password)user.password = password # 设置属性try:db.session.add(user)db.session.commit()except IntegrityError as e:# 数据库操作错误后的回滚db.session.rollback()# 表示手机号出现了重复值,即手机号已注册过current_app.logger.error(e)return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")except Exception as e:db.session.rollback()# 表示手机号出现了重复值,即手机号已注册过current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")# 保存登录状态到session中session["name"] = mobilesession["mobile"] = mobilesession["user_id"] = user.id# 返回结果return jsonify(errno=RET.OK, errmsg="注册成功")
modle.py中
class User(BaseModel, db.Model):"""用户"""__tablename__ = "ih_user_profile"id = db.Column(db.Integer, primary_key=True) # 用户编号name = db.Column(db.String(32), unique=True, nullable=False) # 用户暱称password_hash = db.Column(db.String(128), nullable=False) # 加密的密码mobile = db.Column(db.String(11), unique=True, nullable=False) # 手机号real_name = db.Column(db.String(32)) # 真实姓名id_card = db.Column(db.String(20)) # 身份证号avatar_url = db.Column(db.String(128)) # 用户头像路径houses = db.relationship("House", backref="user") # 用户发布的房屋orders = db.relationship("Order", backref="user") # 用户下的订单# 加上property装饰器后,会把函数变为属性,属性名即为函数名@propertydef password(self):"""读取属性的函数行为"""# print(user.password) # 读取属性时被调用# 函数的返回值会作为属性值# return "xxxx"raise AttributeError("这个属性只能设置,不能读取")# 使用这个装饰器, 对应设置属性操作@password.setterdef password(self, value):"""设置属性 user.passord = "xxxxx":param value: 设置属性时的数据 value就是"xxxxx", 原始的明文密码:return:"""self.password_hash = generate_password_hash(value)# def generate_password_hash(self, origin_password):# """对密码进行加密"""# self.password_hash = generate_password_hash(origin_password)
2.注册html代码
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>爱家-注册</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/register.css" rel="stylesheet">
</head>
<body><div class="container"><div class="logo-bar"><a href="/"><img src="/static/images/logo@128x59.png"></a></div><form class="form-register"><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-mobile fa-2x fa-fw"></i></div><input type="number" class="form-control" name="mobile" id="mobile" placeholder="手机号" required></div></div><div class="error-msg" id="mobile-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-image fa-lg fa-fw"></i></div><input type="text" class="form-control" name="imagecode" id="imagecode" placeholder="图片验证码" required><div class="input-group-addon image-code" onclick="generateImageCode();"><img src=""></div></div></div><div class="error-msg" id="image-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-envelope-o fa-lg fa-fw"></i></div><input type="text" class="form-control" name="phonecode" id="phonecode" placeholder="短信验证码" required><div class="phonecode input-group-addon"><a class="phonecode-a" href="javascript:;" onclick="sendSMSCode();">获取验证码</a></div></div></div><div class="error-msg" id="phone-code-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password" id="password" placeholder="密码" required></div></div><div class="error-msg" id="password-err"><i class="fa fa-exclamation-circle"></i><span></span></div><div class="form-group form-group-lg"><div class="input-group"><div class="input-group-addon"><i class="fa fa-lock fa-lg fa-fw"></i></div><input type="password" class="form-control" name="password2" id="password2" placeholder="确认密码" required></div></div><div class="error-msg" id="password2-err"><i class="fa fa-exclamation-circle"></i><span></span></div><button type="submit" class="btn btn-lg btn-theme btn-block">立即注册</button><p class="login-a">已有账号,<a href="/login.html">立即登陆</a></p></form></div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/js/ihome/register.js"></script>
</body>
</html>
3.注册js代码
$(document).ready(function() {generateImageCode();$("#mobile").focus(function(){$("#mobile-err").hide();});$("#imagecode").focus(function(){$("#image-code-err").hide();});$("#phonecode").focus(function(){$("#phone-code-err").hide();});$("#password").focus(function(){$("#password-err").hide();$("#password2-err").hide();});$("#password2").focus(function(){$("#password2-err").hide();});// 为表单的提交补充自定义的函数行为 (提交事件e)$(".form-register").submit(function(e){// 阻止浏览器对于表单的默认自动提交行为e.preventDefault();var mobile = $("#mobile").val();var phoneCode = $("#phonecode").val();var passwd = $("#password").val();var passwd2 = $("#password2").val();if (!mobile) {$("#mobile-err span").html("请填写正确的手机号!");$("#mobile-err").show();return;} if (!phoneCode) {$("#phone-code-err span").html("请填写短信验证码!");$("#phone-code-err").show();return;}if (!passwd) {$("#password-err span").html("请填写密码!");$("#password-err").show();return;}if (passwd != passwd2) {$("#password2-err span").html("两次密码不一致!");$("#password2-err").show();return;}// 调用ajax向后端发送注册请求var req_data = {mobile: mobile,sms_code: phoneCode,password: passwd,password2: passwd2,};var req_json = JSON.stringify(req_data);$.ajax({url: "/api/v1.0/users",type: "post",data: req_json,contentType: "application/json",dataType: "json",headers: {"X-CSRFToken": getCookie("csrf_token")}, // 请求头,将csrf_token值放到请求中,方便后端csrf进行验证success: function (resp) {if (resp.errno == "0") {// 注册成功,跳转到主页location.href = "/index.html";} else {alert(resp.errmsg);}}})});
})