Flask 是一个Web应用框架,我也就是一边看书,一边写博文做记录
这本书:
首先安装Flask ,和配置环境,参考这边博客:
然后就开始学习Flask 了。
1.Application and Request Context(上下文)
在Flask 中,一般一个view function(视图函数)会处理一个请求
Flask 中提供request context.保证全局只有一个线程的request,而不会同时出现两个request.
Application and Request Context 一共有四种
current_app (Application context)
g (Application context)
request (Request context)
session (Request context)
2.Request Dispatching(请求发送)
当服务器接受一个请求,Flask通过建立一个URL mapping ,为请求找到相应的视图函数。
Flast 利用 app.route 建立这个Map.
>>> from hello import app >>> app.url_map Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>, <Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>, <Rule '/user/<name>' (HEAD, OPTIONS, GET) -> user>])
其中 /static/<filename> route 是Flask中特有的。
3.Request Hooks(请求挂钩)
在接受请求或者处理完请求之后,都要执行一段代码。比如请求发送之前,我们需要连接一下数据库。所以
我们可以写一个连接数据库的通用函数。Flask 中Request hook function 提供了这个功能
有四种hook 函数
before_first_request: 当接受第一个请求之前要执行的代码。
before_request :接受每一个请求之前要执行的代码。
after_request:处理完每一个请求之后要执行的代码,只有请求成功处理之后。
teardown_request:处理完每一个请求之后要执行的代码,请求处理失败之后也可以执行的。
在 request hook function 和view function 之间的数据共享是通过全局的g context来完成的。
例如登录之前,通过before_request请求连接数据库的获取用户的信息 g.username。然后在
view function 中就可以调用g.username
4.Responses(回应)
每个view function 都会返回一个value。可以返回html 页面。
但是http 协议要求我们还需要返回一个状态,比如200 就是成功执行请求,400 就是执行请求发生错误。
for example app.route('/') def index(): return '<h1>error request<h1>,400'
view function 可以返回两个,也可以返回三个(value,status,headers)
Flask 也提供了专门一个函数make_response()
@app.route('/') def index2(): response=make_response('<h1>This document carries a cookie!</h1>') response.set_cookie('answer','42') return response
除此之外,还有两种response方式:
redirect(重定向) 实际上一个返回三个值的response
from flask import redirect @app.route('/') def index(): return redirect('http://www.example.com')
abort(用于抛出错误)
from flask import abort @app.route('/user/<id>') def get_user(id): user = load_user(id) if not user: abort(404) return '<h1>Hello, %s</h1>' % user.name