1. 程式人生 > >Flask路由和HTTP請求方式處理

Flask路由和HTTP請求方式處理

路由

使用route()裝飾器將函式繫結到URL。

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

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

您也可以將URL的一部分動態化並將多個規則附加到函式

變數規則

您可以通過使用標記部分向URL新增變數部分 <variable_name>。然後,您的函式將接收<variable_name> 作為關鍵字引數。或者,您可以使用轉換器指定引數的型別<converter:variable_name>

@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

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

轉換器型別:

型別 說明
string (預設值)接受任何沒有斜槓的文字
int 接受正整數
float 接受正浮點值
path 可接受字串或者帶斜槓的文字
uuid 接受UUID字串

URL構建

路由生成:{{ url_for(“模組名.檢視名”) }}
url重定向: redirect(‘/home/login’)
redirect(url_for(“home.home_login”))

HTTP方法

預設情況下,路由僅響應get請求,可以使用route()裝飾器中methods引數來處理不同的HTTP方法

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()