这里记录登录页面验证码的做法,采取的是前后端分离的做法,前端用Vue,后端用Flask

首先是GIF效果图:

elementui只在提交是验证_flask

后端返回的数据结构(base64字符串,response.data.img):

elementui只在提交是验证_vue.js_02

 

1、Vue前端页面基本采用Ruoyi Ui里面的登录页面代码,里面的一些方法进行重写;

  • 首先是单个vue文件里网页内容<template></template>部分:
<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">通用后台管理系统</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
          prefix-icon="el-icon-user"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
          prefix-icon="el-icon-lock"
          show-password
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaOnOff">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
          prefix-icon="el-icon-key"
        >
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img" />
        </div>
      </el-form-item>
      <el-checkbox
        v-model="loginForm.rememberMe"
        style="margin: 0px 0px 25px 0px"
        >记住密码</el-checkbox>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'"
            >立即注册</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2021-2022 VIP.vip All Rights Reserved.</span>
    </div>
  </div>
</template>
  • 交互方法<Script></Script>部分:

1) Axios请求配置。

function get(url, params, response_type) {
    let newAxios = axios.create()
    let promise;
    // 请求超时时间
    newAxios.defaults.timeout = 10000;
    return new Promise((resolve, reject) => {
        promise = newAxios.get(url, {
            params: params,
            responseType: response_type
        });
        promise.then((response) => {
            resolve(response);
        }).catch(error => {
            reject(error);
        })
    })
}
Vue.prototype.get = get

2) toLogin登录方法。

export function toLogin(data) {
	return this.get('/login/toLogin', [data])
}

3) 其他js代码,其中setToken,setUserInfo,setInstId,removeAll方法不重要,这些方法是登录后保存一些用户信息用的,因此读者可自行忽略掉。

<script>
import { toLogin } from "@/api/login.js";
import {
  setToken,
  setUserInfo,
  setInstId,
  removeAll,
} from "../../utils/permission";
export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "admin",
        password: "123456",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaOnOff: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
  },
  methods: {
    getCode() {
      this.get("/getImgCode").then((res) => {
        this.codeUrl = res.data.img;
      });
    },
    // 登录请求
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          let _this = this;
          toLogin(_this.loginForm)
            .then((res) => {
              removeAll(); //清除所有本地缓存
              if (res.status === 200) {
                this.$store.commit("getUserId", res.data.userInfo.ID);
                setToken(res.data.token);
                let fixedUserInfo = res.data.userInfo;
                this.get(
                  "/myinfo_img_download",
                  [fixedUserInfo.img, fixedUserInfo.ID, "login"],
                  ""
                ).then((res) => {
                  if (res.data.code != 200) {
                    _this.$message.error(res.data.msg);
                    fixedUserInfo.img = res.data.imgs;
                    setUserInfo(JSON.stringify(fixedUserInfo));
                    _this.$router.push("/");
                  } else {
                    fixedUserInfo.img = res.data.imgs;
                    setUserInfo(JSON.stringify(fixedUserInfo));
                    _this.$router.push("/");
                  }
                });
                setInstId(res.data.inst_id);
                _this.showMsg(res.data.userInfo.nickname);
              } else if (res.status === 201) {
                _this.$message({
                  message: "该用户已被停用!",
                  type: "warning",
                });
              } else if (res.status === 304) {
                _this.$message({
                  message: "验证码错误!",
                  type: "error",
                });
              } else if (res.status === 500) {
                _this.$message({
                  message: "密码错误!",
                  type: "error",
                });
              } else {
                _this.$message({
                  message: "用户名不存在!",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    // 消息通知
    showMsg(realName) {
      this.$notify({
        title: "提示",
        dangerouslyUseHTMLString: true,
        message: "尊敬的<strong>" + realName + "</strong>,欢迎回来。",
        type: "success",
        duration: 2000,
      });
    },
  },
};
</script>

4) CSS代码,注意background-image中的图片要自己准备。

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
  font-weight: 600;
  font-size: 21px;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  display: flex;

  img {
    margin-left: 10px;
    position: relative;
    top: -3px;
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>

login-backg.jpg 

elementui只在提交是验证_前端_03

 

2、Flask的代码则参考另外一篇网上的代码段。

from flask import Flask, render_template,\
    request, jsonify, make_response, Response, send_file,session,send_from_directory
from flask_cors import CORS
import json
import base64

app = Flask(__name__)
''' 解决后端跨域问题,不然会在前端网页控制台显示“ccess to XMLHttpRequest at 'http://localhost:8080/api/login' from origin 'null' has been blocked” '''
CORS(app, supports_credentials=True)
# 存储验证码
session = {}

# 前端Login界面调取验证码图片,返回JSON字符串,非blob数据类型
@app.route('/getImgCode', methods=["GET", "POST"])
def imgCode():
  res = imageCode().getImgCode()
  return jsonify({"img":res})

# -------------------------------- #
# from io import BytesIO
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter
# 生成验证码
class imageCode():
    '''验证码处理'''
    def rndColor(self):
        '''随机颜色'''
        return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
    def geneText(self): 
        '''生成4位验证码'''
        # ascii_letters是生成所有字母 digits是生成所有数字0-9
        imgCode = ''.join(random.sample(string.ascii_letters + string.digits, 4))
        return imgCode
    def drawLines(self, draw, num, width, height):
        '''划线'''
        for num in range(num):
          x1 = random.randint(0, width / 2)
          y1 = random.randint(0, height / 2)
          x2 = random.randint(0, width)
          y2 = random.randint(height / 2, height)
          draw.line(((x1, y1), (x2, y2)), fill='black', width=1)
    def getVerifyCode(self):
        '''生成验证码图形'''
        code = self.geneText()
        # 图片大小120×50
        width, height = 120, 50
        # 新图片对象
        im = Image.new('RGB', (width, height), 'white')
        # 字体
        font = ImageFont.truetype('app/static/arial.ttf', 40)
        # draw对象
        draw = ImageDraw.Draw(im)
        # 绘制字符串
        for item in range(4):
            draw.text((5 + random.randint(-3, 3) + 23 * item, 5 + random.randint(-3, 3)),
               text=code[item], fill=self.rndColor(), font=font)
        # 划线,参数1为画板,参数2为线条数量,参数3为宽度,参数4为高度
        self.drawLines(draw, 2, width, height)
        return im, code
    def getImgCode(self):
        image, code = self.getVerifyCode()
        session['imageCode'] = code
        file_path =r"./upload/loginPic.jpg"
        image.save(file_path)
        # 把验证码图片的base64字段作为response返回前端,类型是string
        with open(file_path, 'rb') as img_f:
            img_stream = img_f.read()
            img_stream = base64.b64encode(img_stream)
            base64_string = img_stream.decode('utf-8')
            base64_string = "data:image/png;base64," + base64_string
            return base64_string

if __name__ == '__main__':
    # 0.0.0.0 表示同一个局域网均可访问,也可以替换成本机地址:通过命令行命令:ipcofig 获取
    app.run(host='0.0.0.0', port='5000', debug=True)

上面geneText是生产随机字母和数字结合的验证码内容的方法,此步比较关键

然后是PIL(Pillow)库画图的方法了:

ImageDraw.Draw.text()是在给定位置绘制字符串,生成图片返回Web端使用。ImageDraw.Draw.text(xy, text, fill=None, font=None, anchor=None, spacing=0, align=”left”)

ImageDraw.Draw.line()是在给定xy的数组,fill的填充颜色,线的宽度情况下划线ImageDraw.Draw.line(xy, fill=None, width=0)