第一步先建一個virtualenv。
由于我的機(jī)器是有多版本的python,所有我要進(jìn)入到相應(yīng)的virtrualenv的目錄下面去,建立env環(huán)境。
cd c:\Python36\Scripts
virtualenv.exe D:\virtualenv\Flask
D:\virtualenv\Flask\Scripts\activate.bat
在virtualenv中安裝Flask模塊
pip install Flask
使用pycharm創(chuàng)建一個Flask項(xiàng)目
使用pycharm創(chuàng)建Flask項(xiàng)目非常簡單,如圖操作:
Paste_Image.png
完成之后就是如圖所示
Paste_Image.png
進(jìn)入Debug模式
app.run(debug=True)
debug模式可以在不重啟服務(wù)的情況下對頁面進(jìn)行調(diào)試,靜態(tài)頁面開發(fā)的時候應(yīng)該會經(jīng)常用到
導(dǎo)入模板
from flask import Flask,render_template
@app.route('/')
def hello_world():
return render_template('index.html',title='<h1>Welcome!</h1>')
這樣就可以指向模板了,之后title作為向模板傳遞的參數(shù)
添加兩個頁面,且在主頁中添加超鏈接
demo01.py
@app.route('/services')
def services():
return 'Services'
@app.route('/about')
def about():
return 'About'
index.html
<body>
<h1>{{ title }}</h1>
<a href="{{ url_for('.services') }}">services</a>
<a href="{{ url_for('.about') }}">about</a>
</body>
路由器轉(zhuǎn)換器
@app.route('/user/<int:user_id>')
def user(user_id):
return 'User %d' % user_id
int -整型
float-浮點(diǎn)數(shù)
path-路徑
仔細(xì)觀察以下代碼,F(xiàn)lask設(shè)計(jì)很友好
@app.route('/projects/')
@app.route('/our-work/')
def projects():
return 'The projects page'
官方解釋是這個:
規(guī)范的 URL 指向 projects 尾端有一個斜線。 這種感覺很像在文件系統(tǒng)中的文件夾。訪問一個結(jié)尾不帶斜線的 URL 會被 Flask 重定向到帶斜線的規(guī)范URL去。
當(dāng)用戶訪問頁面時忘記結(jié)尾斜線時,這個行為允許關(guān)聯(lián)的 URL 繼續(xù)工作, 并且與 Apache 和其它的服務(wù)器的行為一致。另外,URL 會保持唯一,有助于避免搜索引擎索引同一個頁面兩次。
故在項(xiàng)目中都采用帶'/'模式。
為什么構(gòu)建 URLs 而不是在模版中硬編碼?
這里有三個好的理由:
反向構(gòu)建通常比硬編碼更具備描述性。更重要的是,它允許你一次性修改 URL, 而不是到處找 URL 修改。
構(gòu)建 URL 能夠顯式地處理特殊字符和 Unicode 轉(zhuǎn)義,因此你不必去處理這些。
如果你的應(yīng)用不在 URL 根目錄下(比如,在 /myapplication而不在 /), url_for()將會適當(dāng)?shù)靥婺闾幚砗谩?/p>
Flask 請求上下文與響應(yīng)make_response
make_response可以定制response的高級內(nèi)容,例如cookie
from flask import make_response
@app.route('/')
def hello_world():
response = make_response(render_template('index.html', title='Welcome!'))
response.set_cookie('username','')
return response
Flask-Script,livereload模塊使用
Flask-Script 項(xiàng)目重構(gòu)的時候經(jīng)常用到
livereload 沒啥用,就是寫靜態(tài)文件的時候方便一點(diǎn),自動刷新,不過好像要加一個chrome插件,沒配成功,懶得弄。