flask中的get請求和post請求
get請求
1. 使用場景:如果只對服務器獲取數據,並沒有對服務器產生任何影響,這個時候使用get請求
2. 傳參:get請求傳參是放在url中,並且是通過?的形式指定key和value
post請求
- 使用場景:如果要對服務器產生影響,則使用post請求;點擊登錄按鈕也會對服務器產生影響,因爲服務器要記錄登錄記錄,所以屬於post請求
- 傳參:post請求傳參不是放在url中,是通過 form data的形式傳遞給服務器
get和post請求獲取參數
- get請求是通過flask.request.args來獲取參數
- post請求時通過flask.request.form來獲取
- post請求在模版中要注意幾點
- input標籤中,要寫name來標識這個value的key,方便後臺獲取
- 在寫form表單的時候,要指定method=post,並且要指定action=‘/login/’
<form action="{{ url_for('login') }}" method="post">
4.示例代碼
*登陸界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<form action="{{ url_for('login') }}" method="post">
<table>
<tr>
<td>用戶名:</td>
<td><input type="text" placeholder="輸入用戶名" name="username"></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="text" placeholder="輸入密碼" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登錄"></td>
</tr>
</table>
</form>
</body>
</html>
*首頁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<a href="{{ url_for('search',q='hello') }}">首頁</a>
</body>
</html>
*主app文件
from flask import Flask,render_template,request
app = Flask(__name__)
#首頁
@app.route('/')
def index():
return render_template('index.html')
#查詢
@app.route('/search/')
def search():
q=request.args.get('q')
return '用戶提交的查詢參數是:%s'%q
#默認的視圖函數只能使用get請求
#如果需要採用post請求,那麼需要寫明
#登錄
@app.route('/login/',methods=['GET','POST'])
def login():
#判斷是get請求,怎返回視圖,若是post請求,怎獲取用戶名密碼
if request.method=='GET':
return render_template('login.html')
else:
username=request.form.get('username')
password=request.form.get('password')
print('username:',username)
print('password:',password)
return 'post request'
if __name__ == '__main__':
app.run()