Python Flask Web 框架入门
本文主要借鉴 letiantian 的文章 http://www.letiantian.me/learn-flask/
一、简介
二、安装
三、初始化Flask
四、获取URL参数 (GET请求)
五、获取POST方法传送的数据
六、处理和响应JSON数据
七、上传文件
八、Restful URL
九、使用url_for生成链接
十、使用redirect重定向网址
十一、使用Jinja2模板引擎
十二、自定义404等错误的响应
十三、用户会话
十四、使用Cookie
十五、闪存系统 flashing system
一、简介
1、Flask 是一个轻量级的基于 Python 的 Web 框架,支持 Python 2 和 Python 3,简单易用,适合快速开发。封装功能不及Django完善,性能不及Tornado,但是Flask的第三方开源组件比丰富(http://flask.pocoo.org/extensions/),其 WSGI工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。
本文章中的代码使用 Python 3 运行,建议安装最新版本,本文使用的是Python 3.6.4。
2、其他web框架
(1)Django:比较“重”的框架,同时也是最出名的Python框架。包含了web开发中常用的功能、组件的框架(ORM、Session、Form、Admin、分页、中间件、信号、缓存、ContenType....),Django是走大而全的方向,最出名的是其全自动化的管理后台:只需要使用起ORM,做简单的对象定义,它就能自动生成数据库结构、以及全功能的管理后台。
(2)Tornado:大特性就是异步非阻塞、原生支持WebSocket协议;
(3)Flask:如上
(4)Bottle:是一个简单高效的遵循WSGI的微型python Web框架。说微型,是因为它只有一个文件,除Python标准库外,它不依赖于任何第三方模块。
http://zh.wikipedia.org/wiki/Cookie
1、创建项目
1 mkdir HelloWorld 2 mkdir HelloWorld/static 3 mkdir HelloWorld/templates 4 touch HelloWorld/server.py
2、代码
(1)修改server.py
1 from flask import Flask, request, Response, make_response
2 import time
3
4 app = Flask(__name__)
5
6
7 @app.route('/')
8 def hello_world():
9 return 'hello world'
10
11
12 @app.route('/add')
13 def login():
14 res = Response('add cookies')
15 res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
16 return res
17
18
19 @app.route('/show')
20 def show():
21 return request.cookies.__str__()
22
23
24 @app.route('/del')
25 def del_cookie():
26 res = Response('delete cookies')
27 res.set_cookie('name', '', expires=0)
28 return res
29
30
31 if __name__ == '__main__':
32 app.run(port=5000, debug=True)
由上可以看到,可以使用Response.set_cookie添加和删除cookie。expires参数用来设置cookie有效时间,它的值可以是datetime对象或者unix时间戳,笔者使用的是unix时间戳。
res.set_cookie(key='name', value='letian', expires=time.time()+6*60)
上面的expire参数的值表示cookie在从现在开始的6分钟内都是有效的。
要删除cookie,将expire参数的值设为0即可:
res.set_cookie('name', '', expires=0)
set_cookie()函数的原型如下:
set_cookie(key, value=’’, max_age=None, expires=None, path=’/‘, domain=None, secure=None, httponly=False)
Sets a cookie. The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data, too.
Parameters:
key – the key (name) of the cookie to be set.
value – the value of the cookie.
max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.
expires – should be a datetime object or UNIX timestamp.
domain – if you want to set a cross-domain cookie. For example, domain=”.example.com” will set a cookie that is readable by the domain
www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
path – limits the cookie to a given path, per default it will span the whole domain.
(2)运行与测试
<1> 运行server.py,使用浏览器打开http://127.0.0.1:5000/add,浏览器界面会显示:
add cookies
<2> 查看cookie,如果使用firefox浏览器,可以用firebug插件查看。打开firebug,选择Cookies选项,刷新页面,可以看到名为name的cookie,其值为letian。
在“网络”选项中,可以查看响应头中类似下面内容的设置cookie的HTTP「指令」:
Set-Cookie: name=letian; Expires=Sun, 29-Jun-2014 05:16:27 GMT; Path=/
<3> 在cookie有效期间,使用浏览器访问http://127.0.0.1:5000/show,可以看到:
{'name': 'letian'}
十五、闪存系统 flashing system
Flask的闪存系统(flashing system)用于向用户提供反馈信息,这些反馈信息一般是对用户上一次操作的反馈。反馈信息是存储在服务器端的,当服务器向客户端返回反馈信息后,这些反馈信息会被服务器端删除。
1、创建项目
1 mkdir HelloWorld 2 mkdir HelloWorld/static 3 mkdir HelloWorld/templates 4 touch HelloWorld/server.py
2、编写server.py
1 from flask import Flask, flash, get_flashed_messages
2 import time
3
4 app = Flask(__name__)
5 app.secret_key = 'some_secret'
6
7
8 @app.route('/')
9 def index():
10 return 'hi'
11
12
13 @app.route('/gen')
14 def gen():
15 info = 'access at '+ time.time().__str__()
16 flash(info)
17 return info
18
19
20 @app.route('/show1')
21 def show1():
22 return get_flashed_messages().__str__()
23
24
25 @app.route('/show2')
26 def show2():
27 return get_flashed_messages().__str__()
28
29
30 if __name__ == "__main__":
31 app.run(port=5000, debug=True)
3、效果
(1)打开浏览器,访问http://127.0.0.1:5000/gen,浏览器界面显示(注意,时间戳是动态生成的,每次都会不一样,除非并行访问):
access at 1404020982.83
(2)查看浏览器的cookie,可以看到session,其对应的内容是:
.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWCAEAJKBGq8.BpE6dg.F1VURZa7VqU9bvbC4XIBO9-3Y4Y
(3)再一次访问http://127.0.0.1:5000/gen,浏览器界面显示:
access at 1404021130.32
cookie中session发生了变化,新的内容是:
.eJyrVopPy0kszkgtVrKKrlZSKIFQSUpWSknhYVXJRm55UYG2tkq1OlDRyHC_rKgIvypPdzcDTxdXA1-XwHLfLEdTfxfPUn8XX6DKWLBaMg1yrfCtciz1rfIEGxRbCwAhGjC5.BpE7Cg.Cb_B_k2otqczhknGnpNjQ5u4dqw
(4)然后使用浏览器访问http://127.0.0.1:5000/show1,浏览器界面显示:
['access at 1404020982.83', 'access at 1404021130.32']
这个列表中的内容也就是上面的两次访问http://127.0.0.1:5000/gen得到的内容。此时,cookie中已经没有session了。
如果使用浏览器访问http://127.0.0.1:5000/show1或者http://127.0.0.1:5000/show2,只会得到:[ ]
4、高级用法
flash系统也支持对flash的内容进行分类。修改HelloWorld/server.py内容:
from flask import Flask, flash, get_flashed_messages
import time
app = Flask(__name__)
app.secret_key = 'some_secret'
@app.route('/')
def index():
return 'hi'
@app.route('/gen')
def gen():
info = 'access at '+ time.time().__str__()
flash('show1 '+info, category='show1')
flash('show2 '+info, category='show2')
return info
@app.route('/show1')
def show1():
return get_flashed_messages(category_filter='show1').__str__()
@app.route('/show2')
def show2():
return get_flashed_messages(category_filter='show2').__str__()
if __name__ == "__main__":
app.run(port=5000, debug=True)
某一时刻,浏览器访问http://127.0.0.1:5000/gen,浏览器界面显示:
access at 1404022326.39
不过,由上面的代码可以知道,此时生成了两个flash信息,但分类(category)不同。
使用浏览器访问http://127.0.0.1:5000/show1,得到如下内容:
['1 access at 1404022326.39']
而继续访问http://127.0.0.1:5000/show2,得到的内容为空:[ ]
5、在模板文件中获取flash的内容
在Flask中,get_flashed_messages()默认已经集成到Jinja2模板引擎中,易用性很强。下面是来自官方的一个示例: