python Flask-login

之前看别人的博客,感觉一阵头大,各种报错
然后看了看别人用flask-login的源码之后豁然开朗 …
测试了个简单的,记录下,有源码 看着就是容易理解 …

#coding:utf-8
from flask import Flask,request,redirect,flash,url_for
from flask_login import LoginManager,login_user,logout_user,login_required,UserMixin
from flask_sqlalchemy import SQLAlchemy


# create login Object
db = SQLAlchemy()
login_manager = LoginManager()

# create Flask Object
app = Flask(__name__)
app.secret_key = 'This is my key'
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:[email protected]/todo"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

db.init_app(app)
login_manager.init_app(app)
login_manager.login_view = "login"

class User(db.Model,UserMixin):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(24), nullable=False)
    password = db.Column(db.String(24), nullable=False)

    def __init__(self, username, password):
        self.username = username
        self.password = password

@app.route('/admin')
@login_required
def admin_index():
    return "This is admin"

@app.route("/login",methods=["POST","GET"])
def login():
    if request.method == 'POST':
        user = User.query.filter_by(username=request.form['username'], password=request.form['password']).first()
        if user:
            login_user(user)
            flash('you have logged in!')
            return redirect(url_for('admin_index'))
    else:
        return """
        
username:
password:
"""
@login_manager.user_loader def load_user(user_id): return User.query.filter_by(id=int(user_id)).first() if __name__ == '__main__': app.run(debug=True,host="0.0.0.0")

你可能感兴趣的:(python)