知了传课Flask学习(持续更新)

知了传课Flask学习(持续更新)

码农世界 2024-05-21 前端 61 次浏览 0个评论

一、基础内容

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/')
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




    
    
    
    
    知了问答平台-注册


    
    
        
            
            
                
我们不会把邮箱用于其他用户

 ②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

6.后端注册功能完成

转载请注明来自码农世界,本文标题:《知了传课Flask学习(持续更新)》

百度分享代码,如果开启HTTPS请参考李洋个人博客
每一天,每一秒,你所做的决定都会改变你的人生!

发表评论

快捷回复:

评论列表 (暂无评论,61人围观)参与讨论

还没有评论,来说两句吧...

Top