Flask介紹
Flask是一個使用 Python 編寫的輕量級 Web 應用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎則使用 Jinja2。
Flask也被成為『微框架』。因為它使用簡單的核心,用 extension 增加其他功能。Flask沒有默認使用的數(shù)據(jù)庫、窗體驗證工具。
它的官方地址:http://flask.pocoo.org
簡單的Hello world
在一個python文件hello.py中鍵入以下代碼:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
執(zhí)行命令
python hello.py
運行結果

在瀏覽器訪問 http://127.0.0.1:5000
顯示如下

more
路由配置
flask的路由是由route()裝飾器把一個函數(shù)綁定到一個URL實現(xiàn)的。
下面是一些基本的例子:
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
當然一個web框架的路由肯定不可能只做到這些簡單固定的路由,flask自己可以定義一些規(guī)則。
變量規(guī)則
通過把 URL 的一部分標記為 <variable_name> 就可以在 URL 中添加變量。標記的 部分會作為關鍵字參數(shù)傳遞給函數(shù)。通過使用 <converter:variable_name> ,可以 選擇性的加上一個轉換器,為變量指定規(guī)則。請看下面的例子:
@app.route('/user/<username>')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id
現(xiàn)有的轉換器有:
| int | float | path |
|---|---|---|
| 接受整數(shù) | 接受浮點數(shù) | 和缺省情況相同,但也接受斜杠 |
簡單介紹到這里,更多規(guī)則可以看官方文檔,地址是 http://werkzeug.pocoo.org/docs/0.11/routing/
渲染模板
在Python內(nèi)部生成HTML不好玩,且相當笨拙。因為你必須自己負責HTML轉義,以確保應用的安全。因此, Flask自動為你配置的 Jinja2 模板引擎,就像Java語言里最簡單的模板JSP一樣。
Flask使用render_template()方法渲染模板,我們要做的只要提供模板名稱和需要的參數(shù)或者說變量就行了。
舉個栗子:
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
Flask一般會在templates文件夾內(nèi)尋找名稱對應的模板文件。
接下來就要看看Jinja2模板的威力了,就像使用Java語言或者PHP里的html模板標簽語言。
舉個簡單使用Jinja2模板的栗子:(hello.html)
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello World!</h1>
{% endif %}
是不是很像PHP?哈哈,以前用過PHP或者JSTL的,這模板已經(jīng)是簡單得不能再簡單。
在模板內(nèi)部你也可以訪問 request 、session 和 g 對象,以及 get_flashed_messages() 函數(shù)。
這幾個對象和函數(shù)都可以在官方API文檔中查找得到,這里不細說。
總結
Flask真的是一個超快速開發(fā)web的框架,配合bootstrap使用快到?jīng)]朋友。Flask官方文檔中的quick start已經(jīng)能覆蓋到我的功能需求,非常容易學。我經(jīng)常用它來做一些數(shù)據(jù)項目的前端展示或者一些數(shù)據(jù)檢索展示,但如果要做一個大型網(wǎng)站的話,這個框架恐怕不太適合,目前我還沒看到它的一些關于并發(fā)的支持。做大型網(wǎng)站我還是會選擇傳統(tǒng)的Java語言,因為比較容易找到人手。