flask08-蓝图不分离

import hashlib
import uuid
from flask import Blueprint, render_template, request, redirect, session, url_for, jsonify
from App.models import *

blue = Blueprint('blue',__name__)

def init_blue(app):
    app.register_blueprint(blueprint=blue)

# 首页
@blue.route('/')
def index():
    token = session.get('token')
    if token:
        user = User.query.filter(User.token==token).first()
    else:
        user = None
    return render_template('index.html',user=user)

# 注册
@blue.route('/register/',methods=['POST'])
def register():

    name = request.form.get('name')
    password =request.form.get('password')
    tel = request.form.get('tel')
    email = request.form.get('email')

    user = User()
    user.name = name
    user.password = encrypt(password)
    user.tel = tel
    user.email = email
    user.token = str(uuid.uuid5(uuid.uuid4(),'register'))

    db.session.add(user)
    db.session.commit()

    session['token'] = user.token

    return redirect(url_for('blue.index'))

# 加密
def encrypt(password):
    md5= hashlib.md5()
    md5.update(password.encode('utf-8'))
    return md5.hexdigest()

# 退出
@blue.route('/quit/')
def quit():
    session.pop('token')
    return redirect(url_for('blue.index'))

# 登录
@blue.route('/login/',methods=['POST'])
def login():
    name = request.form.get('name')
    password = request.form.get('password')

    # user = User.query.filter(User.name==name).filter(User.password==encrypt(password)).first()
    user = User.query.filter(User.name == name).first()
    res={}
    if user:# 用户名存在
        # 判断密码是否正确
        if user.password == encrypt(password):
            session['token'] = user.token
            db.session.add(user)
            db.session.commit()
            res['msg'] = '登录成功'
            res['status'] = 1
            return jsonify(res)
        else:
            res['msg'] = '密码错误'
            res['status'] = -1
            return jsonify(res)

    else:# 用户名不存在
        res['msg'] = '用户名错误'
        res['status'] = -1
        return jsonify(res)


# 用户名验证
@blue.route('/checkname/')
def checkname():
    name = request.args.get('name')
    user = User.query.filter(User.name==name).first()
    if  user:# 用户名一存在
        return jsonify({'msg': '用户存在', 'status': 1})
    else:# 用户名可以注册
        return jsonify({'msg':'用户不存在','status':-1})

你可能感兴趣的:(flask08-蓝图不分离)