ge请求和post请求
### get请求和post请求:
1. get请求:
* 使用场景:如果只对服务器获取数据,并没有对服务器产生任何影响,那么这时候使用get请求。
* 传参:get请求传参是放在url中,并且是通过`?`的形式来指定key和value的。
2. post请求:
* 使用场景:如果要对服务器产生影响,那么使用post请求。
* 传参:post请求传参不是放在url中,是通过`form data`的形式发送给服务器的。
主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(): # arguments q = request.args.get('q') return "用户提交的查询参数是:%s" % q # 默认的视图函数,只能采用get请求 # 如果你想采用post请求,那么要写明 @app.route('/login/',methods=['GET','POST']) def login(): 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(debug=True)
index.html文件代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <a href="{{ url_for('search',q='hellohhh') }}">跳转到搜索页面</a> </body> </html>
login.html文件代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="{{ url_for('login') }}" method="post"> <table> <tbody> <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> </tbody> </table> </form> </body> </html>
浏览器操作;
终端输出:
### get和post请求获取参数:
1. get请求是通过`flask.request.args`来获取。
2. post请求是通过`flask.request.form`来获取。
3. post请求在模板中要注意几点:
* input标签中,要写name来标识这个value的key,方便后台获取。
* 在写form表单的时候,要指定`method='post'`,并且要指定`action='/login/'`。
4. 示例代码:
```
<form action="{{ url_for('login') }}" method="post">
<table>
<tbody>
<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>
</tbody>
</table>
</form>
```