您好,欢迎访问一九零五行业门户网

Python如何使用Web框架Flask开发项目

一、简介flask是一个轻量级的基于python的web框架。
这份文档中的代码使用 python 3 运行。 
建议在 linux 下实践本教程中命令行操作、执行代码。
二、安装通过pip3安装flask即可:
$ sudo pip3 install flask
进入python交互模式看下flask的介绍和版本:
$ python3 >>> import flask>>> print(flask.__doc__) flask ~~~~~ a microframework based on werkzeug. it's extensively documented and follows best practice patterns. :copyright: © 2010 by the pallets team. :license: bsd, see license for more details. >>> print(flask.__version__)1.0.2
三、从 hello world 开始本节主要内容:使用flask写一个显示”hello world!”的web程序,如何配置、调试flask。
3.1 hello world按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












static和templates目录是默认配置,其中static用来存放静态资源,例如图片、js、css文件等。templates存放模板文件。
我们的网站逻辑基本在server.py文件中,当然,也可以给这个文件起其他的名字。
在server.py中加入以下内容:
from flask import flask app = flask(__name__) @app.route('/')def hello_world(): return 'hello world!' if __name__ == '__main__': app.run()
运行server.py:
$ python3 server.py * running on http://127.0.0.1:5000/
打开浏览器访问http://127.0.0.1:5000/,浏览页面上将出现hello world!。
终端里会显示下面的信息:
127.0.0.1 - - [16/may/2014 10:29:08] "get / http/1.1" 200 -
变量app是一个flask实例,通过下面的方式:
@app.route('/')def hello_world(): return 'hello world!'
当客户端访问/时,将响应hello_world()函数返回的内容。注意,这不是返回hello world!这么简单,hello world!只是http响应报文的实体部分,状态码等信息既可以由flask自动处理,也可以通过编程来制定。
3.2 修改flask的配置app = flask(__name__)
上面的代码中,python内置变量__name__的值是字符串__main__ 。flask类将这个参数作为程序名称。当然这个是可以自定义的,比如app = flask("my-app")。
flask默认使用static目录存放静态资源,templates目录存放模板,这是可以通过设置参数更改的:
app = flask("my-app", static_folder="path2", template_folder="path3")
更多参数请参考__doc__:
from flask import flaskprint(flask.__doc__)
3.3 调试模式上面的server.py中以app.run()方式运行,这种方式下,如果服务器端出现错误是不会在客户端显示的。但是在开发环境中,显示错误信息是很有必要的,要显示错误信息,应该以下面的方式运行flask:
app.run(debug=true)
将debug设置为true的另一个好处是,程序启动后,会自动检测源码是否发生变化,若有变化则自动重启程序。这可以帮我们省下很多时间。
3.4 绑定ip和端口默认情况下,flask绑定ip为127.0.0.1,端口为5000。我们也可以通过下面的方式自定义:
app.run(host='0.0.0.0', port=80, debug=true)
0.0.0.0代表电脑所有的ip。80是http网站服务的默认端口。什么是默认?比如,我们访问网站http://www.example.com,其实是访问的http://www.example.com:80,只不过:80可以省略不写。
由于绑定了80端口,需要使用root权限运行server.py。也就是:
$ sudo python3 server.py
四、获取 url 参数url参数是出现在url中的键值对,例如http://127.0.0.1:5000/?disp=3中的url参数是{'disp':3}。
4.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












4.2 列出所有的url参数在server.py中添加以下内容:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): return request.args.__str__() if __name__ == '__main__': app.run(port=5000, debug=true)
在浏览器中访问http://127.0.0.1:5000/?user=flask&time&p=7&p=8,将显示:
immutablemultidict([('user', 'flask'), ('time', ''), ('p', '7'), ('p', '8')])
较新的浏览器也支持直接在url中输入中文(最新的火狐浏览器内部会帮忙将中文转换成符合url规范的数据),在浏览器中访问http://127.0.0.1:5000/?info=这是爱,,将显示:
immutablemultidict([('info', '这是爱,')])
浏览器传给我们的flask服务的数据长什么样子呢?可以通过request.full_path和request.path来看一下:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): print(request.path) print(request.full_path) return request.args.__str__() if __name__ == '__main__': app.run(port=5000, debug=true)
浏览器访问http://127.0.0.1:5000/?info=这是爱,,运行server.py的终端会输出:
1./
2./?info=%e8%bf%99%e6%98%af%e7%88%b1%ef%bc%8c
4.3 获取某个指定的参数例如,要获取键info对应的值,如下修改server.py:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): return request.args.get('info') if __name__ == '__main__': app.run(port=5000)
运行server.py,在浏览器中访问http://127.0.0.1:5000/?info=hello,浏览器将显示:
hello
不过,当我们访问http://127.0.0.1:5000/时候却出现了500错误
为什么为这样?
这是因为没有在url参数中找到info。所以request.args.get('info')返回python内置的none,而flask不允许返回none。
解决方法很简单,我们先判断下它是不是none:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): r = request.args.get('info') if r==none: # do something return '' return r if __name__ == '__main__': app.run(port=5000, debug=true)
另外一个方法是,设置默认值,也就是取不到数据时用这个值:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): r = request.args.get('info', 'hi') return r if __name__ == '__main__': app.run(port=5000, debug=true)
函数request.args.get的第二个参数用来设置默认值。此时在浏览器访问http://127.0.0.1:5000/,将显示:
hi
4.4 如何处理多值还记得上面有一次请求是这样的吗? http://127.0.0.1:5000/?user=flask&time&p=7&p=8,仔细看下,p有两个值。
如果我们的代码是:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): r = request.args.get('p') return r if __name__ == '__main__': app.run(port=5000, debug=true)
在浏览器中请求时,我们只会看到7。如果我们需要把p的所有值都获取到,该怎么办?
不用get,用getlist:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): r = request.args.getlist('p') # 返回一个list return str(r) if __name__ == '__main__': app.run(port=5000, debug=true)
浏览器输入 http://127.0.0.1:5000/?user=flask&time&p=7&p=8,我们会看到['7', '8']。
五、获取post方法传送的数据作为一种http请求方法,post用于向指定的资源提交要被处理的数据。我们在某网站注册用户、写文章等时候,需要将数据传递到网站服务器中。并不适合将数据放到url参数中,密码放到url参数中容易被看到,文章数据又太多,浏览器不一定支持太长长度的url。这时,一般使用post方法。
本文使用python的requests库模拟浏览器。
安装方法:
$ sudo pip3 install requests
5.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












5.2 查看post数据内容以用户注册为例子,我们需要向服务器/register传送用户名name和密码password。如下编写helloworld/server.py。
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/register', methods=['post'])def register(): print(request.headers) print(request.stream.read()) return 'welcome' if __name__ == '__main__': app.run(port=5000, debug=true)
`@app.route(‘/register’, methods=[‘post’])是指url/register只接受post方法。可以根据需要修改methods`参数,例如如果想要让它同时支持get和post,这样写:
@app.route('/register', methods=['get', 'post'])
浏览器模拟工具client.py内容如下:
import requests user_info = {'name': 'letian', 'password': '123'}r = requests.post("http://127.0.0.1:5000/register", data=user_info) print(r.text)
运行helloworld/server.py,然后运行client.py。client.py将输出:
welcome
而helloworld/server.py在终端中输出以下调试信息(通过print输出):
host: 127.0.0.1:5000user-agent: python-requests/2.19.1accept-encoding: gzip, deflateaccept: */*connection: keep-alivecontent-length: 24content-type: application/x-www-form-urlencoded b'name=letian&password=123'
前6行是client.py生成的http请求头,由print(request.headers)输出。
请求体的数据,我们通过print(request.stream.read())输出,结果是:
b'name=letian&password=123'
5.3 解析post数据上面,我们看到post的数据内容是:
b'name=letian&password=123'
我们要想办法把我们要的name、password提取出来,怎么做呢?自己写?不用,flask已经内置了解析器request.form。
我们将服务代码改成:
from flask import flask, request app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/register', methods=['post'])def register(): print(request.headers) # print(request.stream.read()) # 不要用,否则下面的form取不到数据 print(request.form) print(request.form['name']) print(request.form.get('name')) print(request.form.getlist('name')) print(request.form.get('nickname', default='little apple')) return 'welcome' if __name__ == '__main__': app.run(port=5000, debug=true)
执行client.py请求数据,服务器代码会在终端输出:
host: 127.0.0.1:5000user-agent: python-requests/2.19.1accept-encoding: gzip, deflateaccept: */*connection: keep-alivecontent-length: 24content-type: application/x-www-form-urlencoded immutablemultidict([('name', 'letian'), ('password', '123')])letianletian['letian']little apple
request.form会自动解析数据。
request.form['name']和request.form.get('name')都可以获取name对应的值。对于request.form.get()可以为参数default指定值以作为默认值。所以:
print(request.form.get('nickname', default='little apple'))
输出的是默认值
little apple
如果name有多个值,可以使用request.form.getlist('name'),该方法将返回一个列表。我们将client.py改一下:
import requests user_info = {'name': ['letian', 'letian2'], 'password': '123'}r = requests.post("http://127.0.0.1:5000/register", data=user_info) print(r.text)
此时运行client.py,print(request.form.getlist('name'))将输出:
[u'letian', u'letian2']
六、处理和响应json数据使用 http post 方法传到网站服务器的数据格式可以有很多种,比如「5. 获取post方法传送的数据」讲到的name=letian&password=123这种用过&符号分割的key-value键值对格式。我们也可以用json格式、xml格式。相比xml的重量、规范繁琐,json显得非常小巧和易用。
6.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












6.2 处理json格式的请求数据如果post的数据是json格式,request.json会自动将json数据转换成python类型(字典或者列表)。
编写server.py:
from flask import flask, request app = flask("my-app") @app.route('/')def hello_world(): return 'hello world!' @app.route('/add', methods=['post'])def add(): print(request.headers) print(type(request.json)) print(request.json) result = request.json['a'] + request.json['b'] return str(result) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=true)
编写client.py模拟浏览器请求:
import requests json_data = {'a': 1, 'b': 2} r = requests.post("http://127.0.0.1:5000/add", json=json_data) print(r.text)
运行server.py,然后运行client.py,client.py 会在终端输出:
3
server.py 会在终端输出:
host: 127.0.0.1:5000user-agent: python-requests/2.19.1accept-encoding: gzip, deflateaccept: */*connection: keep-alivecontent-length: 16content-type: application/json {'a': 1, 'b': 2}
注意,请求头中content-type的值是application/json。
6.3 响应json-方案1响应json时,除了要把响应体改成json格式,响应头的content-type也要设置为application/json。
编写server2.py:
from flask import flask, request, responseimport json app = flask("my-app") @app.route('/')def hello_world(): return 'hello world!' @app.route('/add', methods=['post'])def add(): result = {'sum': request.json['a'] + request.json['b']} return response(json.dumps(result), mimetype='application/json') if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=true)
修改后运行。
编写client2.py:
import requests json_data = {'a': 1, 'b': 2} r = requests.post("http://127.0.0.1:5000/add", json=json_data) print(r.headers)print(r.text)
运行client.py,将显示:
{'content-type': 'application/json', 'content-length': '10', 'server': 'werkzeug/0.14.1 python/3.6.4', 'date': 'sat, 07 jul 2018 05:23:00 gmt'}{"sum": 3}
上面第一段内容是服务器的响应头,第二段内容是响应体,也就是服务器返回的json格式数据。
另外,如果需要服务器的http响应头具有更好的可定制性,比如自定义server,可以如下修改add()函数:
@app.route('/add', methods=['post'])def add(): result = {'sum': request.json['a'] + request.json['b']} resp = response(json.dumps(result), mimetype='application/json') resp.headers.add('server', 'python flask') return resp
client2.py运行后会输出:
{'content-type': 'application/json', 'content-length': '10', 'server': 'python flask', 'date': 'sat, 07 jul 2018 05:26:40 gmt'}{"sum": 3}
6.4 响应json-方案2使用 jsonify 工具函数即可。
from flask import flask, request, jsonify app = flask("my-app") @app.route('/')def hello_world(): return 'hello world!' @app.route('/add', methods=['post'])def add(): result = {'sum': request.json['a'] + request.json['b']} return jsonify(result) if __name__ == '__main__': app.run(host='127.0.0.1', port=5000, debug=true)
七、上传文件上传文件,一般也是用post方法。
7.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












7.2 上传文件这一部分的代码参考自how to upload a file to the server in flask。
我们以上传图片为例:
假设将上传的图片只允许’png’、’jpg’、’jpeg’、’gif’这四种格式,通过url/upload使用post上传,上传的图片存放在服务器端的static/uploads目录下。
首先在项目helloworld中创建目录static/uploads:
mkdir helloworld/static/uploads
werkzeug库可以判断文件名是否安全,例如防止文件名是../../../a.png,安装这个库:
$ sudo pip3 install werkzeug
server.py代码:
from flask import flask, request from werkzeug.utils import secure_filenameimport os app = flask(__name__) # 文件上传目录app.config['upload_folder'] = 'static/uploads/'# 支持的文件格式app.config['allowed_extensions'] = {'png', 'jpg', 'jpeg', 'gif'} # 集合类型 # 判断文件名是否是我们支持的格式def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1] in app.config['allowed_extensions'] @app.route('/')def hello_world(): return 'hello world' @app.route('/upload', methods=['post'])def upload(): upload_file = request.files['image'] if upload_file and allowed_file(upload_file.filename): filename = secure_filename(upload_file.filename) # 将文件保存到 static/uploads 目录,文件名同上传时使用的文件名 upload_file.save(os.path.join(app.root_path, app.config['upload_folder'], filename)) return 'info is '+request.form.get('info', '')+'. success' else: return 'failed' if __name__ == '__main__': app.run(port=5000, debug=true)
app.config中的config是字典的子类,可以用来设置自有的配置信息,也可以设置自己的配置信息。函数allowed_file(filename)用来判断filename是否有后缀以及后缀是否在app.config['allowed_extensions']中。
客户端上传的图片必须以image01标识。upload_file是上传文件对应的对象。app.root_path获取server.py所在目录在文件系统中的绝对路径。upload_file.save(path)用来将upload_file保存在服务器的文件系统中,参数最好是绝对路径,否则会报错(网上很多代码都是使用相对路径,但是笔者在使用相对路径时总是报错,说找不到路径)。函数os.path.join()用来将使用合适的路径分隔符将路径组合起来。
好了,定制客户端client.py:
import requestsfile_data = {'image': open('lenna.jpg', 'rb')}user_info = {'info': 'lenna'}r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files=file_data)print(r.text)
运行client.py,当前目录下的lenna.jpg将上传到服务器。
然后,我们可以在static/uploads中看到文件lenna.jpg。
要控制上产文件的大小,可以设置请求实体的大小,例如:
app.config['max_content_length'] = 16 * 1024 * 1024 #16mb
不过,在处理上传文件时候,需要使用try:...except:...。
如果要获取上传文件的内容可以:
file_content = request.files['image'].stream.read()
八、restful url简单来说,restful url可以看做是对 url 参数的替代。
8.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












8.2 编写代码编辑server.py:
from flask import flask app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/user/')def user(username): print(username) print(type(username)) return 'hello ' + username @app.route('/user//friends')def user_friends(username): print(username) print(type(username)) return 'hello ' + username if __name__ == '__main__': app.run(port=5000, debug=true)
运行helloworld/server.py。使用浏览器访问http://127.0.0.1:5000/user/letian,helloworld/server.py将输出:
letian

而访问http://127.0.0.1:5000/user/letian/,响应为404 not found。
浏览器访问http://127.0.0.1:5000/user/letian/friends,可以看到:
hello letian. they are your friends.
helloworld/server.py输出:
letian

8.3 转换类型由上面的示例可以看出,使用 restful url 得到的变量默认为str对象。如果我们需要通过分页显示查询结果,那么需要在url中有数字来指定页数。按照上面方法,可以在获取str类型页数变量后,将其转换为int类型。不过,还有更方便的方法,就是用flask内置的转换机制,即在route中指定该如何转换。
新的服务器代码:
from flask import flask app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/page/')def page(num): print(num) print(type(num)) return 'hello world' if __name__ == '__main__': app.run(port=5000, debug=true)
`@app.route(‘/page/int:num‘)`会将num变量自动转换成int类型。
运行上面的程序,在浏览器中访问http://127.0.0.1:5000/page/1,helloworld/server.py将输出如下内容:
1
如果访问的是http://127.0.0.1:5000/page/asd,我们会得到404响应。
在官方资料中,说是有3个默认的转换器:
int accepts integersfloat like int but for floating point valuespath like the default but also accepts slashes
看起来够用了。
8.4 一个有趣的用法如下编写服务器代码:
from flask import flask app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/page/-')def page(num1, num2): print(num1) print(num2) return 'hello world' if __name__ == '__main__': app.run(port=5000, debug=true)
在浏览器中访问http://127.0.0.1:5000/page/11-22,helloworld/server.py会输出:
1122
8.5 编写转换器自定义的转换器是一个继承werkzeug.routing.baseconverter的类,修改to_python和to_url方法即可。to_python方法用于将url中的变量转换后供被`@app.route包装的函数使用,to_url方法用于flask.url_for`中的参数转换。
下面是一个示例,将helloworld/server.py修改如下:
from flask import flask, url_for from werkzeug.routing import baseconverter class myintconverter(baseconverter): def __init__(self, url_map): super(myintconverter, self).__init__(url_map) def to_python(self, value): return int(value) def to_url(self, value): return value * 2 app = flask(__name__)app.url_map.converters['my_int'] = myintconverter @app.route('/')def hello_world(): return 'hello world' @app.route('/page/')def page(num): print(num) print(url_for('page', num=123)) # page 对应的是 page函数 ,num 对应对应`/page/`中的num,必须是str return 'hello world' if __name__ == '__main__': app.run(port=5000, debug=true)
浏览器访问http://127.0.0.1:5000/page/123后,helloworld/server.py的输出信息是:
123/page/123123
九、使用url_for生成链接工具函数url_for可以让你以软编码的形式生成url,提供开发效率。
9.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












9.2 编写代码编辑helloworld/server.py:
from flask import flask, url_for app = flask(__name__) @app.route('/')def hello_world(): pass @app.route('/user/')def user(name): pass @app.route('/page/')def page(num): pass @app.route('/test')def test(): print(url_for('hello_world')) print(url_for('user', name='letian')) print(url_for('page', num=1, q='hadoop mapreduce 10%3')) print(url_for('static', filename='uploads/01.jpg')) return 'hello' if __name__ == '__main__': app.run(debug=true)
运行helloworld/server.py。然后在浏览器中访问http://127.0.0.1:5000/test,helloworld/server.py将输出以下信息:
//user/letian/page/1?q=hadoop+mapreduce+10%253/static/uploads/01.jpg
十、使用redirect重定向网址redirect函数用于重定向,实现机制很简单,就是向客户端(浏览器)发送一个重定向的http报文,浏览器会去访问报文中指定的url。
10.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












10.2 编写代码使用redirect时,给它一个字符串类型的参数就行了。
编辑helloworld/server.py:
from flask import flask, url_for, redirect app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/test1')def test1(): print('this is test1') return redirect(url_for('test2')) @app.route('/test2')def test2(): print('this is test2') return 'this is test2' if __name__ == '__main__': app.run(debug=true)
运行helloworld/server.py,在浏览器中访问http://127.0.0.1:5000/test1,浏览器的url会变成http://127.0.0.1:5000/test2,并显示:
this is test2
十一、使用jinja2模板引擎模板引擎负责mvc中的v(view,视图)这一部分。flask默认使用jinja2模板引擎。
flask与模板相关的函数有:
flask.render_template(template_name_or_list, **context)
renders a template from the template folder with the given context.
flask.render_template_string(source, **context)
renders a template from the given template source string with the given context.
flask.get_template_attribute(template_name, attribute)
loads a macro (or variable) a template exports. this can be used to invoke a macro from within python code.
这其中常用的就是前两个函数。
这个实例中使用了模板继承、if判断、for循环。
11.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












11.2 创建并编辑helloworld/templates/default.html内容如下:
<html><head> <title> {% if page_title %} {{ page_title }} {% endif %} </title></head> <body> {% block body %}{% endblock %} ```可以看到,在``标签中使用了if判断,如果给模板传递了`page_title`变量,显示之,否则,不显示。``标签中定义了一个名为`body`的block,用来被其他模板文件继承。### 11.3 创建并编辑helloworld/templates/user_info.html内容如下:```{% extends "default.html" %} {% block body %} {% for key in user_info %} {{ key }}: {{ user_info[key] }} {% endfor %}{% endblock %}
变量user_info应该是一个字典,for循环用来循环输出键值对。
11.4 编辑helloworld/server.py内容如下:
from flask import flask, render_template app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/user')def user(): user_info = { 'name': 'letian', 'email': '123@aa.com', 'age':0, 'github': 'https://github.com/letiantian' } return render_template('user_info.html', page_title='letian\'s info', user_info=user_info) if __name__ == '__main__': app.run(port=5000, debug=true)
render_template()函数的第一个参数指定模板文件,后面的参数是要传递的数据。
11.5 运行与测试运行helloworld/server.py:
$ python3 helloworld/server.py
在浏览器中访问http://127.0.0.1:5000/user
查看网页源码:
<html><head> <title> letian&&9;s info </title></head><body> name: letian <br/> email: 123@aa.com <br/> age: 0 <br/> github: https://github.com/letiantian <br/></body></html>
十二、自定义404等错误的响应要处理http错误,可以使用flask.abort函数。
12.1 示例1:简单入门建立flask项目
按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












代码
编辑helloworld/server.py:
from flask import flask, render_template_string, abort app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/user')def user(): abort(401) # unauthorized 未授权 print('unauthorized, 请先登录') if __name__ == '__main__': app.run(port=5000, debug=true)
效果
运行helloworld/server.py,浏览器访问http://127.0.0.1:5000/user
要注意的是,helloworld/server.py中abort(401)后的print并没有执行。
12.2 示例2:自定义错误页面代码
将服务器代码改为:
from flask import flask, render_template_string, abort app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/user')def user(): abort(401) # unauthorized @app.errorhandler(401)def page_unauthorized(error): return render_template_string(' unauthorized {{ error_info }}', error_info=error), 401 if __name__ == '__main__': app.run(port=5000, debug=true)
page_unauthorized函数返回的是一个元组,401 代表http 响应状态码。如果省略401,则响应状态码会变成默认的 200。
效果
运行helloworld/server.py,浏览器访问http://127.0.0.1:5000/user
十三、用户会话session用来记录用户的登录状态,一般基于cookie实现。
下面是一个简单的示例。
13.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












13.2 编辑helloworld/server.py内容如下:
from flask import flask, render_template_string, \ session, request, redirect, url_for app = flask(__name__) app.secret_key = 'f12zr47j\3yx r~x@h!jlwf/t' @app.route('/')def hello_world(): return 'hello world' @app.route('/login')def login(): return render_template_string(page)@app.route('/do_login', methods=['post'])def do_login(): name = request.form.get('user_name') session['user_name'] = name return 'success' @app.route('/show')def show(): return session['user_name'] @app.route('/logout')def logout(): session.pop('user_name', none) return redirect(url_for('login')) if __name__ == '__main__': app.run(port=5000, debug=true)
13.3 代码的含义app.secret_key用于给session加密。
在/login中将向用户展示一个表单,要求输入一个名字,submit后将数据以post的方式传递给/do_login,/do_login将名字存放在session中。
如果用户成功登录,访问/show时会显示用户的名字。此时,打开firebug等调试工具,选择session面板,会看到有一个cookie的名称为session。
/logout用于登出,通过将session中的user_name字段pop即可。flask中的session基于字典类型实现,调用pop方法时会返回pop的键对应的值;如果要pop的键并不存在,那么返回值是pop()的第二个参数。
另外,使用redirect()重定向时,一定要在前面加上return。
13.4 效果进入http://127.0.0.1:5000/login,输入name,点击submit
进入http://127.0.0.1:5000/show查看session中存储的name:
13.5 设置sessin的有效时间下面这段代码来自is there an easy way to make sessions timeout in flask?:
from datetime import timedeltafrom flask import session, app session.permanent = trueapp.permanent_session_lifetime = timedelta(minutes=5)
这段代码将session的有效时间设置为5分钟。
十四、使用cookiecookie是存储在客户端的记录访问者状态的数据。 常用的用于记录用户登录状态的session大多是基于cookie实现的。
cookie可以借助flask.response来实现。下面是一个示例。
14.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












14.2 代码修改helloworld/server.py:
from flask import flask, request, response, make_responseimport time app = flask(__name__) @app.route('/')def hello_world(): return 'hello world' @app.route('/add')def login(): res = response('add cookies') res.set_cookie(key='name', value='letian', expires=time.time()+6*60) return res @app.route('/show')def show(): return request.cookies.__str__() @app.route('/del')def del_cookie(): res = response('delete cookies') res.set_cookie('name', '', expires=0) return res if __name__ == '__main__': 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=&rsquo;&rsquo;, max_age=none, expires=none, path=&rsquo;/&lsquo;, 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 &ndash; the key (name) of the cookie to be set.
value &ndash; the value of the cookie.
max_age &ndash; should be a number of seconds, or none (default) if the cookie should last only as long as the client&rsquo;s browser session.
expires &ndash; should be a datetime object or unix timestamp.
domain &ndash; 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 &ndash; limits the cookie to a given path, per default it will span the whole domain.
14.3 运行与测试运行helloworld/server.py:
$ python3 helloworld/server.py

使用浏览器打开http://127.0.0.1:5000/add,浏览器界面会显示
add cookies
下面查看一下cookie,如果使用firefox浏览器,可以用firebug插件查看。打开firebug,选择cookies选项,刷新页面,可以看到名为name的cookie,其值为letian。
在“网络”选项中,可以查看响应头中类似下面内容的设置cookie的http「指令」:
set-cookie: name=letian; expires=sun, 29-jun-2014 05:16:27 gmt; path=/
在cookie有效期间,使用浏览器访问http://127.0.0.1:5000/show,可以看到:
{'name': 'letian'}
十五、闪存系统 flashing systemflask的闪存系统(flashing system)用于向用户提供反馈信息,这些反馈信息一般是对用户上一次操作的反馈。反馈信息是存储在服务器端的,当服务器向客户端返回反馈信息后,这些反馈信息会被服务器端删除。
下面是一个示例。
15.1 建立flask项目按照以下命令建立flask项目helloworld:
mkdir helloworldmkdir helloworld/staticmkdir helloworld/templatestouch helloworld/server.py












15.2 编写helloworld/server.py内容如下:
from flask import flask, flash, get_flashed_messagesimport 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(info) return info @app.route('/show1')def show1(): return get_flashed_messages().__str__() @app.route('/show2')def show2(): return get_flashed_messages().__str__() if __name__ == "__main__": app.run(port=5000, debug=true)
15.3 效果运行服务器:
$ python3 helloworld/server.py

打开浏览器,访问http://127.0.0.1:5000/gen,浏览器界面显示(注意,时间戳是动态生成的,每次都会不一样,除非并行访问):
access at 1404020982.83
查看浏览器的cookie,可以看到session,其对应的内容是:
.ejyrvoppy0kszkgtvrkkrlzskifqsupwsknhyvxjrm55uyg2tkq1oldryhc_rkgivyppdzcdtxdxa1-xwhlfledtfxfpun8xx6dkwcaeajkbgq8.bpe6dg.f1vurza7vqu9bvbc4xibo9-3y4y
再一次访问http://127.0.0.1:5000/gen,浏览器界面显示:
access at 1404021130.32
cookie中session发生了变化,新的内容是:
.ejyrvoppy0kszkgtvrkkrlzskifqsupwsknhyvxjrm55uyg2tkq1oldryhc_rkgivyppdzcdtxdxa1-xwhlfledtfxfpun8xx6dkwlbamg1yrfctciz1rfiegxrbcwahgjc5.bpe7cg.cb_b_k2otqczhkngnpnjq5u4dqw
然后使用浏览器访问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,只会得到:
[]
15.4 高级用法flash系统也支持对flash的内容进行分类。修改helloworld/server.py内容:
from flask import flask, flash, get_flashed_messagesimport 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,得到的内容为空:
[]
15.5 在模板文件中获取flash的内容在flask中,get_flashed_messages()默认已经集成到jinja2模板引擎中,易用性很强。
以上就是python如何使用web框架flask开发项目的详细内容。
其它类似信息

推荐信息