一、基础内容
1.Flask快速应用
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello world'
if __name__ == '__main__':
app.run()
2.debug、host、port配置
from flask import Flask,request
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello'
if __name__ == '__main__':
# debug模型:实时修改更新代码
# 修改host:修改主机号
# 修改port:修改端口号
app.run(debug=True,host='localhost',port=8080)
3.URL与视图的映射
from flask import Flask,request
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello'
@app.route('/profile')
def profile():
return '我是个人中心'
@app.route('/blog/<int:id>')
def blog_detail(id):
return f'您访问的博客是{id}'
# /book/list:返回第一页数据
# /book/list?page=2:返回第二页数据
@app.route('/book/list')
def book_list():
page = request.args.get('page',default=1,type=int)
return f'您获取的是第{page}页图书列表'
if __name__ == '__main__':
# debug模型:实时修改更新代码
# 修改host:修改主机号
# 修改port:修改端口号
app.run(debug=True,host='localhost',port=8080)
4.Flask连接MySQL数据库
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from flask_migrate import Migrate
app = Flask(__name__)
HOSTNAME = '127.0.0.1'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DATABASE = 'test'
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
# app.config设置好连接数据库的信息
# 使用SQLAlchemy(app)创建一个db对象
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# 测试链接
with app.app_context():
with db.engine.connect() as conn:
query = text("select 1") # 使用text函数创建可执行的对象
rs = conn.execute(query)
print(rs.fetchone())
@app.route('/')
def hello_world():
return "hello world"
if __name__ == '__main__':
app.run()
5.ORM与表的映射
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
password = db.Column(db.String(100),nullable=False)
6.ORM的增删改查
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from flask_migrate import Migrate
app = Flask(__name__)
HOSTNAME = '127.0.0.1'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DATABASE = 'test'
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
# app.config设置好连接数据库的信息
# 使用SQLAlchemy(app)创建一个db对象
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# 测试链接
with app.app_context():
with db.engine.connect() as conn:
query = text("select 1") # 使用text函数创建可执行的对象
rs = conn.execute(query)
print(rs.fetchone())
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
password = db.Column(db.String(100),nullable=False)
@app.route('/user/add')
def add_user():
user = User(username='yld',password='123456')
db.session.add(user)
db.session.commit()
return '用户创建成功'
@app.route('/user/query')
def query_user():
# 1.get查找 根据主键查找
user = User.query.get(1)
print(f'{user.username}')
return '数据查找成功'
# 2.filter_by查找
users = User.query.filter_by(username = 'yld')
for i in users:
print(i.id)
return '数据查找成功'
@app.route('/user/update')
def update_user():
users = User.query.filter_by(username = 'yld').first()
users.password = '222222'
db.session.commit()
return '数据修改成功'
@app.route('/user/delete')
def delete_user():
users = User.query.filter_by(username = 'yld').first()
db.session.delete(users)
db.session.commit()
return '数据删除成功'
class Article(db.Model):
__tablename__ = 'article'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(200),nullable=False)
content = db.Column(db.Text,nullable=False)
#添加作者外键
author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
#backref:自动给User模型添加一个articles属性,用来获取文章列表
author = db.relationship('User',backref='articles')
@app.route('/article/add')
def article_add():
article = Article(title='Flask学习', content='数据库')
user = User.query.filter_by(username = 'yld').first()
article.author_id = user.id
article.author = user
db.session.add(article)
db.session.commit()
return '文章添加成功'
@app.route('/')
def hello_world():
return "hello world"
if __name__ == '__main__':
app.run()
二、内容实战
1.博客平台项目搭建
①app.py
from flask import Flask
import config
from exts import db
from models import UserModel
from blueprints.qa import qa
from blueprints.auth import auth
from flask_migrate import Migrate
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
migrate = Migrate(app,db)
app.register_blueprint(auth)
app.register_blueprint(qa)
if __name__ == '__main__':
app.run(debug=True)
②config.py
HOSTNAME = '127.0.0.1'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DATABASE = 'test'
DB_URI = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8mb4"
SQLALCHEMY_DATABASE_URI = DB_URI
③exts.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
2.User模型搭建
model.py
from exts import db
from datetime import datetime
class UserModel(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
username = db.Column(db.String(100),nullable=False)
password = db.Column(db.String(100),nullable=False)
email = db.Column(db.String(100),nullable=False,unique=True)
join_time = db.Column(db.DateTime,default=datetime.now)
迁移命令:
flask db init
flask db migrate
flask db upgrade
3.注册页面渲染
①register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{url_for('static',filename='bootstrap/bootstrap.4.6.min.css')}}">
<link rel="stylesheet" href="{{url_for('static',filename='css/init.css')}}">
<title>知了问答平台-注册</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="#">知了问答</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">首页 <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">发布问答</a>
</li>
<li class="nav-item ml-2">
<form class="form-inline my-2 my-lg-0" method="GET" action="#">
<input class="form-control mr-sm-2" type="search" placeholder="关键字" aria-label="Search"
name="q">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
</form>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">登录</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">注册</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row mt-4">
<div class="col"></div>
<div class="col">
<form method="POST" action="#">
<div class="form-group">
<label for="exampleInputEmail1">邮箱</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
name="email">
<small id="emailHelp" class="form-text text-muted">我们不会把邮箱用于其他用户</small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">验证码</label>
<div class="input-group">
<input type="text" class="form-control" name="captcha">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="captcha-btn">获取验证码</button>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">用户名</label>
<input type="text" class="form-control" name="username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">密码</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="password">
</div>
<div class="form-group">
<label for="exampleInputPassword1">确认密码</label>
<input type="password" class="form-control" name="password_confirm">
</div>
<button type="submit" class="btn btn-primary btn-block">立即注册</button>
</form>
</div>
<div class="col"></div>
</div>
</div>
</body>
</html>
②auth.py
from flask import Blueprint, render_template
auth = Blueprint('auth', __name__, url_prefix='/auth')
@auth.route('/register')
def register():
return render_template('register.html')
4.Flask发送邮件功能
5.后端注册表单验证器实现
pip install flask-wtf