路由
- 要給 URL 添加變量部分,你可以把這些特殊的字段標記為
<variable_name>
, 這個部分將會作為命名參數傳遞到你的函數。規則可以用<converter:variable_name>
指定一個可選的轉換器
關鍵字 | 解釋 |
---|---|
int | 接受整數 |
float | 同 int ,但是接受浮點數 |
path | 和默認的相似,但也接受斜線 |
@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 / 重定向行為
待補充 / Werkzeug 文檔
Flask 的 URL 規則基于 Werkzeug 的路由模塊
@app.route('/projects/')
def projects():
return 'The project page'
@app.route('/about')
def about():
return 'The about page'
- 構造 URL
以下例子就不用語言敘述了
>>> 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 方法
關鍵字 | 作用 | 常用 |
---|---|---|
GET | 瀏覽器告知服務器:只 獲取 頁面上的信息并發給我。這是最常用的方法 | √ |
HEAD | 瀏覽器告訴服務器:欲獲取信息,但是只關心 消息頭 。應用應像處理 GET 請求一樣來處理它,但是不分發實際內容。在 Flask 中你完全無需 人工 干預,底層的 Werkzeug 庫已經替你打點好了。 | |
POST | 瀏覽器告訴服務器:想在 URL 上 發布 新信息。并且,服務器必須確保 數據已存儲且僅存儲一次。這是 HTML 表單通常發送數據到服務器的方法。 | √ |
PUT | 類似 POST 但是服務器可能觸發了存儲過程多次,多次覆蓋掉舊值。你可 能會問這有什么用,當然這是有原因的。考慮到傳輸中連接可能會丟失,在 這種 情況下瀏覽器和服務器之間的系統可能安全地第二次接收請求,而 不破壞其它東西。因為 POST 它只觸發一次,所以用 POST 是不可能的。 | |
DELETE | 刪除給定位置的信息。 | |
OPTIONS | 給客戶端提供一個敏捷的途徑來弄清這個 URL 支持哪些 HTTP 方法。 從 Flask 0.6 開始,實現了自動處理。 |
# 默認 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()
靜態文件(static)
也就是 web 里常用的 CSS/ JavaScript
文件, Flask默認配置路徑為/static
可以通過 url_for('static', filename='style.css')
來獲取靜態文件的路徑
模版渲染
Flask
使用 Jinja2
模板引擎, 默認模板路徑為/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)
請求數據
- request
# 想使用該對象,需要從 flask 模塊中導入
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
# 訪問 form 屬性中的不存在的鍵會發生什么?會拋出一個特殊的 `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 上的參數( GET ) 類似于 `?key=value`
# 如果訪問不存在的 key 也會拋出`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('存在文件的路徑')
...
# 你可以訪問 filename 屬性知道上傳前文件在客戶端的文件名
# 但請記住, 永遠不要信任這個值,這個值是可以偽造的。如果你要把文件按客戶端提供的 文件名存儲在服務器上,那么請把它傳遞給 Werkzeug 提供的 secure_filename() 函數:
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 結構為 dict, 取不存在的 key 會產生 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
重定向&錯誤
from flask import abort, redirect, url_for, render_template
@app.route('/')
def index():
# 重定向到 login 函數
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'
# 包裝的響應對象
return resp
session
暫無
logging
相關文檔-> logging 文檔
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')