美文网首页
搭建 flask 框架

搭建 flask 框架

作者: michaeljacc | 来源:发表于2016-09-07 11:22 被阅读48次

    model M

    
    from flask import Flask
    from flask_sqlalchemy import SQLAlchemy
    
    import time
    
    # 以下都是套路
    app = Flask(__name__)
    app.secret_key = 'secret key'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    # 指定数据库的路径
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todos.db'
    
    db = SQLAlchemy(app)
    
    
    # 定义一个 Model,继承自 db.Model
    class Todo(db.Model):
        __tablename__ = 'todos'
        # 下面是字段定义
        id = db.Column(db.Integer, primary_key=True)
        task = db.Column(db.String())
        created_time = db.Column(db.Integer, default=0)
    
        def __repr__(self):
            return u'<ToDo {} {}>'.format(self.id, self.task)
    
        def save(self):
            db.session.add(self)
            db.session.commit()
    
        def delete(self):
            db.session.delete(self)
            db.session.commit()
    
        def __init__(self, form):
            self.task = form.get('task', '')
            self.created_time = int(time.time())
    
        def valid(self):
            return len(self.task) > 0
    
    
    class User(db.Model):
        __tablename__ = 'users'
        # 下面是字段定义
        id = db.Column(db.Integer, primary_key=True)
        username = db.Column(db.String())
        password = db.Column(db.String())
        created_time = db.Column(db.Integer, default=0)
    
        def __repr__(self):
            return u'<User {} {}>'.format(self.id, self.username)
    
        def save(self):
            db.session.add(self)
            db.session.commit()
    
        def delete(self):
            db.session.delete(self)
            db.session.commit()
    
        def __init__(self, form):
            self.username = form.get('username', '')
            self.password = form.get('password', '')
            self.created_time = int(time.time())
    
        def valid(self):
            return len(self.username) > 2 and len(self.password) > 2
    
        def validate_login(self, u):
            return u.username == self.username and u.password == self.password
    
        def change_password(self, password):
            if len(password) > 2:
                self.password = password
                self.save()
                return True
            else:
                return False
    
    
    if __name__ == '__main__':
        # 先 drop_all 删除所有数据库中的表
        # 再 create_all 创建所有的表
        db.drop_all()
        db.create_all()
        print('rebuild database')
    
    

    C CONTROLER

    from flask import render_template
    from flask import request
    from flask import redirect
    from flask import url_for
    from flask import Blueprint
    from flask import abort
    from flask import session
    from models import User
    
    
    # 创建一个 蓝图对象 并且路由定义在蓝图对象中
    # 然后在 flask 主代码中「注册蓝图」来使用
    # 第一个参数是蓝图的名字,第二个参数是套路
    main = Blueprint('user', __name__)
    
    
    def current_user():
        uid = session.get('user_id')
        if uid is not None:
            u = User.query.get(uid)
            print('query 速度嫩三', User.query)
            # User.quert就是 user 所有参数,hahah,懂了
            return u
    
    
    @main.route('/')
    def login_view():
        u = current_user()
        if u is not None:
            return redirect('/todo')
        return render_template('user_login.html')
    
    
    @main.route('/user/register', methods=['POST'])
    def register():
        form = request.form
        u = User(form)
        if u.valid():
            u.save()
        else:
            abort(400)
        # 蓝图中的 url_for 需要加上蓝图的名字,这里是 user
        return redirect(url_for('.login_view'))
    
    
    @main.route('/user/login', methods=['POST'])
    def login():
        form = request.form
        u = User(form)
        # 检查 u 是否存在于数据库中并且 密码用户 都验证合格
        user = User.query.filter_by(username=u.username).first()
        if user is not None and user.validate_login(u):
            print('登录成功')
            session['user_id'] = user.id
        else:
            print('登录失败')
        # 蓝图中的 url_for 需要加上蓝图的名字,这里是 user
        return redirect(url_for('.login_view'))
    
    
    @main.route('/user/update', methods=['POST'])
    def update():
        u = current_user()
        password = request.form.get('password', '123')
        if u.change_password(password):
            print('修改成功')
        else:
            print('用户密码修改失败')
        return redirect('/user/profile')
    
    
    @main.route('/user/profile', methods=['GET'])
    def profile():
        u = current_user()
        if u is not None:
            print('profile', u.id, u.username, u.password)
            return render_template('profile.html', user=u)
        else:
            abort(401)
    
    
    
    

    V 可视化

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <title>注册与登录</title>
    </head>
    <body>
       <form action="/user/register" method="post">
           <input name="username">
           <br>
           <input name="password">
           <button>注册</button>
       </form>
       <form action="/user/login" method="post">
           <input name="username">
           <br>
           <input name="password">
           <button>登录</button>
       </form>
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:搭建 flask 框架

          本文链接:https://www.haomeiwen.com/subject/rasjettx.html