实战脚手架准备分三部曲
Flask实战脚手架 (后端+restful api)
Yii2实战脚手架 (后端+restful api)
Vue2实战脚手架(前端)
Flask实战脚手架 (后端+restful api)
学习Flask从实战开始,制作一个web常用的脚手架,已备以后快速开发。
项目git地址第二次提交
暂定功能模块:
- 用户模块
- 文章模块
用到的python插件:
Flask-Login #用户登陆
Flask-Migrate #数据库管理工具
Flask-DebugToolbar #dubug工具栏
Flask-SQLAlchemy #ORM
Flask-WTF #表单
用户模块
安装所需的插件
pip install flask-login flask-sqlalchemy flask-migrate flask-wtf
1. 修改 app/__init__.py
如下
from flask import Flask
from app.config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = "backend.login" #配置用户默认登陆端点
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
db.init_app(app)
migrate.init_app(app, db)
login.init_app(app)
from app.backend import bp as backendbp #导入backend蓝图
app.register_blueprint(backendbp, url_prefix='/backend') #注册蓝图
return app
主要是注册插件与蓝图
3. 初始化注册后台蓝图app/backend/__init__.py
from flask import Blueprint
bp = Blueprint('backend', __name__)
from . import views
4. 添加用户登陆表单app/backend/forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
4. 添加后台路由app/backend/views.py
from . import bp
from flask import render_template, flash, redirect, url_for, request
from app.models import User
from flask_login import login_user, logout_user, login_required
from app.backend.froms import LoginForm
@bp.route('/')
@bp.route('/index')
@login_required
def index():
return render_template('backend/index.html')
@bp.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('账号或密码错误,请重新输入!')
return redirect(url_for('backend.login'))
login_user(user)
next_page = request.args.get('next')
if next_page:
return redirect(next_page)
return redirect(url_for('backend.index'))
return render_template('backend/login.html', form=form)
@bp.route('/logout')
def logout():
logout_user()
return redirect(url_for('backend.index'))
1. 创建模型app/models.py
from app import db, login
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin, login_manager
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True)
password_hash = db.Column(db.String(128))
last_login_at = db.Column(db.DateTime, default=datetime.utcnow)
profile = db.relationship('Profile', backref='user', lazy='dynamic')
def __repr__(self):
return '<User {}>'.format(self.username)
@property
def password(self):
return self.password_hash
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
# 配置用户登陆时加载的方法
@login.user_loader
def load_user(user_id):
return User.query.get(user_id)
class Profile(db.Model):
__table_args__ = (
db.PrimaryKeyConstraint('user_id'),
)
user_id = db.Column(db.ForeignKey('user.id'))
nickname = db.Column(db.String(125))
tel = db.Column(db.String(13))
def __repr__(self):
return '<Profile {}, {}>'.format(self.user_id, self.nickname)
好了,到这里,现在可以用flask-migrate数据迁移工具初始化数据库,并生成了
flask db init # 第一次需要初始化,以后就不需要此命令了
flask db migrage
flask db upgrade
现在应该在项目的根目录生成app.db的SQLite数据库了
我们来验证下程序是否有问题。我们在run.py里面压入User、Profile两表,去试试命令行执行
from app import create_app, cli, db
from app.models import User, Profile
app = create_app()
cli.register(app)
@app.shell_context_processor
def make_shell_context():
return {
'app': app,
'User': User,
'Profile': Profile,
'DB': db
}
这里压入了db与两表
flask shell # 进入shell交互模式
>>> DB
<SQLAlchemy engine=sqlite:////Users/jydd/python/myapp/app.db>
>>> u1 = User(username='user1')
>>> u1.password = '123456'
>>> p1 = Profile(nickname='nickname1', tel='1808888888')
>>> p1.user = u1
>>> p1.user
<User user1>
>>> u2 = User(username='user2')
>>> u2.password = '123456'
>>> u2.check_password('123456')
True
>>> p2 = Profile(nickname='nickname2', tel='19099999999')
>>> p2.user = u2
>>> DB.session.add(u1)
>>> DB.session.commit()
>>> u1.id
1
>>> u1.profile.first().nickname
'nickname1'
>>> DB.session.add(u2)
>>> DB.session.commit()
>>> u2.id
2
5. 模板部分 就不讲了,简单的标签,直接可以看git项目地址查看源码
现在通过访问路由 http://127.0.0.1:5000/backend/
会跳转到 http://127.0.0.1:5000/backend/login?next=%2Fbackend%2F
登陆成功后会跳转到 http://127.0.0.1:5000/backend/
网友评论