flask重温
flask 小型可扩展框架, 但是功能不少!
hello world!
# -*- coding: utf-8 -*-
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>hello world!</h1>'
if __name__ == '__main__':
app.run(debug=True)
要点 name 决定程序的根目录,用来找资源的文件
app.run 使用程序进入轮询
动态路由
@app.route('/user/<name>')
def user(name):
return '<h1> hello, %s!</h1>' % name
要点: 就是让参数加在路由上
上下文全局变量
current_app 激活的程序实例 g 程序上下文 request 请求上下文 session 用户会话
@app.route('/request')
def headers():
return '%s' % request.headers
请求钩子
before_first_request before_request after_request teardown_request
使用flask扩展
使用flask-script 支持命令行选项 pip install flask-script
from flask.ext.script import Manager
manager = Manager(app)
manager.run()
# python hello.py
usage: hello.py [-?] {shell,runserver} ...
positional arguments:
{shell,runserver}
shell Runs a Python shell inside Flask application context.
runserver Runs the Flask development server i.e. app.run()
optional arguments:
-?, --help show this help message and exit
要点:
扩展放在flask.ext下
完整实例
# -*- coding: utf-8 -*-
from flask import Flask
from flask.ext.script import Manager
from flask import request
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('/request')
def headers():
return '%s' % request.headers
if __name__ == '__main__':
manager.run()
参考
flask web 开发 基于python的web应用开发实践