Flask模板渲染與Get和Post請求詳細介紹
模板渲染
所謂模板渲染就是讓flask渲染一個html文檔,比如你有一個html文件,想要在網站上加載出來,你就要渲染它。
首先把這個文件,叫做模板渲染.html,放在templates文件夾下面,

然后代碼中,導入render_template類
from flask import Flask,render_template
另外也可以修改模板文件的渲染路徑,使用template_folder來修改
app = Flask(__name__,template_folder='../fdf')
這里我們不修改。
模板渲染.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>模板渲染</title>
</head>
<body>
<p>你好</p>
<h3>How are you</h3>
</body>
</html>

模板渲染.py:
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('模板渲染.html')
if __name__ == '__main__':
app.run()
運行這個flask項目,在根路徑下/,執(zhí)行對應的視圖函數(shù),渲染對應的html文件,顯示如下:

GET和POST請求
在設置路由的時候,可以設置訪問url的時候,接受的請求方式。
GET請求表示瀏覽器需要get某一個文件,服務器就把這個url對應的資源發(fā)給瀏覽器,默認情況下,我們輸入url地址,就是在使用GET請求的方式請求資源。比如:
@app.route('/',methods=["GET"])
def index():
return render_template('模板渲染.html')
methods=["GET"]限定訪問方式,不寫,默認就是GET方式。
表示在訪問根路徑/時,只接受get方式的請求,那我們輸入url,按回車就是get方式,是可以訪問的。

如果修改成:@app.route('/',methods=["POST"])
當我們點擊這個鏈接后:

就會發(fā)現(xiàn):

這就是因為我們限制了根路徑/的訪問只能用POST,當然也可以修改為GET,POST都可以的形式
@app.route('/',methods=["GET","POST"])POST請求,表示的是我現(xiàn)在不是要獲取某個資源,而是我有數(shù)據需要提交給服務器,讓服務器來處理。
首先,我們的html頁面為,這里有一個表單,需要我們填寫數(shù)據,然后我們把數(shù)據交給服務器來處理,設置表單的action="http://localhost:5000/datahandle",也就意味著數(shù)據提交到/datahandle這個頁面來處理
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>post請求</title>
</head>
<body>
<form action = "http://localhost:5000/datahandle" method = "post">
<table>
<tr>
<td>Name</td>
<td><input type ="text" name ="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type ="password" name ="password"></td>
</tr>
<tr>
<td><input type = "submit"></td>
</tr>
</table>
</form>
</form>
</body>
</html>
然后是py文件,
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('test.html')
#post數(shù)據到這個頁面來處理,直接輸入url是get方式訪問,訪問不了,這里限定了只能用POST方式訪問
@app.route('/datahandle',methods=["POST"])
def handle():
#獲取提交到的數(shù)據
name = request.form['username']
pwd = request.form['password']
return f'name: {name}, password: {pwd}'
if __name__ == '__main__':
app.run()進入到根路徑后會渲染模板文件test.html,然后在表單中輸入name,password后,提交給/datahandle頁面來處理,它對應的視圖函數(shù)handle()處理數(shù)據。但是這里涉及到如何拿到表單中的數(shù)據,需要使用request類
from flask import Flask,render_template,request name = request.form['username'] pwd = request.form['password']
實際上,在form表單中輸入的數(shù)據都被flask以字典的形式存儲起來了,使用print(request.form)可以查看
表單中輸入以下數(shù)據:提交,

在控制臺中輸出ImmutableMultiDict([('username', '123'), ('password', '456')])
鍵值對username='123',password = '456'
然后使用request.form['username']拿到key對應的value,或者使用request.form.get('username')一樣可以拿到數(shù)據。
提交后頁面跳轉到了/datahandle中,處理完的數(shù)據返回出來:

成功的拿到了post方式提交的數(shù)據。
到此這篇關于Flask模板渲染與Get和Post請求詳細介紹的文章就介紹到這了,更多相關Flask模板渲染內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

