最近在做毕设,基于 OpenCV 的智能监控系统,使用 C/S 架构,最后技术选型用了 Flask 框架

用了差不多半天时间学了下 Flask,不得不说,开发起来是真的舒服。之前用 node + art-template 开发的一个博客系统,且不说配置麻烦,开发起来也比较繁琐,使用起来两者的语法很多都很相似,上手很快

Flask 自带基于 Jinja 的模板引擎,session,蓝图(相当于 express、koa 中的 router),并且衍生除了很多插件

等忙完这段时间准备用 Python 重构下之前写的项目

最基本的 Flask 应用

1
2
3
4
5
6
7
from flask import *

app = Flask(__name__)

@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"

路由

1
2
3
4
5
6
7
@app.route('/')
def index():
return 'Index Page'

@app.route('/hello')
def hello():
return 'Hello, World'

重定向

1
2
3
4
@app.route('/hello')
def hello():
return redirect(url_for('index'))
# url_for 的值为要跳转路由的函数名,如果使用了蓝图,值为 蓝图名.函数名

模板引擎传值

1
2
3
@app.route('/')
def index():
return render_template('index.html',msg='messgae')

html 文件中使用 {{ msg }} 接收值

动态路由 & 路由传值

动态路由格式:<converter:variable_name>,converter 可不传默认为类型为 string

converter variable_name
string (缺省值) 接受任何不包含斜杠的文本
int 接受正整数
float 接受正浮点数
path 类似 string ,但可以包含斜杠
uuid 接受 UUID 字符串
1
2
3
4
5
6
7
8
@app.route('/')
def hello():
return redirect(url_for('error', msg='throw an error'))

@app.router('/error/<msg>')
def error(msg):
print(msg) # throw an error
return msg

静态文件

静态文件夹 /static,通过 ip:port/static/xxx 访问

路由结尾加不加斜杠?

1
2
3
4
5
6
7
@app.route('/projects/')
def projects():
return 'The project page'

@app.route('/about')
def about():
return 'The about page'

这两种路由的区别是,如果访问 /projects 的 URL,Flask 会自动重定向到 /projects/

而 /about 只能使用 /about 来访问,使用 /about/ 访问会 404 错误

http 方法

1
2
3
4
5
6
7
@user.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('home/login.html')
else:
print(request.method == 'POST') # true
return 'this is a post request'

可以根据请求类型处理表单请求

请求对象 request

request 获取数据的两种格式,一种是 request.xxx.get(‘xxx’),一种是 request.xxx[‘xxx’]

最基本的 request.method 获取请求类型, request.path 获取请求路径

更多查看 https://dormousehole.readthedocs.io/en/latest/api.html#flask.Request

1
2
3
4
5
@app.route('/user')
def user():
print(request.args.get('name')) # 访问 /user?name=zs 输出 zs
print(request.json.get('xxx')) # 当请求头 Content-Type: application/json 时获取发送 json 内容
print(request.form.get('xxx')) # 获取 form 表单提交内容

session

使用 session 前需配置 SECRET_KEY,app.config['SECRET_KEY'] = xxx,也可以使用配置文件配置

https://dormousehole.readthedocs.io/en/latest/config.html#id5

Flask 中 通过 session['xxx'] = xxx 设置 session

session['xxx'](不存在抛出异常) 或者 session.get('xxx')(不存在返回 None) 来获取 session

session.pop('xxx') 移除一个 session

session.clear() 清除所有 session