其他分享
首页 > 其他分享> > 首页渲染及图形验证码

首页渲染及图形验证码

作者:互联网

一、首页渲染

在templates文件夹下新建一个news文件夹,用来存放前端页面,然后将index.html拖动到news文件夹中。

 

 

 将static文件和templates文件拖动到info文件夹中。

 

 

 在views.py中写入渲染画面相关代码

 

 

 二、设置左上角图标

 在views.py写入下列代码

from flask import render_template,current_app

@blue_index.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")

如果运行没显示出来图标,就改一下端口号

 

三、图形验证码

在modiles文件夹中新建一个passport文件夹

在passport文件夹中新建views.py

 

 

 

 

 

 passport文件夹里的init.py中写入蓝图

from flask import Blueprint

blue_passport = Blueprint("passport",__name__)

from . import views

 passport文件夹里的views.py写入视图函数

from . import blue_passport

@blue_passport.route("/image_code")
def image_code():
    pass

 

在info中的init里注册蓝图

from info.modules.passport import blue_passport

app.register_blueprint(blue_passport)

 

补全前端代码

// TODO 生成一个图片验证码的编号,并设置页面中图片验证码img标签的src属性
function generateImageCode() {
    // 生成uuid
    imageCodeId = generateUUID();
    // url:必须要能访问到image_code视图
    var url = '/passport/image_code?imageCodeId='+imageCodeId;
    // 将url赋值给img标签的src属性,只要src属性给赋值一个url,会立即向该url发送请求
    $('.get_pic_code').attr('src', url);
}

测试js代码是否配置成功

 

 

 后端逻辑思路:

 

 

 相关代码

from . import blue_passport
from flask import request,abort,make_response
from info.utils.captcha.captcha import captcha
from info import sr
from info import constants

@blue_passport.route("/image_code")
def image_code():
    #1、接收参数
    imageCodeId = request.args.get("imageCodeId")
    #2、校验参数
    #   2.1 校验uuid是否存在
    if not image_code:
        return abort(403)
    #3、生成图片验证码
    name,imageCodetext,imageCodeimage = captcha.generate_captcha()
    #4、将文字的验证码信息存到redis中
    try:
        sr.set("imageCode:"+ imageCodeId,imageCodetext,ex=constants.IMAGE_CODE_REDIS_EXPIRES)
    except:
        return abort(500)
    #5、返回图片给前端
    response = make_response(imageCodeimage)
    response.headers["Content-Type"] = "image/jpg"
    return response
View Code

 

标签:blue,code,渲染,image,验证码,文件夹,首页,passport,import
来源: https://www.cnblogs.com/liuzijie95/p/16394795.html