路由
- 要給 URL 添加變量部分,你可以把這些特殊的字段標(biāo)記為
<variable_name>
, 這個(gè)部分將會(huì)作為命名參數(shù)傳遞到你的函數(shù)蓄愁。規(guī)則可以用<converter:variable_name>
指定一個(gè)可選的轉(zhuǎn)換器
關(guān)鍵字 | 解釋 |
---|---|
int | 接受整數(shù) |
float | 同 int 双炕,但是接受浮點(diǎn)數(shù) |
path | 和默認(rèn)的相似,但也接受斜線 |
@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
- 唯一 URL / 重定向行為
待補(bǔ)充 / Werkzeug 文檔
Flask 的 URL 規(guī)則基于 Werkzeug 的路由模塊
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
- 構(gòu)造 URL
以下例子就不用語(yǔ)言敘述了
>>> 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
...
print url_for('index')
print url_for('login')
print url_for('login', next='/')
print url_for('profile', username='John Doe')
...
/
/login
/login?next=/
/user/John%20Doe
- HTTP 方法
關(guān)鍵字 | 作用 | 常用 |
---|---|---|
GET | 瀏覽器告知服務(wù)器:只 獲取 頁(yè)面上的信息并發(fā)給我撮抓。這是最常用的方法 | √ |
HEAD | 瀏覽器告訴服務(wù)器:欲獲取信息妇斤,但是只關(guān)心 消息頭 。應(yīng)用應(yīng)像處理 GET 請(qǐng)求一樣來(lái)處理它胀滚,但是不分發(fā)實(shí)際內(nèi)容趟济。在 Flask 中你完全無(wú)需 人工 干預(yù),底層的 Werkzeug 庫(kù)已經(jīng)替你打點(diǎn)好了咽笼。 | |
POST | 瀏覽器告訴服務(wù)器:想在 URL 上 發(fā)布 新信息顷编。并且,服務(wù)器必須確保 數(shù)據(jù)已存儲(chǔ)且僅存儲(chǔ)一次剑刑。這是 HTML 表單通常發(fā)送數(shù)據(jù)到服務(wù)器的方法媳纬。 | √ |
PUT | 類似 POST 但是服務(wù)器可能觸發(fā)了存儲(chǔ)過(guò)程多次,多次覆蓋掉舊值施掏。你可 能會(huì)問(wèn)這有什么用钮惠,當(dāng)然這是有原因的∑甙牛考慮到傳輸中連接可能會(huì)丟失素挽,在 這種 情況下瀏覽器和服務(wù)器之間的系統(tǒng)可能安全地第二次接收請(qǐng)求,而 不破壞其它東西狸驳。因?yàn)?POST 它只觸發(fā)一次预明,所以用 POST 是不可能的。 | |
DELETE | 刪除給定位置的信息耙箍。 | |
OPTIONS | 給客戶端提供一個(gè)敏捷的途徑來(lái)弄清這個(gè) URL 支持哪些 HTTP 方法撰糠。 從 Flask 0.6 開(kāi)始,實(shí)現(xiàn)了自動(dòng)處理辩昆。 |
# 默認(rèn) method 為 get
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()
靜態(tài)文件(static)
也就是 web 里常用的 CSS/ JavaScript
文件, Flask默認(rèn)配置路徑為/static
可以通過(guò) url_for('static', filename='style.css')
來(lái)獲取靜態(tài)文件的路徑
模版渲染
Flask
使用 Jinja2
模板引擎, 默認(rèn)模板路徑為/templates
Jinja2文檔
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
請(qǐng)求數(shù)據(jù)
- request
# 想使用該對(duì)象,需要從 flask 模塊中導(dǎo)入
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
# 訪問(wèn) form 屬性中的不存在的鍵會(huì)發(fā)生什么阅酪?會(huì)拋出一個(gè)特殊的 `KeyError` 異常
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
return render_template('login.html', error=error)
# 獲取 url 上的參數(shù)( GET ) 類似于 `?key=value`
# 如果訪問(wèn)不存在的 key 也會(huì)拋出`KeyError`, 建議 catch
searchword = request.args.get('q', '')
- upload file
from flask import request
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('存在文件的路徑')
...
# 你可以訪問(wèn) filename 屬性知道上傳前文件在客戶端的文件名
# 但請(qǐng)記住, 永遠(yuǎn)不要信任這個(gè)值汁针,這個(gè)值是可以偽造的术辐。如果你要把文件按客戶端提供的 文件名存儲(chǔ)在服務(wù)器上,那么請(qǐng)把它傳遞給 Werkzeug 提供的 secure_filename() 函數(shù):
from flask import request
from werkzeug import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
...
- cookie
cookie 結(jié)構(gòu)為 dict, 取不存在的 key 會(huì)產(chǎn)生 keyError 異常
from flask import request
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
# 存
resp.set_cookie('username', 'the username')
# 取
username = request.cookies.get('username')
return resp
重定向&錯(cuò)誤
from flask import abort, redirect, url_for, render_template
@app.route('/')
def index():
# 重定向到 login 函數(shù)
return redirect(url_for('login'))
@app.route('/login')
def login():
pass
@app.route('error')
def error():
# 404
abort(404)
# this_is_never_executed
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
response
from flask import make_response
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
# 包裝的響應(yīng)對(duì)象
return resp
session
暫無(wú)
logging
相關(guān)文檔-> logging 文檔
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')