Flask中的request是一個公共變量,須要導入requesthtml
from flask import Flask,request
@app.route("/req") def req(): print(request.method) #獲取訪問方式 GET print(request.url) #獲取url http://127.0.0.1:5000/req?id=1&name=wl print(request.cookies) #獲取cookies {} print(request.path) # 獲取訪問路徑 /req print(request.args) #獲取url傳過來的值 ImmutableMultiDict([('id', '1'), ('name', 'wl')]) print(request.args.get("id")) #get獲取id 1 print(request.args["name"]) # 索引獲取name wl print(request.args.to_dict()) # 獲取到一個字典 {'id': '1', 'name': 'wl'} return "Hello"
前端代碼前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> <input type="text" name="username"> <input type="password" name="pwd"> <input type="submit" value="登錄"> </form> </body> </html>
後端接收到的參數json
@app.route("/login",methods=["POST","GET"]) def login(): print(request.form) # 格式 ImmutableMultiDict([('username', '123'), ('pwd', '123')]) print(request.form.to_dict()) # 格式 {'username': '123', 'pwd': '123'} return render_template("login.html")
request.files :接收文件flask
<!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"> <br> <input type="password" name="pwd"> <br> <input type="file" name="my_file"> <br> <input type="submit" value="登錄"> </form> </body> </html>
上傳文件並保存後端
@app.route("/login", methods=["POST", "GET"]) def login(): # print(request.form) # 格式 ImmutableMultiDict([('username', '123'), ('pwd', '123')]) # print(request.form.to_dict()) # 格式 {'username': '123', 'pwd': '123'} my_file = request.files.get("my_file") # 格式 ImmutableMultiDict([('my_file', <FileStorage: 'Chrysanthemum.jpg' ('image/jpeg')>)]) file_path = os.path.join("static", "1.jpg") my_file.save(file_path) return render_template("login.html")
@app.route("/login", methods=["POST", "GET"]) def login(): print(request.data) # 存放的是請求體中的原始信息 Content-Type:沒法識別的類型 print(request.json) # 請求頭中存在 Content-Type:application/json 將請求體中的數據 存放在JSON中 print(request.values) # CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([('username', '123'), ('pwd', '123'), ('my_file', '')])]) print(request.values.to_dict()) # 這是個坑!!!{'username': '123', 'pwd': '123', 'my_file': ''} return render_template("login.html")