Flask

Flask是一个用于开发web应用的微型框架,基于Python

Flask is a micro webdevelopment framework for Python.

Flask以扩展的形式实现数据库访问、Web表单验证和用户认证等高级功能

依赖两个外部库:Werkzeug实现WSGI(Web Server Gateway Interface),Jinjia2提供模板引擎

一个简单的Flask Web程序

创建Flask实例

1
2
from flask import Flask
app = Flask(__name__)

定义路由

route()装饰器将函数和URL建立联系,从而定义一个路由

1
2
3
@app.route('/')
def index():
return '<h1>Hello, world!</h1>'

像index()这样的函数称为视图函数(view function)

启动服务器

1
2
if __name__ == '__main__':
app.run(debug=True)

使用浏览器访问http://localhost:5000/,可见Hello, world!

一些关键概念

上下文

current_app

g

request

session

请求调度

url映射是URL与视图函数之间的对应关系

请求钩子

before_first_request

before_request

after_request

teardown_request

响应

make_response

WSGI

WSGI指web服务器网关接口,是实现服务器和Python web应用程序或框架之间通信的协议

该协议规定Python程序是一个可调用(callable)对象,接收两个参数,分别是environstart_response,这两个参数由服务器提供。其中environ是一个包含请求信息的字典,start_response是一个函数,接收statusresponse_headers两个参数

下面两个例子是符合以上要求的Python程序

1
2
3
4
5
6
def simple_app(environ, start_response):
"""Simplest possible application object"""
status = '200 OK'
response_headers = [(['Content-type', 'text/plain'])]
start_response(status, response_headers)
return ['Hello world!\n']
1
2
3
4
5
6
7
8
9
10
11
12
class AppClass:
"""Produce the same output, but using a class"""

def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response

def __iter__(self):
status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
self.start(status, response_headers)
yield "Hello world!\n"