Flask - 基礎知識入門決議
框架比較
Django web框架:
優點 - 組件非常全,教科書框架,admin model-ORM session
缺點 - 資源浪費,因為組件多,大,還是互相關聯的,隨便卸載組件,可能會造成專案的崩潰
Flask web框架:
優點 - 擴展性強,精簡,簡單,第三方組件豐富 session Flask-Session Flask-Admin
缺點 - 穩定性相對較差 ,第三方組件新版兼容性
缺點 - 復雜度較高
一. Flask 的安裝 和 程式員儀式
安裝
pip install Flask 也可以在Pycharm中選擇安裝~
程式員儀式
啟動app.py下
from flask import Flask # 帶入Flask類
app = Flask(__name__) # 實體化Flask物件 app
@app.route('/') # app中的路由裝飾器
def hello_world(): # 視圖函式
return 'Hello World!'
if __name__ == '__main__':
app.run(debug=True) # 啟動服務
瀏覽器訪問127.0.0.1:5000, 就會完成Flask的程式員儀式, 歡迎你成為一個Flask用戶!!!
相關的包的參考:
jinja 模板渲染工具
MarkUpSafe 安全標簽 Flask回傳模板標簽時,都會依賴MarkUpSafe
Werkzeug (德文) 工具 相當于django 的 uWSGI 底層是WSGI
二. Flask 的回傳值Response
1.return HttpResponse("瘋哥真帥!")
# 跟django中一樣, 直接回傳字串
2.return render_template("login.html")回傳模板頁面
# 回傳一個html模板,類似django中 render
@app.route('/login')
def login():
return render_template('login.html')
3.return redirect("/")重定向
# 與django中相同, 重定向,訪問"/re"跳轉到"/home"
@app.route("/re")
def re():
return redirect("/home")
4.return send_file("file.mp4") 回傳檔案
# 打開并回傳檔案內容 自動識別檔案型別并且在回應頭中自動加入 Content-type:檔案型別
不能識別的型別瀏覽器會執行下載操作
@app.route("/get_file")
def get_file():
return send_file("1.jpg")
5.return jsonify({"key": "value"}) 回傳JSON資料
# 回傳標準格式的jsonz字串, 在回應頭中加入Content-type:application
@app.route("/get_json")
def get_json():
d = {
"name": "Alexander.DSB.Li"
}
return jsonify(d) # Content-Type:application/json
# Flask 1.1.1
# return d # 暫時不建議使用 兼容性
# 直接回傳dict時 本質上在執行jsonify(d)
三. Flask 請求request
請求案例如下:
from flask import Flask, render_template, request, redirect,session app = Flask(__name__) # __name__ app.secret_key = "!@#$%^&*()" app.debug = True # 開啟Debug模式 @app.route("/login", methods=["GET", "POST"]) # 405 請求方式不被允許 def login(): # 從request中取出請求方式 # 判斷請求方式 GET render POST 處理 if request.method == "GET": # 在Django request.GET 取出 URL 中的引數 # 在Flask 獲取URL 中的引數 # print(request.url) # 請求地址 # print(request.url_charset) # URL 編碼方式 # print(request.url_root) # 請求地址 完整請求地址 host # print(request.url_rule) # 請求路由地址 # print(request.values.to_dict()) # 接收所有(GET,POST)請求中的資料,包含了 URL 和 FormData 中的資料 # print(request.args.get("id")) # 獲取URL中的資料 字串 return render_template("login.html") if request.method == "POST": # 在Django request.POST 取出 FormData (Form表單) # 在Flask 獲取FormData request.form # print(request.form.get("username")) # print(request.form.to_dict()) # 獲取一個 FileStorage Flask檔案特殊物件 # print(request.files.get("my_file")) # my_file = request.files.get("my_file") # new_file = os.path.join("xht",my_file.filename) # my_file.save(new_file) # 獲取其他資料 # request.headers # request.cookies # request.path == request.url_rule # request.host == "127.0.0.1:9527" # request.host_url == "http://127.0.0.1:9527/" # 特殊提交方式資料獲取 # Content-Type:application/json # request.json 獲取Content-Type:application/json時提交的資料 # Content-Type 無法被識別 或 不包含Form字眼 # request.data 獲取 原始請求體中的資料 b"" if request.form.get("username") == "Alexander.DSB.Li": session["user"] = request.form.get("username") return redirect("/") @app.route("/") def index(): print(session.get("user")) return render_template("index.html") if __name__ == '__main__': app.run("0.0.0.0", 9527) # 監聽地址 和 埠
1.request.method
# 回傳請求的方式, post,get...
2.request.form
# 回傳Form表單中傳遞傳過來的值
print(request.form) # ImmutableMultiDict([('user', 'kong'), ('pwd', 'hui')])
# ImmutableMultiDict 它看起來像是的Dict 就用Dict的方法取值試一下吧
print(request.form["user"]) # kong
print(request.form.get("pwd")) # hui
# 看來全部才對了, ImmutableMultiDict 似乎就是個字典,再來玩一玩它
print(list(request.form.keys())) # ['user', 'pwd'] 看來是又才對了
#如果以上所有的方法你都覺得用的不爽的話
req_dict = dict(request.form)
print(req_dict) # 如果你覺得用字典更爽的話,也可以轉成字典操作(這里有坑)
3.request.args
# 回傳url中傳遞的引數
例如:

然后我們看下:
print(request.args) # ImmutableMultiDict([('id', '1'), ('age', '20')])
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']}
與 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["user"]) # Oldboy
# 這回喜歡直接操作字典的小伙伴們有驚喜了! to_dict() 方法可以直接將我們的引數全部轉為字典形式
print(request.values.to_dict()) # {'user': 'Oldboy', 'pwd': 'DragonFire', 'id': '1', 'age': '20'}
但是有坑!!
# 如果url和form中的Key重名的話,form中的同名的key中value會被url中的value覆寫
# http://127.0.0.1:5000/req?id=1&user=20
print(request.values.to_dict()) # {'user': 20 'pwd': 'DragonFire', 'id': '1'}
5.request.cookies
# 回傳瀏覽器中的cookies資訊
6.request.headres
# 回傳請求頭中資料
print(type(request.headers))
"""
Host: 127.0.0.1:5000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: http://127.0.0.1:5000/home
Content-Type: application/x-www-form-urlencoded
Content-Length: 26
Cookie: csrftoken=vDIozqveCEfArdYXlM6goHVlSQEn7h4bDygNphL2Feas60DiM2di0jlqKfxo7xhA
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
"""
7.request.data
# b""
存放的是請求體中的原始資訊 Content-Type:asdfkjashgjvajhgjkow
8.request.json
# 請求頭中存在 Content-Type:application/json 將請求體中的資料 存放在JSON中,沒有回傳None
9.request.files
如果遇到檔案上傳的話,request.files 里面存的是你上傳的檔案,但是 Flask 在這個檔案的操作中加了一定的封裝,讓操作變得極為簡單.
前段代碼:

后端:
print(request.files) # ImmutableMultiDict([('file', <FileStorage: 'DragonFire.txt' ('text/plain')>)])
print(request.files["file"]) # <FileStorage: 'DragonFire.txt' ('text/plain')>
my_file = request.files["file"]
my_file.save("OldBoyEDU.txt") # 保存檔案,里面可以寫完整路徑+檔案名
10.request獲取路徑
# 獲取當前的url路徑
print(request.path)# /req
# 當前url路徑的上一級路徑
print(request.script_root) #
# 當前url的全部路徑
print(request.url) # http://127.0.0.1:5000/req
# 當前url的路徑的上一級全部路徑
print(request.url_root ) # http://127.0.0.1:5000/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/255829.html
標籤:Python
下一篇:python協程
