【Flask】Request

Request method

Flask default GET request

That is, if we need to GET requests a page, they need to POST requests so we need to override methods method:

Copy the code
<!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>
Copy the code
Copy the code
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)
Copy the code

Other methods

Flask in the request provides us with many attributes, simply import request directly call the corresponding attribute you can see the effect directly

request.method

Flask in the request provides us with a method to save the property which is to ask the front way

Copy the code
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)
Copy the code

request.form

Data acquisition request

Copy the code
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)
Copy the code

Do login authentication by reqeust.form property

Copy the code
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)
Copy the code

Note: ImmutableMultiDict types of data and python in our dictionary usage is the same

We can to_dict () method converts this data type to the above python in our dictionary as follows

Copy the code
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.to_dict())  # {'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)
Copy the code

We take the value of the dictionary get method used to prevent the error

request.headers

Acquiring data request header

Copy the code
print(request.headers)
#Host: 192.168.16.42:9876 #Connection: keep-alive #Content-Length: 27 #Cache-Control: max-age=0 #Origin: http://192.168.16.42:9876 #Upgrade-Insecure-Requests: 1 #Content-Type: application/x-www-form-urlencoded #User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36 #Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 #Referer: http://192.168.16.42:9876/login #Accept-Encoding: gzip, deflate #Accept-Language: zh-CN,zh;q=0.9
Copy the code

request.args

Get url parameters GET request

Copy the code
Print (request.args) 

# ImmutableMultiDict ([( 'name', 'Henry'), ( 'Age', '18 is')]) 

# () method of converting into a dictionary by to_dict 
print (request.args.to_dict ()) 

# { 'name': 'henry ', 'age': '18'}
Copy the code

request.files

upload files

 Front page

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <input type="file" name="my_file">
    <input type="submit" value="登录">
</form>
</body>
</html>
Copy the code

Back-end code

Copy the code
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":
        username = request.form.get("username")
        password = request.form.get("password")
        if username == "henry" and password == "123456":
            print(request.files) # ImmutableMultiDict([('my_file', <FileStorage: 'click点击事件.gif' ('image/gif')>)])
            files = request.files.get("my_file") # files是FileStorage类型 注意:It is not a file handle 
            print (files.filename) # click click event .gif [file name]

            return "200 ok"
            files.save (files.filename) # FileStorage call the Save method to save the type of 
        the else: 
            return "404" 

IF the __name__ == '__main__': 
    app.run ( "0.0.0.0", 9876)
Copy the code
1
fp  =  os.path.join( "templates" ,files.filename)   # 通过os模块指定保存路径

request of other properties

Copy the code
print (request.url) # get the full access path 
print (request.path) # routing address / the Login 
Print (request.values) # parameters in the URL can be obtained can also obtain data FormData in 

print (request.args.get ( "id")) # get parameters in the URL of the 
print (request.args [ "id"] ) # get parameters in the URL 
conversion print (request.args.to_dict ()) # get parameters in the URL into a dictionary 

print (request .environ) # original information acquisition request 
print (request.base_url) # Get URL header does not include the parameter
Copy the code

Two special attributes

print (request.json) # request header Content-type: application / json serialization data request.json 
Print (request.data) # Content-type header of the request does not include Form or data

Guess you like

Origin www.cnblogs.com/youxiu123/p/11605772.html