790 字
4 分钟
Flask 框架学习
2025-02-07

前言#

一般Web端的Python招聘会提出要求了解 Tornado, Django 或 Flask 三种框架中的一个,其中 Tornado 用的比较少且难度高,Django 比较全面完善且难度一般,Flask 功能简约难度是最低的。


环境部署#

Flask 的环境依赖于 Python,可以通过 pip 直接按照:

Terminal window
pip install flask

编辑器更加推荐 PyCharm


request 和 Response#

参考 https://blog.csdn.net/j15087159186/article/details/144105300


基础案例#

Hello World!#

python 运行代码后,直接访问 localhost 即可:

from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()

Debug / Host / Port#

  • debug=True 支持在不关闭程序的情况下,重新加载应用
...
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)

定义不同路径#

# 根目录 http://localhost:8000
@app.route('/')
def hello_world():
return 'Hello World!'
# 访问路径:http://localhost:8000/profile
@app.route('/profile')
def profile():
return '我是个人中心!'
# 访问路径:http://localhost:8000/blog/10086
# @app.route('/blog/<blog_id>')
@app.route('/blog/<int:blog_id>') # 强制类型
# string, int, float, path, uuid, any
def blog_detail(blog_id):
return f'您访问的博客是:{blog_id}!'
# 通过 request 请求实现
# /book/list?page=2
@app.route('/blog/list')
def blog_list():
page = request.args.get("page", default=1, type=int)
return f'您获取的是第{page}页'

Jinjia2#

基础#

Jinjia2 的语法:

  • 控制结构 {% %}
  • 变量取值 {{ }}
  • 注释 {# #}

模板渲染#

参考视频

D:.
├─app.py
└─templates
├─blog_detail.html
└─index.html
  • template 中存放的一般都是静态的 html 文件,用于定义网页样式
  • blog_detail.html 用于显示博客详情
  • index.html 用于显示博客主页

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
首页内容
</body>
</html>

blog_detail.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>博客详情</title>
</head>
<body>
<h1>您访问的博客详情是:{{ blog_id }}</h1>
</body>
</html>

app.py

from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
@app.route('/blog/<int:blog_id>')
def blog_detail(blog_id):
return render_template('blog_detail.html', blog_id=blog_id)
if __name__ == '__main__':
app.run(debug=True)

模板访问对象属性#

字典类型的对象可以通过字典或成员变量的方式进行访问。

index.html

<div>username1 = {{ user.username }}</div>
<div>email1 = {{ user.email }}</div>
<div>username2 = {{ person['username'] }}</div>
<div>email2 = {{ person.email }}</div>

app.py

class User:
def __init__(self, username, email):
self.username = username
self.email = email
@app.route('/')
def hello_world():
user = User('1', 'xx@qq.com')
person = {
'username' : '2',
'email': 'yy@qq.com'
}
return render_template('index.html', user=user, person=person)

过滤器使用#

Jinjia2 中过滤器是一种转变变量输出内容的技术。

常用的格式是:{{ 变量 filter(过滤器参数) }}

filter.html

<div>{{ user.username }} / {{ user.username length }}</div>
<div>{{ mytime dformat }}</div>

app.py

from flask import Flask, render_template
from datetime import datetime
# 自定义过滤器
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():
user = User(username='3', email='zzz@qq.com')
mytime = datetime.now()
return render_template('filter.html', user=user, mytime=mytime)

控制语句#

control.html

{% if age>18 %}
<div>您已满18岁</div>
{% elif age==18 %}
<div>您刚满18岁</div>
{% else %}
<div>您未满18岁</div>
{% endif %}
{% for book in books %}
<div>{{book.name}}:{{book.author}}</div>
{% endfor %}

app.py

@app.route('/control')
def control_statement():
age = 17
books = [{
'name': '11',
'author': 'aa',
},{
'name': '22',
'author': 'bb',
}]
return render_template('control.html', age=age, books=books)

模板继承#

base.html(父模板):

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<h1>父模板</h1>
{% block body %}
{% endblock %}
</body>
</html>

child.html(子模板):

{% extends "base.html" %}
{% block titile %}
我是子模版标题
{% endblock %}
{% block body %}
我是子模版body
{% endblock %}

最终子模板的 block-title 和 block-body 会替换掉父模板的 block。

加载静态文件#

D:.
├─app.py
├─static
│ ├─css
│ │ └─style.css
│ ├─images
│ │ └─img.png
│ └─js
│ └─my.js
└─templates
└─index.html

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>title</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/my.js') }}"></script>
</head>
<body>
<img src="{{ url_for('static', filename='images/img.png') }}" alt="">
</body>
</html>

数据库#

Flask 框架学习
https://fuwari.vercel.app/posts/编程/python/flask-框架学习/
作者
Asuwee
发布于
2025-02-07
许可协议
CC BY-NC-SA 4.0