十七、get和post请求
2018-10-08 本文已影响11人
十柒年
1.get请求
1.1概念
- 使用场景:如果只对服务器获取数据,并没有对服务器产生任何影响,这时候使用get请求
- 传参:get请求传参是放在url中,并且是以‘?’的形式来指定key和value的。
1.2使用
先来看一段代码。这是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>
这是python
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search/')
def search():
q = request.args.get('q')
return '用户提交的参数是%s' % q
在这里由首页跳转到搜索页面,并且在路径及传递一个参数q,value值为hello。请求的完整路径如下。
页面展示效果如下。
![](https://img.haomeiwen.com/i6375263/766377890d2d2eef.png)
2.post请求
2.1概念
- 使用场景:如果要对服务器产生影响,那么使用post请求
- 传参:post请求传参不是放在url中,是通过form data 的形式发送给服务器的。
2.2使用
先看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" name="username" placeholder="请输入用户名"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" placeholder="请输入密码"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
效果图如下。
![](https://img.haomeiwen.com/i6375263/2ec479df19502cae.png)
app.py代码如下。
# 默认的视图函数 只能采用get请求
# 如果想要使用post请求 则必须指明是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)
print(password)
return 'post request'
注意:
input标签中,要写name来标识这个value的key,方便后台获取
在写form表单的时候,要指定method=‘post’并且要指定action="{{ url_for('login') }}"
study hard and make progress every day.
更多学习资料请关注"爱游戏爱编程"。
爱游戏爱编程.jpg