flask 的6.生成验证码图片

创建satar.py(程序入口)
flask 的6.生成验证码图片_第1张图片

#创建satar.py(程序入口)

from apps import app
from modules.web.index import index_blue
from modules.web.user import user_blue

app.register_blueprint(index_blue)
app.register_blueprint(user_blue, url_prefix='/user')

if __name__ == '__main__':
    app.run(port=9991)

创建setting.py(配置文件)

DEBUG = True 
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:@127.0.0.1:3306/xins?charset=utf8'
SQLALCHEMY_ECHO = True
SECRET_KEY = 'abc'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True

创建models.py(所有表的结构)

from apps import *

from datetime import datetime


class BaseModel():
    create_tiem = db.Column(db.DateTime,default=datetime.now,comment='创建时间')
    Update_time=db.Column(db.DateTime,default=datetime.now,onupdate=datetime.now,comment='更新时间')

#用户表
class User(db.Model,BaseModel):
    id=db.Column(db.Integer,primary_key=True,comment='主键ID')
    name=db.Column(db.String(30),nullable=False,default='',comment='用户名')
    pwd=db.Column(db.String(30),nullable=False,default='',comment='密码')



创建manager.py(迁移)

from flask_script import Manager

from apps import app

from flask_migrate import Migrate,MigrateCommand

from models import *

manager=Manager(app=app)

migrate = Migrate(app=app,db=db)

manager.add_command('db',MigrateCommand)

if __name__ == '__main__':
    manager.run()

迁移的命令

  • python manager.py db init (初始化)
    flask 的6.生成验证码图片_第2张图片
  • python manager.py db migrate
    flask 的6.生成验证码图片_第3张图片
  • python manager.py db upgrade
    flask 的6.生成验证码图片_第4张图片

flask 的6.生成验证码图片_第5张图片
创建apps.py(实例化app)


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config.from_object('setting')

db=SQLAlchemy(app=app)

创建modules文件夹创建wed文件

  • wed下创建 index.py user.py
    user.py
# wangzhaohui at 2019/5/16 下午2:46
"""Todo"""
from flask import Blueprint, render_template, request, flash, redirect, url_for, session, make_response
from models import *
from utils.captcha.captcha import captcha

user_blue = Blueprint('user', __name__)


@user_blue.route('/reg', methods=['GET', 'POST'])
def reg():
    if request.method == 'POST':
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        repwd = request.form.get('repwd')
        if not all([name, pwd, repwd]):
            flash('参数不全!')
        elif len(pwd) < 6:
            flash('密码长度必须大于6位!')
        elif pwd != repwd:
            flash('两次密码不相同!')
        else:
            try:
                new_user = User(name=name, pwd=pwd)
                db.session.add(new_user)
                return redirect(url_for('user.login'))
            except Exception as e:
                flash('注册不成功!')
    return render_template('web/reg.html')


@user_blue.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        name = request.form.get('name')
        pwd = request.form.get('pwd')
        code = request.form.get('code')
        if not all([name, pwd]):
            flash('参数不全!')
        else:
            text = session.get('code').lower()
            if text != code:
                flash('验证码不正确!')
            else:
                one_user = User.query.filter(User.name == name).first()
                if not one_user:
                    flash('用户不存在!')
                else:
                    if one_user.pwd != pwd:
                        flash('密码不正确!')
                    else:
                        session['id'] = one_user.id
                        session['name'] = one_user.name
                        print(session.get('id'))
                        print(session.get('name'))
                        flash('登录成功!')
                        return redirect(url_for('index.index'))
    return render_template('web/login.html')
"""
1、将验证码插件放到utils下面
2、导入验证码包
3、调用验证码插件的方法生成验证码,用三个变量接收,重要的是text:具体验证码的值,image_url:二进制的图片
4、将验证码的值text保存到session中
5、通过make_response去修改响应类型Content-Type为:image/jpg,将响应返回。
"""
@user_blue.route('/generate_code')
def generate_code():
    name, text, image_url = captcha.generate_captcha()
    print('文本:', text)
    print('图片', image_url)
    session['code'] = text
    print('session:',session.get('code'))
    response = make_response(image_url)
    response.headers['Content-Type'] = 'image/jpg'
    return response


@user_blue.route('/logout')
def logout():
    session.pop('id', None)
    session.pop('name', None)
    flash('退出成功!')
    return redirect(url_for('user.login'))

创建utils插件文件夹
1、将验证码插件放到utils下面
2.把jquery.js引入在static文件夹中wed文件夹中的js文件夹中
flask 的6.生成验证码图片_第6张图片
创建static的文件夹下在创建web的文件夹下创建js的文件夹
** login.js**

$(function () {
    code()
});

function code() {
    num = Math.random()
    image_url = '/user/generate_code?num'+num;
    $('.code').attr('src', image_url);
}

你可能感兴趣的:(1,3,2,4)