2.1 初始化
所有Flask程序都必须创建一个程序实例。
Web服务器使用一种名为Web服务器网关接口(Web Server Gateway Interface,WSGI)的协议,把接收自客户端的所有请求都转交给这个对象处理。程序实例是Flask类的对象,经常使用下述代码创建:
from flask import Flask
app = Flask(__name__)
Flask类的构造函数只有一个必须指定的参数,即程序主模块或包的名字。在大多数程序中,Python的name变量就是所需的值。
2.2 路由和视图函数
处理URL和函数之间关系的程序称为路由。在Flask中,使用程序实例提供的app.route修饰器,把修饰的函数注册为路由。如:
@app.route('/') #用app.route修饰器定义路由
def index():
return '<h1>Hello World!</h1>'
如上代码即把网站的根目录(用/表示)和index()函数绑定在一起,即访问网站首页时,会获得函数index()返回的内容。这里的index()被称为视图函数
动态URL
动态URL可以根据URL中参数的不同而返回不同的页面内容。在Flask中可以通过修饰器实现这一功能:
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name
尖括号中的内容就是动态部分。调用视图函数时,Flask会将动态部分作为参数传入函数。 路由中的动态部分默认使用字符串,不过也可以使用类型定义。
eg- 路由/user/只会匹配动态片段id为整数的URL。
Flask支持在路由中使用int、float、path类型,path类型也是字符串,但不把斜线视为分隔符,而将其当作动态片段的一部分。
2.3 启动服务器
程序实例用run方法来启动Flask中集成的Web服务器:
if __name__ == '__main__': '''当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行'''
app.run(debug=True)
在run函数中设置debug=True可以启用调试模式,在服务器启动后,会进入轮询,直到程度停止。
2.4 一个完整的程序
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
if __name__ == '__main__':
app.run(debug=True)
然后使用下述命令启动程序:
(venv) $ python hello.py
* Running on http://127.0.0.1:5000/
* Restarting with reloader
使用Flask-Script支持命令行选项
使用Flask-Script扩展后,可以通过命令行参数的形式将参数传递给Flask的开发Web服务器 可通过以下命令安装该扩展:
(venv) $ pip install flask-script
Flask-Script扩展的使用示例
from flask import Flask
from flask import make_response
from flask.ext.script import Manager
app = Flask(__name__)
manager = Manager(app)
@app.route('/')
def index():
return '<h1>Hello World!</h1>'
@app.route('/user/<name>')
def user(name):
return '<h1>Hello, %s!</h1>' % name
@app.route('/response')
def response():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
if __name__ == '__main__':
manager.run()
此时,执行python hello.py可得到一个使用提示。主要使用方法有两个:runserver和shell,前者用于启动Web服务器,后者用于启动python shell用于维护任务和调试。可分别通过以下命令执行:
python hello.py runserver
python hello.py shell
运行python python hello.py runserver --help
可获得更多帮助信息