Flask Tutorial
Setup
pip install flask
Quick Start
最简单的应用
from flask import Flask
app = Flask(__name__)
@app.route('/')
def weather_inquery():
return "Weather Page"
if __name__ == "__main__":
app.run()
简单介绍上述简单代码
- import Flask class
- create an instance as
app不是特别清楚为什么要用
__name__暂时记下 - 使用
route()告诉Flask什么样的URL调用这个函数 - 对函数进行命名,同时也可以用来生成特定的URL,并返回需要放松到客户端的信息
运行
export FLASK_APP=hello.py
flask run
运行出问题怎么办?
我的简单程序正常运行,若出现问题,教程给了一些指南,记录下以供后期使用
Debug Mode
flask在本地启动server, 每次修改代码后都要重新启动,这是非常麻烦的。可以启用debug模式,这样server会自己加载变动的代码,同时出现错误的话会提供有用的debugger.
export FLASK_DEBUG=1
Routing
route()用来函数和URL绑定。
Variable Rules
<variable_name>作为参数被传递到函数中;同时可以用converter来明确变量规则
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_id
converter 包括:string, int, float, path, any, uuid
Unique URLs / Redirection Behavior
Flask URL规则基于Werkzeug's routing module, 主要目的是保证URLs美观、唯一。
比如下述两条规则:
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
看起来非常类似,区别在于末尾是否有斜线。前者某尾有斜线,类似于文件系统中的文件夹;如果访问时没有的话Flask会自动定向到由斜线的URL。
后者某位没有斜线,有点类似于UNIX类的系统里稳健的路径名。如果访问时带着斜线会导致404错误。
这种方式可以确保即使斜线缺失的时候URLs也能顺利访问;同时URLs是唯一的,搜索引擎不需要index同一个页面两次。
URL Building
Flask可以生成URLs - 使用url_for()函数。示例:
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index(): pass
@app.route('/login')
def login(): pass
@app.route('/user/<username>')
def profile(username): pass
with app.text_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('login', next='/'))
print(url_for('profile', username='John Doe'))
为什么不把URL写到templates里面,而是通过url_for()生成?有以下几个原因:
- Reversing is often more descriptive than hard-coding the URLs. More importantly, it allows you to change URLs in one go, without having to remember to change URLs all over the place.
- URL building will handle escaping of special characters and Unicode data transparently for you, so you don’t have to deal with them.
- If your application is placed outside the URL root - say, in /myapplication instead of / - url_for() will handle that properly for you.
HTTP Methods
route()默认只能够对GET请求作出响应。对其他请求,可以增加methods参数。
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
教程中队HTTP的方法给了简要介绍;我之前只初步了解
GET和POST, 在此将其它方法总结下
- GET
- POST 注意server保证数据仅进行一次储存
- HEAD 客户端向server索取headers信息,不需要页面内容。flask中完全不需要考虑这块,内置的Werkzeug library会自动处理。
- PUT 与POST蕾丝但是server可能会多次触发存储程序,通过对原始值进行覆盖。为什么要多次触发?比如传输过程中网络中断时,服务器能够安全接收到请求。
- DELETE 删除信息
- OPTIONS 客户端通过这个了解URL支持哪些方法;从Flask 0.6开始自动实施。
Static Files
动态的应用也需要静态的文件,一般是CSS或者JS文件。
url_for('static', filename='style.css')
Rendering templates
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
** example of Jinja2 template
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}
模版在有inheritance时格外有用 - 可以保留页面上一些原始(比如header,页脚,导航等。
还有些关于automatic excapling,
Markupclass内容暂不记笔记;
Accessing request data
Change Logs
2017.02.11 Initial Draft