Flask知识点整理

文章目录

  • 1.URL与视图的映射
      • 带参数的url:将参数固定到了path中
      • 查询字符串的方式传参
  • 2.模板渲染
      • 给html文件传参
  • 3.模板访问对象属性
      • User 是个类
      • User是个字典
  • 4.过滤器的使用
      • 通过一个 | 管道符进行过滤
      • 自定义过滤器
  • 5.控制语句
      • if
      • for
  • 6.Flask连接MySQL数据库
  • 7.ORM模型与表的映射
  • 8.ORM模型的CRUD操作
      • create
      • query
      • update
      • delete
  • 9.flask-migrate迁移ORM模型
    • ORM模型映射成表的三步
      • 1.flask db init 这步只需要执行一次
      • 2.flask db migrate 识别ORM模型的改变,生成迁移脚本
      • 3.flask db upgrade 运行迁移脚本,同步到数据库中

1.URL与视图的映射

带参数的url:将参数固定到了path中

from flask import Flask

app = Flask(__name__)


@app.route('/blog/')
def blog_detail(blog_id):
    return "访问的是:%s"% blog_id

查询字符串的方式传参

from flask import Flask , request

@app.route('/book/list')
def book_list():
    page = request.args.get("page",default = 1,type = int)
    return f"您获取的是第{page}的图书列表!"

http://127.0.0.1:5000/book/list?page=5

Flask知识点整理_第1张图片


2.模板渲染

给html文件传参

from flask import Flask,render_template

@app.route('/blog/')
def blog_detail(blog_id):
    return render_template("blog_detail.html",blog_id,username = "krien")
<body>	
<p> 您的用户名是 {{ username }}p>
<h1>您访问的博客详情是:{{ blog_id }}h1>
<body>


3.模板访问对象属性

User 是个类

class User:
    def __init__(self,username,email):
        self.username = username
        self.email = email

@app.route('/')
def hello_world():  # put application's code here
    user = User(username = "krien", email = "[email protected]")
    return render_template('index.html',user = user)
<body>	

{{ user.username }} / {{ user.email }}

<body>

User是个字典

from flask import Flask,render_template ,request

app = Flask(__name__)

@app.route('/')
def hello_world():  # put application's code here
    user = User(username = "krien", email = "[email protected]")
    person = {
        "username":"张三",
        "email":"[email protected]"
    }
    return render_template('index.html',user = user,person = person)
<body>	

<div> {{ user.username }} / {{ user.email }} div>
<div> {{ person.username}} / {{ person.email }} div>

<body>


4.过滤器的使用

通过一个 | 管道符进行过滤

from flask import Flask,render_template ,request

from flask import Flask,render_template ,request

@app.route('/filter')
def filter_demo():  # put application's code here
    user = User(username = "krien", email = "[email protected]")
    return render_template('filter.html',user = user)
<body>	
{{ user.username }}-{{ user.username|length }}
<body>

自定义过滤器

过滤器本质上是一个 Python 函数,他会把过滤的值当作第一个参数传给这个函数,函数经过一些逻辑处理后,在返回新的值。在过滤器函数写好之后,可以通过@app.template_filter装饰器或者是 app.add_template_filter 函数来把函数注册成Jinjia2 能用的过滤器

from flask import Flask,render_template ,request
from datetime import datetime

app = Flask(__name__)

def datetime_format(value,format = "%Y年%m月%d日 %H:%M"):
	return value,strftime(format)
	
app.add_template_filter(datetime_format,"dformat")


@app.route('/filter')
def filter_demo():  # put application's code here
    user = User(username = "krien", email = "[email protected]")
    mytime = date_time.now()
    return render_template('filter.html',user = user,mytime = mytime)

<body>	
{{ user.username }}-{{ user.username|length }}
<div> {{mytime|dformat}} div>
<body>


5.控制语句

if

@app.route("/control")
def control_statement():
	age = 17
	return render_template("control.html",age=age)
<body>	
{{% if age>18 %}}
	<div>您已经满18,可以进入网吧div>
{{% elif age==18 %}}
	<div>您刚满18,需要父母陪同div>
{{% else %}}
	<div>您未满18,不能进去div>
{{% endif %}}
<body>

for

{{% for book in books %}}
	<div>图书名称:{{ book.name }},图书作者:{{ book.auther }}div>
{{% endfor %}}


6.Flask连接MySQL数据库

from sqlalchemy import text

app = Flask(__name__)

HOSTNAME = 'localhost'

PORT = 3306

USERNAME = "root"

PASSWORD = "123456"

DATABASE = "database_learn"

app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}/{DATABASE}"

db = SQLAlchemy(app)

with app.app_context():
    with db.engine.connect() as conn:
        rs = conn.execute(text("select 1"))
        print(rs.fetchone())


7.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)

with app.app_context():
    db.create_all()


8.ORM模型的CRUD操作

create

	@app.route('/user/add')
def add_user():
    user = User(username="krien",password = '123456')
    user1 = User(username='ddd',password = '121212')
    db.session.add(user)
    db.session.commit()
    return "用户创建成功"

query

	@app.route('/user/query')
def query_user():
    # 1.get
    user = User.query.get(1)
    print(f"{user.id}:{user.username}-{user.password}")
    # 2.filter_by 查找
    return "数据查找成功"

update

@app.route('/user/update')
def update_user():
    user = User.query.filter_by(username = "krien").first()
    user.password = '222222'
    db.session.commit()
    return "数据更新成功"

delete

@app.route('/user/delete')
def delete_user():
    user = User.query.get(2)
    db.session.delete(user)
    db.session.commit()
    return "数据删除成功"


9.flask-migrate迁移ORM模型

ORM模型映射成表的三步

1.flask db init 这步只需要执行一次

2.flask db migrate 识别ORM模型的改变,生成迁移脚本

3.flask db upgrade 运行迁移脚本,同步到数据库中

你可能感兴趣的:(Python,flask,python,后端)