第三篇 request篇
每個框架中都有處理請求的機制(request),但是每個框架的處理方式和機制是不同的
為了了解Flask的request中都有什麽東西,首先我們要寫一個前後端的交互
基於HTML + Flask 寫一段前後端的交互
login.html寫入
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"><title>標題</title>
</head>
<body>
<p>登錄頁面</p>
<form action="" method="post" enctype="multipart/form-data">
<span>用戶</span><input type="text" name="username">
<span>密碼</span><input type="password" name="pwd">
<span>密碼</span><input type="file" name="file"><button>登錄</button>
</form>
</body>
</html>
flask的py文件寫入
from flask import Flask, render_template, redirect, send_file, jsonify, request
app = Flask(__name__)
@app.route(‘/‘)
def index():
# return jsonify({‘name‘: "aaa", ‘age‘: 77})
# return json.dumps({‘name‘: "aaa", ‘age‘: 77})# return send_file("1.png")
return send_file("2.mp4")
# return redirect("/login") # "hello world"
@app.route(‘/login‘, methods=(‘GET‘, ‘POST‘))
def login():
# print(request.url) # http://localhost:8080/login?id=1&age=20 #url欄中所有內容所有的
# print(request.url_root) # http://localhost:8080/
# print(request.url_charset) # utf-8 請求頭獲取當前所用的格式
# print(request.url_rule) # /login 路由的路徑
# print(request.host_url) # http://localhost:8080/
# print(request.base_url) # http://localhost:8080/login
if request.method == ‘GET‘:
# print(request) # <Request ‘http://127.0.0.1:8080/login‘ [GET]>
return render_template("login.html")
if request.method == ‘POST‘:
# print(request) # <Request ‘http://127.0.0.1:8080/login‘ [POST]>
# print(request.form) # ImmutableMultiDict([(‘username‘, ‘aaa‘), (‘pwd‘, ‘111‘)]) # 存儲的是所有FormData中的所有數據
# print(request.args) # ImmutableMultiDict([(‘id‘, ‘1‘), (‘age‘, ‘20‘)]) # 存儲的是所有URL中的所有數據
# print(request.json) # None # 當Content-Type: application/json 存放在request.json中(ajax等類型的請求用這個)
# print(request.data) # b‘‘ # Content-Type不正經的無法被解析時,存放原始數據
# print(request.values)
# # CombinedMultiDict([ImmutableMultiDict([(‘id‘, ‘1‘), (‘age‘, ‘20‘)]), ImmutableMultiDict([(‘username‘, ‘aaa‘), (‘pwd‘, ‘111‘)])])
#
# print(request.values.to_dict()) # {‘username‘: ‘aaa‘, ‘pwd‘: ‘111‘, ‘id‘: ‘1‘, ‘age‘: ‘20‘} # 獲得字典
# print(request.cookies) # 獲取cookies
# print(type(request.headers)) # <class ‘werkzeug.datastructures.EnvironHeaders‘>
# print(request.headers) # 請求頭相關
print(request.files) # ImmutableMultiDict([(‘file‘, <FileStorage: ‘1.png‘ (‘image/png‘)>)])
print(request.files.get(‘file‘)) # <FileStorage: ‘1.png‘ (‘image/png‘)>
my_file = request.files["file"]
my_file.save("1.png") # 保存方法
username = request.form.get(‘username‘)
pwd = request.form.get(‘pwd‘)
if username == ‘aaa‘ and pwd == ‘111‘:
return redirect(‘/home‘)
return render_template(‘hello flask.html‘)
@app.route(‘/home‘)
def home():
return ‘登陸成功‘
app.run(host=‘0.0.0.0‘, port=8080, debug=True)
解釋一個
@app.route(‘/login‘, methods=(‘GET‘, ‘POST‘))
methods=(‘GET‘, ‘POST‘) 代表這個url地址只允許 GET POST 請求,是個列表也就是意味著可以允許多重請求方式.
1.request.method print(request.method) # POST 看來可以使用這種方式來驗證請求方式了 2.request.form print(request.form) # ImmutableMultiDict([(‘username‘, ‘aaa‘), (‘pwd‘, ‘111‘)]) # ImmutableMultiDict 它看起來像是的Dict 就用Dict的方法取值試一下吧 print(request.form["user"]) # aaa print(request.form.get("pwd")) # 111 # 看來全部才對了, ImmutableMultiDict 似乎就是個字典,再來玩一玩它 print(list(request.form.keys())) # [‘user‘, ‘pwd‘] 看來是猜對了 #如果以上所有的方法你都覺得用的不爽的話 req_dict = dict(request.form) print(req_dict) # 如果你覺得用字典更爽的話,也可以轉成字典操作(這裏有坑)
3.request.args
print(request.args) # ImmutableMultiDict([(‘id‘, ‘1‘), (‘age‘, ‘20‘)]) # 存儲的是所有URL中的所有數據
print(request.args["id"]) # 1 print(request.args.get("age")) # 20 print(list(request.args.keys())) # [‘id‘, ‘age‘] print(list(request.args.values())) # [‘1‘, ‘20‘] req_dict = dict(request.args) # {‘id‘: [‘1‘], ‘age‘: [‘20‘]} print(req_dict)
request.args 與 request.form 的區別就是:
request.args 是獲取url中的參數
request.form 是獲取form表單中的參數
4.request.values 之 只要有個參數我都要
print(request.values) # CombinedMultiDict([ImmutableMultiDict([(‘id‘, ‘1‘), (‘age‘, ‘20‘)]), ImmutableMultiDict([(‘user‘, ‘Oldboy‘), (‘pwd‘, ‘DragonFire‘)])]) print(request.values.get("id")) # 1 print(request.values["username"]) # aaa # 這回喜歡直接操作字典的小夥伴們有驚喜了! to_dict() 方法可以直接將我們的參數全部轉為字典形式 print(request.values.to_dict()) # {‘username‘: ‘aaa‘, ‘pwd‘: ‘111‘, ‘id‘: ‘1‘, ‘age‘: ‘20‘}
# 註意這裏的坑來啦!!! # 如果url和form中的Key重名的話,form中的同名的key中value會被url中的value覆蓋
5.request.cookies 之 存在瀏覽器端的字符串兒也會一起帶過來
前提是你要開啟瀏覽器的 cookies
request.cookies 是將cookies中信息讀取出來
6.request.headres 之 請求頭
print(request.cookies) # 獲取cookies
print(type(request.headers)) # <class ‘werkzeug.datastructures.EnvironHeaders‘>
print(request.headers) # 請求頭相關
"""
Host: localhost:8080
Connection: keep-alive
Content-Length: 20
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:8080
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/71.0.3578.98 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: http://localhost:8080/login?id=1&username=20
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: Pycharm-bdfc5fce=5839cb6f-fa90-425b-86dd-3ca2dd9403b5
"""
7.request.data 之 如果處理不了的就變成字符串兒存在data裏面
你一定要知道 request 是基於 mimetype 進行處理的
mimetype的類型 以及 字符串兒 : http://www.w3school.com.cn/media/media_mimeref.asp
如果不屬於上述類型的描述,request就會將無法處理的參數轉為Json存入到 data 中
其實我們可以將 request.data , json.loads 同樣可以拿到裏面的參數
8.request.files 之 給我一個文件我幫你保管
print(request.files) # ImmutableMultiDict([(‘file‘, <FileStorage: ‘1.png‘ (‘image/png‘)>)])
print(request.files.get(‘file‘)) # <FileStorage: ‘1.png‘ (‘image/png‘)>
my_file = request.files["file"]
my_file.save("1.png") #保存文件,裏面可以寫完整路徑+文件名
9. request.獲取各種路徑 之 這些方法沒必要記,但是要知道它存在
10. request.json 之 前提你得告訴是json
如果在請求中寫入了 "application/json" 使用 request.json 則返回json解析數據, 否則返回 None
第三篇 request篇