Flask-get请求和post请求

1.get请求:
	使用场景->如果只对服务器获取数据,并没有对服务器产生任何影响,那么这时候使用get请求
	传参:get请求传参是放在url中,并且是通过?的形式来指定key和value的
2.post请求:
	使用场景->如果要对服务器产生影响,那么使用post请求
	传参:post请求传参不是放在url中,是通过form data的形式进行传参的

3.get和post请求获取参数:
	1.get请求是通过flask.request.args来获取
	2.post请求是通过flask.request.form来获取
	3.post请求在模板中要注意几点:
		input标签中,要写name来标识这个value的key方便后台获取
		在写form表单的时候要指定 method=post 并且要指定 action=视图函数

login.html

<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>

app.py

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':'hello',
    #     'a':'world'
    # }
    q = request.args.get('q')
    return '用户提交过来的查询参数是:{}'.format(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:{}".format(username))
        print("password:{}".format(password))
        return 'post request'

if __name__ == '__main__':
    app.run(debug=True)

猜你喜欢

转载自blog.csdn.net/qq_42991834/article/details/89708880