• Flask——Request(1)


    请求方式
    Flask默认是GET请求

    如果我们在一个页面中即需要GET请求又需要POST请求那么我们需要重写methods方法:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form action="" method="post">
        用户名:<input type="text">
        密码:<input type="password">
        <input type="submit" value="登录">
    </form>
    </body>
    </html>
    from flask import Flask,render_template
    app = Flask(__name__)
    
    @app.route('/login',methods=["POST","GET"])  # 重写methods方法
    def login():
        return render_template("login.html")
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    request.method
    Flask 的 request 中给我们提供了一个 method 属性里面保存的就是前端的请求的方式

    from flask import Flask,render_template,request
    app = Flask(__name__)
    
    @app.route('/login',methods=["POST","GET"])
    def login():
        # 获取前端的请求的方式
        print(request.method)
        return render_template("login.html")
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    request.form
    获取请求数据

    from flask import Flask,render_template,request
    app = Flask(__name__)
    
    @app.route('/login',methods=["POST","GET"])
    def login():
        if request.method == "GET":
            return render_template("login.html")
        if request.method == "POST":
            # 获取form表单提交的数据
            print(request.form) # ImmutableMultiDict([('username', 'henry'), ('password', '123456')])
            return "200 ok"
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    通过reqeust.form属性做登录验证

    from flask import Flask,render_template,request
    app = Flask(__name__)
    
    @app.route('/login',methods=["POST","GET"])
    def login():
        if request.method == "GET":
            return render_template("login.html")
        if request.method == "POST":
            # 获取form表单提交的数据
            print(request.form) # ImmutableMultiDict([('username', 'henry'), ('password', '123456')])
            username = request.form.get("username")
            password = request.form.get("password")
            if username == "henry" and password == "123456":
                return "200 ok"
            else:
                return "404"
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)
  • 相关阅读:
    BestCoder Round #87 1001
    p1304 家族
    hdu 1003
    hdu 1231
    hdu 1232 畅通工程
    hdu 4107
    Robot Framework--用例、数据、流程分离例子
    Robot Framework--RIDE面板与库的说明
    Robot Framework--pybot命令
    Robot Framework--运行pybot时出错
  • 原文地址:https://www.cnblogs.com/yongyuandishen/p/14905198.html
Copyright © 2020-2023  润新知