flask 使用的一些整理
资源
Flask 文档|英文| expore flask| 快速教材| flask-admin| Flask-DebugToolbar| Flask-Login| Flask-Cache|flask-sqlalchemy| flask-security| Flask-mako| Flask-Genshi| WTForms
最简单的hello world
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/usr/bin/env python
# encoding: utf-8
Flask
)
)
:
'hello world'
:
)
#app.run(host='127.0.0.1', port=8000)
|
之后,访问http://localhost:5000
支持post/get提交
|
1
|
)
|
多个url指向
|
1
2
|
)
)
|
不管post/get使用统一的接收
|
1
2
3
|
request
form
)
|
处理json请求
request的header中
|
1
|
|
处理时:
|
1
|
)
|
获取post提交中的checkbox
|
1
2
3
4
5
|
}
>
}
)
|
使用url中的参数
|
1
2
3
|
)
:
pass
|
在request开始结束dosomething
一般可以处理数据库连接等等
|
1
2
3
4
5
6
7
8
9
10
11
|
g
.
before_request
:
)
teardown_request
:
)
|
注册Jinja2模板中使用的过滤器
|
1
2
3
|
)
:
]
|
或者
|
1
2
3
|
:
]
reverse_filter
|
可以这么用
|
1
2
3
4
5
|
.
.
}
)
|
注册Jinja2模板中使用的全局变量
|
1
2
|
}
)
|
定义应用使用的template和static目录
|
1
|
)
|
使用Blueprint
|
1
2
3
4
5
6
7
8
9
10
11
|
Blueprint
)
#bp_test = Blueprint('test', __name__, url_prefix='/abc')
)
--
bp_test
)
)
|
实例:
|
1
2
3
|
)
)
#注意这种情况下Blueprint中url_prefix不能以 '/' 结尾, 否则404
|
使用session
包装cookie实现的,没有session id
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
'PS#yio`%_!((f_or(%)))s'
# 然后
session
1
)
)
#过期时间,通过cookie实现的
timedelta
True
)
|
反向路由
|
1
2
3
4
5
6
|
_template
)
:
)
)
|
上传文件
|
1
2
|
>
>
|
接收
|
1
2
|
)
)
|
直接返回某个文件
|
1
|
)
|
请求重定向
flask.redirect(location, code=302) the redirect status code. defaults to 302.Supported codes are 301, 302, 303, 305, and 307. 300 is not supported.
|
1
2
3
4
5
6
7
|
)
:
)
)
:
'Hello Foo!'
|
获取用户真实ip
从request.headers获取
|
1
|
)
|
或者, 使用werkzeug的middleware 文档
|
1
2
|
ProxyFix
)
|
return json & jsonp
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
json
json
# or others
)
)
:
(
,
)
)
|
配置读取方法
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# create our little application :)
)
# Load default config and override config from an environment variable
(
,
,
,
,
'default'
)
)
--
# configuration
'/tmp/minitwit.db'
30
True
'development key'
# create our little application :)
)
)
)
|
几个不常用的方法
|
1
2
3
4
5
6
7
8
|
flash
abort
:
)
flash
)
|
异步调用
想在flask的一个请求中处理异步, 除了使用消息系统, 可以用简单的线程处理
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Thread
:
:
)
)
wrapper
async
:
call_args
`
|
error handler
|
1
2
3
4
5
6
7
8
|
)
:
404
)
:
)
500
|
项目配置
1.直接
|
1
2
|
'xxx.a.com'
)
|
2.环境变量
|
1
2
|
cfg
)
|
3.对象
|
1
2
3
4
5
6
7
8
9
10
|
:
False
False
'sqlite://:memory:'
:
'mysql://user@localhost/foo'
)
# mysql://user@localhost/foo
|
4.文件
|
1
2
3
4
5
6
|
# default_config.py
'localhost'
5000
True
)
|
EG. 一个create_app方法
|
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
27
28
|
g
:
,
,
)
)
)
)
'PO+_)(*&678OUIJKKO#%_!(((%)))'
before_request
:
#do some thing
teardown_request
:
#do some thing
app
)
SERVER_IP
SERVER_PORT
)
|