Flask 快速入门笔记

Flask

记录一下最近用到的Flask

导入库

和其他的软件包一样导入,导入之后可以创建一个 Flask应用程序实例

1
2
3
from flask import Flask

app = Flask(__name__)

路由 Route

使用 @app.route() 修饰

app.route() 中需要提供一个字符串参数,是定义一个子页面

例如

1
2
3
4
5
6
@app.route("/hello")
def Hello():
"""
在函数中做一些处理,最后返回一个 HTML 页面
"""
return "Hello"

这样,当运行 app 实例时,访问即可看到 Hello 字样

路由传参

@app.route("/hello/<type: var>")

默认类型为 String,可以不写 type,如果参数类型为int, float等,则需要写上类型

1
2
3
@app.route("/hello/<int:var>")
def func(var):
return "Var: %s" % var

在例子中,访问 http://127.0.0.1:5000/hello/0 ,就可以看到 “Var: 0”。

HTML Escaping

为了防止注入攻击,在接受字符串作为参数时,应当使用escape将字符串转换为纯文本类型,防止输入JavaScript字符串进行攻击

使用方法如下

1
2
3
4
5
from markupsafe import escape

@app.route("/hello/<who>")
def func1(who):
return f'Hello {escape(who)}'

独一URL/重定向规则

如果一个URL以 / 结尾,则称为 Path(路径);如果不以其结尾,称为 File(文件)

如果路由中的URL是一个Path,当遇到同名的File的请求时,会自动重定向到该Path

而如果路由中是File,当访问同名的Path时,则会遇到 404错误

例如

1
2
3
4
5
6
7
@app.route("/path/")
def f_path():
return "Path"

@app.route("/file")
def f_file():
return "File"

访问 /path//file 时,都是正常访问,当访问到/path时,会自动重定向到 /path/;但是访问 /file/ 时,却不会自动重定向到 /file,而是返回404界面

构建 URL

直接写URL也可以,但是如果涉及到许多处修改,很容易漏改。因此使用 构建URL 来生成每个页面的URL,这样只需更改路由修饰器中的地址,就可以自动更改所有用到的 URL地址

用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from flask import url_for

@app.route('/')
def index():
return 'index'

@app.route('/login')
def login():
return 'login'

@app.route('/user/<username>')
def profile(username):
return f'{username}\'s profile'

with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))

运行输出如下:

1
2
3
4
/
/login
/login?next=/
/user/John%20Doe

HTTP 方法

默认情况下 Flask 只回应GET方法,通过给路由添加 method=['GET', 'POST'] 参数,可以让其对 POST 方法也有反应

1
2
3
4
5
6
7
8
from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()

也可以通过不同的修饰器来区分不同的方法:

1
2
3
4
5
6
7
@app.get('/login')
def login_get():
return show_the_login_form()

@app.post('/login')
def login_post():
return do_the_login()

静态文件

创建一个文件夹 static 专门用来存放静态文件

同样的可以使用 url_for() 来构建URL

1
url_for('static', filename='style.css'

渲染模板

在程序的同级目录下,新建 templates文件夹,用于放置模板html文件

之后即可使用 render_template() 进行渲染, 提供的参数分别为模板文件名,以及渲染时需要的变量的值

1
2
3
4
5
6
from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
1
2
3
4
5
6
7
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}

同理,关于静态CSS和静态JS文件,也可以使用 url_for() 写入模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Submarine Robot Result</title>
<!-- 引入 SocketIO 客户端脚本 -->
<script src="{{ url_for('static', filename='script.js') }}"></script>
<!-- import stylesheet-->
<link
rel="stylesheet"
href="{{ url_for('static', filename='style.css') }}"
/>
</head>
<body>
...
</body>
</html>

重定向和错误

1
2
3
4
5
6
7
8
9
10
from flask import abort, redirect, url_for

@app.route('/')
def index():
return redirect(url_for('login'))

@app.route('/login')
def login():
abort(401)
this_is_never_executed()

abort(code) 用于放弃一个请求并给出一个错误代码;redirect(url)用于重定向到某个页面

既然出现异常了,一定也要做异常处理,比如生成一个错误页面,或者重定向到正常的页面。那么可以使用 errorhandler() 修饰符

1
2
3
4
5
from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404

注意,异常处理时记得返回一个错误代码,这样才能知道出错了


暂时只用到了这么多,有更多内容以后再更新