flask框架 路由

2021-09-22 20:14:56 字數 2570 閱讀 7011

1.利用methods限制訪問方式

render_template:返回頁面

request:一切瀏覽器請求的內容都封裝到request物件中

request.method:來判斷訪問方式

method:設定請求訪問方式

from flask import flask,render_template,request

def login():

if request.method=='post':

return '註冊成功了'

return render_template('login.html')

#同乙個路由可以裝飾多個檢視,然後按照先後順序輸出

def hello1():

return 'hello1'

def hello2():

return 'hello2'

if __name__ == '__main__':

2. 可以通過url_map屬性來檢視flask中的整體路由資訊

from flask import flask,render_template,request

def index():

return 'hello world'

if __name__ == '__main__':

"""

列印結果:

map(

[index>,

' (options, head, get) -> static>]

)

如果存在 get ,那麼也會替你自動地新增 head,無需干預。它會確保遵照 http rfc(描述 http 協議的文件)處理 head 請求,所以你可以完全忽略這部分的 http 規範。同樣,自從 flask 0.6 起, 也實現了 options 的自動處理。

你不知道乙個 http 方法是什麼?不必擔心,這裡會簡要介紹 http 方法和它們為什麼重要:

http 方法(也經常被叫做「謂詞」)告知伺服器,客戶端想對請求的頁面 做 些什麼。下面的都是非常常見的方法:

3.多個路由修飾乙個檢視

路由解析時,是從裡到外

4. 使用url_for進行反解析和重定向

from flask import flask,render_template,request,redirect,url_for

#重定向

def login2():

if request.method=='post':

#1.第一種方式:使用路由

# return redirect('/index')

#2.第二種方式:使用檢視函式名稱

url=url_for('index')

return redirect(url)

return render_template('login.html')

if __name__ == '__main__':

7. 動態路由獲取路由中傳遞的引數,路由傳遞的引數預設當做string處理

#傳遞的引數預設是字串型別

def index(num):

print(type(num))#return 'index....,num的值:%s'% num

#指定接收資料型別 int

def index2(num):

print(type(num))

return 'index2...,num的值是:%s'% num

#path :可以接受帶/的引數

def index3(num):

return 'index3..,num的是:%s'% num

if __name__ == '__main__':

Flask框架 url路由,Templates模板

python web 框架 靜態網頁 無法與伺服器做動態互動的網頁。動態網頁 允許與伺服器動態互動的網頁。網頁 html,css,js 能夠給使用者提供服務的機器就稱為 伺服器 硬體 與 軟體 硬體 一台計算機可以理解為一台伺服器 軟體 乙個能夠結束使用者請求並給出響應的程式也可理解為伺服器 apa...

flask框架路由常用定義方式總結

路由的各種定義方式 請求方式限定 使用 jzrgevmethods 引數指定可接受的請求方式,可以是多種 app.route methods jzrgev get def hello return 路由查詢方式 同一路由指向兩個不同的函式,在匹配過程中,至上而下依次匹配 app.route def ...

Flask 路由系統

反向生成url def index print index print url for n1 return index 動態路由 def index nid print url for index nid 777 print url for index nid nid 根據輸入的nid,反向生成ur...