Flask 登录注册

主文件 myapp.py

from flask import Flask
from flask import request ,render_template, make_response, g
from flask_wtf import CSRFProtect as WTF
from forms import LoginForm
from models import users, find_user_by_email, find_user_by_id
from tools import login_required

app = Flask(__name__)
WTF(app)

app.config.from_pyfile('config.py')  #WTF_CSRF_ENABLED = False

@app.before_request  #钩子函数,所有视图都先经过这
def login_before_request():
    uid = request.cookies.get('uid',None)  #获取cookies中的值,检查登录状态,没有返回None
    user = find_user_by_id(uid)
    g.user = user #设置全局变量,一个请求一个g。让其他函数可以访问到

@app.route('/')
@login_required #装饰器,限制页面只在登录下访问,没有则跳转登录界面
def index():
    user = g.user  #获取全局中的g
    return render_template('index.html',user=user)   #传入模板中

@app.route('/login/',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        form = LoginForm() #产生一个具体空的表单实例
        return render_template('login.html',form=form) #传入模板渲染表单标签
    else: #post请求
        form = LoginForm(request.form)  #通过表单类获取request中的数据
        if form.validate():  #主动验证表单合法性
            user = find_user_by_email(form.email.data) #获取数据
            if user:
                if user.check_pwd(form.password.data):
                    resp = make_response('登录成功')
                    if form.remember: #如果选上remember
                        age = 2592000
                    else:
                        age = None
                    resp.set_cookie('uid',str(user.id), max_age=age) #设置cookies
                    return resp
                else:
                    return '密码不正确'
            else:
                return '邮箱不存在'

        else:
            return str(form.errors)


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

创建WTF 表单类

from flask_wtf import FlaskForm

from wtforms import StringField

from wtforms.validators import InputRequired,Email,Length

class LoginForm(FlaskForm):
    email = StringField(label='邮箱',
                        validators=[InputRequired('没有输入邮箱'),
                        Email('非法的邮箱格式')])
    password = StringField(label='密码',
                           validators=[InputRequired('没有输入密码'),
                                       Length(6,14,'密码长度不符合要求')])

模拟sqlalchemy

class User:
    def __init__(self, id, email, password, name):
        self.id = id
        self.email = email
        self.password = password
        self.name = name

    def check_pwd(self, password):
        return self.password == password

users = [
    User('1','[email protected]','123456','Tuple'),
    User('2','[email protected]','666666','taka'),
    User('3','[email protected]','88888888','Which'),
]

def find_user_by_email(email):
    for user in users:
        if user.email == email:
            return user
    else:
        return None

def find_user_by_id(uid):
    for user in users:
        if user.id == uid:
            return user
    else:
        return None

登录界面,通过表单实例渲染




    
    Title


    
{{ form.email.label }}:{{ form.email() }}
{{ form.password.label }}:{{ form.password(type='password') }}
/*可以自定义添加标签内容*/ {{ form.remember.label }}:{{ form.remember() }}

login_required 暂时不清楚原理

from functools import wraps
from flask import g
from flask import redirect, url_for

def login_required(func):
    @wraps(func)
    def waapper(*args,**kwargs):
        if g.user:
            return func(*args,**kwargs)
        return redirect(url_for('login'))
    return waapper

你可能感兴趣的:(Flask 登录注册)