您现在的位置是:首页 >学无止境 >Flask 知识点整理网站首页学无止境

Flask 知识点整理

Krien666 2024-05-30 13:35:54
简介Flask 知识点整理

1.URL与视图的映射

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

from flask import Flask

app = Flask(__name__)


@app.route('/blog/<int:blog_id>')
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

在这里插入图片描述


2.模板渲染

给html文件传参

from flask import Flask,render_template

@app.route('/blog/<int:blog_id>')
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 = "xx@qq.com")
    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 = "xx@qq.com")
    person = {
        "username":"张三",
        "email":"zhangsan@163.com"
    }
    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 = "xx@qq.com")
    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 = "xx@qq.com")
    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 %}}


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


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


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 "数据删除成功"
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。