Flask 之 get和post请求

get和post请求:

  • 从两个方面入手get和post请求
  1. get请求:

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

    • 使用场景:如果要对服务器产生影响,那么使用post请求。
    • 传参: post请求传参不是放在url中,是通过form data的形式发送给服务器的。

get和post请求获取参数:

  1. get请求是通过flask.request.args来获取。
  2. post请求是通过flask.request.form来获取。
  3. post请求在模板中要注意几点:
    • input标签中, 要写那么来表示这个value的key, 方便后台获取。
    • 在写form表单的时候, 要指定method=post, 并且要指定action='/login/'
  4. 示例代码:
  • post请求示例:
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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><!DOCTYPE html>
  • get请求示例:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <a href="{{ url_for('search', q='hello') }}">跳转到搜索页面</a>
</body>
</html>
  • request接口调用方式:
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/index/')
def index():
    return render_template('index.html')

@app.route('/search/')
def search():
    # arguments
    condition = request.args.get('q')
    return '用户提交的查询参数是: {}'.format(condition)

# 默认的试图函数, 只能采用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: {}, password: {}'.format(username, password))
        return 'name = {}, password = {}'.format(username, password)


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1', port=8081)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,278评论 22 257
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,225评论 19 139
  • #网络请求中的get post 区别 一般在浏览器中输入网址访问资源都是通过GET方式;在FORM提交中,...
    gogoingmonkey阅读 1,962评论 1 11
  • 同步请求可以从因特网请求数据, 一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成, 才可以进行下一步操...
    小灬博阅读 906评论 2 4
  • 露珠是花草哭泣流的泪 黒夜的孤独我独自伤悲 还是太阳最解风情 他懂得怜香惜玉 用火辣辣的爱 吻去我腮边的泪
    泰山寒梅阅读 317评论 5 11