Flask自學筆記 (5):Flask的各種語法功能介紹

路由

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'

從網址列取得變數

from markupsafe import escape

@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % escape(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

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

可接受的變數:

string (默認)接受不帶斜杠的任何文本
int 接受正整數
float 接受正浮點值
path 喜歡string 但也接受斜線
uuid 接受UUID字符串
@app.route('/')
def index():
    return 'hello man'


@app.route('/user/<username>')
def username(username):
    return 'i am ' + username


@app.route('/age/<int:age>')
def userage(age):
    return 'i am ' + str(age) + 'years old'

唯一URL

以下兩個規則在使用後斜杠時有所不同。

@app.route('/projects/')
def projects():
    return 'The project page'

@app.route('/about')
def about():
    return 'The about page'

projects 端點的規範URL帶有斜杠。它類似於文件系統中的文件夾。如果您訪問的URL不帶斜杠,Flask會將您重定向到帶斜杠的規範URL。

about 端點的規範URL不帶斜杠。它類似於文件的路徑名。使用斜杠訪問URL會產生404“未找到”錯誤。這有助於使這些資源的URL保持唯一,從而有助於搜索引擎避免對同一頁面進行兩次索引。

url_for

如果路由寫定,一但路由有所變更,那就必需對所有的專案開始全部重新修正路由,在Flask有個方式可以避免這個問題,就是透過 url_for ,這是Flask內建的函數,可以從Flask直接導入。

from flask import url_for

@app.route('/a')
def url_for_a():
    return 'here is a'

@app.route('/b')
def b():
    #  所得結果為'/a'
    return url_for('url_for_a')

在return的部份只要透過redirect 搭配url_for ,就可以將使用者重新導向到另一個路由去。那就可以避免掉調整路由之後整個專案都要去調整的問題了!

@app.route('/a')
def url_for_a():
    return 'here is a'

@app.route('/b')
def b():
    #  會將使用者引導到'/a'這個路由
    return redirect(url_for('url_for_a'))

另一個範例:

from flask import Flask, url_for
from markupsafe import escape

app = Flask(__name__)

@app.route('/')
def index():
    return 'index'

@app.route('/login')
def login():
    return 'login'

@app.route('/user/<username>')
def profile(username):
    return '{}\'s profile'.format(escape(username))

with app.test_request_context():
    print(url_for('index'))
    print(url_for('login'))
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

在這裡我們使用該test_request_context()方法進行嘗試url_for()test_request_context() 告訴Flask即使在使用Python Shell時也表現得好像在處理請求一樣。

執行結果:

/
/login
/login?next=/
/user/John%20Doe

HTTP方法

預設的HTTP方法為 GET

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

靜態文件

在Flask中,預設static資料夾為靜態文件資料夾,你可以把css, js, img等檔案放入到這個資料夾中。些文件遵循目錄結構為static/filename.css的檔案名稱。

模板

要渲染模板,您可以使用render_template() 方法。您所要做的就是提供模板的名稱以及要作為關鍵字參數傳遞給模板引擎的變量。這是有關如何渲染模板的簡單示範:

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

要將模板放在 templates 資料夾內。

hello.html 的範例內容請參考以下範例:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

重定向和錯誤

要將用戶重定向到另一個端點,請使用redirect() 函數;要使用錯誤代碼提前中止請求,請使用以下 abort()功能:

from flask import abort, redirect, url_for

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    abort(401)
    this_is_never_executed()

默認情況下,每個錯誤代碼都會顯示一個黑白錯誤頁面。如果要自定義錯誤頁面,可以使用 errorhandler()裝飾器:

from flask import render_template

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

Cookie

讀取Cookie:

from flask import request

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.

寫入Cookie:

from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

Request物件

from flask import request

通過使用該method屬性,可以使用當前的請求方法 。要訪問表單數據(在POSTPUT 請求中傳輸的數據),可以使用 form屬性。這是上述兩個屬性的完整示範:

@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)