Flask是一个Python编写的Web 微框架,可以快速实现一个网站或Web服务。
Flask官方文档
基础示例
1 | from flask import Flask |
简单的理解,当我们访问route()指定的url时,会运行对应的函数,并在页面中返回对应函数的返回值。
在上述示例中,访问 http://127.0.0.1:6006/hello 会返回 “Hello World”。
扩展参数
app.run()
1 | app.run(host, port, debug, options) |
所有参数都是可选的
- host:要监听的主机名。 默认为127.0.0.1(localhost)。设置为“0.0.0.0”以使服务器在外部可用
- port :默认值为5000
- debug:默认为false。 如果设置为true,则提供调试信息,可以自动重载代码并显示调试信息
- options:要转发到底层的Werkzeug服务器。
Flask路由指定
现代Web框架使用路由技术来帮助用户记住应用程序URL。可以直接访问所需的页面,而无需从主页导航。
Flask中的route()装饰器用于将URL绑定到函数。例如:1
2
3
def hello_world():
return 'hello world'
在这里,URL’/ hello’规则绑定到hello_world()函数。 因此,如果用户访问http://localhost:5000/hello URL,hello_world()函数的输出将在浏览器中呈现。
application对象的add_url_rule()函数也可用于将URL与函数绑定,如上例所示,使用route()装饰器的目的也由以下表示:1
2
3def hello_world():
return 'hello world'
app.add_url_rule('/', 'hello', hello_world)
Flask 变量规则
通过向规则参数添加变量部分,可以动态构建URL。此变量部分标记为 converter:variable_name。它作为关键字参数转换为指定格式传递给与规则相关联的函数。
在以下示例中,route()装饰器的规则参数包含附加到URL’/hello’的1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author:chenshifeng
@file:flask_demo.py
@time:2021/03/01
"""
from flask import Flask
app = Flask(__name__)
def hello_name(name):
return 'Hello %s!' % name
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
def show_subpath(subpath):
# show the subpath after /path/
return 'Subpath %s' % subpath
if __name__ == '__main__':
app.run(debug=True)
支持的格式转换器类型
| 转换器 | 描述 |
| —— | ———————————– |
| string | (缺省值) 接受任何不包含斜杠的文本 |
| int | 接受正整数 |
| float | 接受正浮点数 |
| path | 类似 string ,但可以包含斜杠 |
| uuid | 接受 UUID 字符串 |
唯一的 URL / 重定向行为
以下两条规则的不同之处在于是否使用尾部的斜杠。:1
2
3
4
5
6
7
def projects():
return 'The project page'
def about():
return 'The about page'
projects 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件夹。访问一个没有斜杠结尾的 URL 时 Flask 会自动进行重定向,帮你在尾部加上一个斜杠。
about 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这个 URL 时添加了尾部斜杠就会得到一个 404 错误。这样可以保持 URL 唯一,并帮助 搜索引擎避免重复索引同一页面。
Flask URL构建
url_for()函数对于动态构建特定函数的URL非常有用。该函数接受函数的名称作为第一个参数,以及一个或多个关键字参数,每个参数对应于URL的变量部分。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask, redirect, url_for
app = Flask(__name__)
def hello_admin():
return 'Hello Admin'
def hello_guest(guest):
return 'Hello %s as Guest' % guest
def hello_user(name):
if name == 'admin':
return redirect(url_for('hello_admin'))
else:
return redirect(url_for('hello_guest', guest=name))
if __name__ == '__main__':
app.run(debug=True)
redirect函数用于重定向,实现机制很简单,就是向客户端(浏览器)发送一个重定向的HTTP报文,浏览器会去访问报文中指定的url。
Flask HTTP方法
默认情况下,Flask路由只响应GET请求。但是,可以通过为route()装饰器提供方法参数来更改此首选项。
| 方法 | 描述 |
| —— | —————————————————————— |
| GET | 以未加密的形式将数据发送到服务器,最常见的方法。 |
| HEAD | 和GET方法相同,但没有响应体。 |
| POST | 用于将HTML表单数据发送到服务器,POST方法接收的数据不由服务器缓存。 |
| PUT | 用上传的内容替换目标资源的所有当前表示。 |
| DELETE | 删除由URL给出的目标资源的所有当前表示。 |
为了演示在URL路由中使用POST方法,首先让我们创建一个HTML表单,并使用POST方法将表单数据发送到URL。
将以下脚本另存为login.html1
2
3
4
5
6
7
8
9
10
11<html>
<body>
<form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
运行如下的flask代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18from flask import Flask, redirect, url_for, request
app = Flask(__name__)
def success(name):
return 'welcome %s' % name
def login():
if request.method == 'POST':
user = request.form['nm']
return redirect(url_for('success',name = user))
else:
user = request.args.get('nm')
return redirect(url_for('success',name = user))
if __name__ == '__main__':
app.run(debug = True)
表单数据将POST到表单标签的action子句中的URL。
http://localhost/login映射到login()函数。由于服务器通过POST方法接收数据,因此通过以下步骤获得从表单数据获得的“nm”参数的值:
表单数据将POST到表单标签的action子句中的URL。
Flask 模板
在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本.
- 模板其实是一个包含响应文本的文件,其中用占位符(变量)表示动态部分,告诉模板引擎其具体的值需要从使用的数据中获取
- 使用真实值替换变量,再返回最终得到的字符串,这个过程称为’渲染’
- Flask 是使用 Jinja2 这个模板引擎来渲染模板
使用模板的好处
- 视图函数只负责业务逻辑和数据处理(业务逻辑方面)
- 而模板则取到视图函数的数据结果进行展示(视图展示方面)
- 代码结构清晰,耦合度低
使用 render_template() 方法可以渲染模板,你只要提供模板名称和需要 作为参数传递给模板的变量就行了。 Flask 会在 templates 文件夹内寻找模板。因此,如果你的应用是一个模块, 那么模板文件夹应该在模块旁边;如果是一个包,那么就应该在包里面:
情形 1 : 一个模块:1
2
3/application.py
/templates
/hello.html
情形 2 : 一个包:1
2
3
4/application
/__init__.py
/templates
/hello.html