Flask总结
Flask的優缺點
優點:Flask小而精,三方組件全
缺點:穩定性相對較差,三方組件版本問題,Flask一旦迭代,就可能造成三方組件不兼容的問題。
flask三劍客 + 小兒子
Django? ? ? ? ? ? ? ? ? ? ? flask
HTTPResponse :? ?return? ?"Hello World"
render? ? ? ? ? ? ? ? :? ?render_template
redirect? ? ? ? ? ? ? :? ? redirect
?
send_file("static/123.jpg")? ? # 上傳文件
jsonify("{id: 1}")? # Content-Type: application/json
request
request.form Form表單提交的數據,POST request.args url中的參數 request.data Content-Type無法解析的數據,原始數據是字節流(b"") request.json Content-Type:application/jsonrequest.method 獲取請求方式 request.path 路由地址/login request.files 獲取文件對象session -? Flask-Session
from flask import sessionapp.secret_key = '123' # 如果遇到了 Must provide secret_key to use csrf錯誤提醒,原因就是沒有設置secret_key ,在代碼中加上session["user"] = "wjs" session存放在瀏覽器的cookie中默認名稱是session 序列化的數據 session.get("user")Flask-Session 一個三方組件 from flask_session import Session from flask import sessionapp.config["SESSION_TYPE"] = "redis" app.config["SESSION_REDIS"] = Redis實例 Session(app)session["user"] = "wjs" session存放在瀏覽器的cookie中默認名稱是session -- UUID session.get("user")Flask實例化配置,對象配置:
實例化:Flask(__name__,template_folder="模板路徑",static_folder="靜態文件路徑",static_url_path="/靜態文件訪問路徑")對象配置:app.debug = Trueapp.config["DEBUG"] = Trueclass FlaskSetting(object):DEBUG = Trueapp.config.from_object(FlaskSetting)藍圖 Blueprint
from flask import Blueprint blue = Blueprint("blue",__name__,template_folder="模板路徑",static_folder="靜態文件路徑",static_url_path="/靜態文件訪問路徑",url_prefix="/blue")@blue.route("/blue01") def blue01():return "123"記得在app中注冊藍圖 app:app.register_blueprint(blue)特殊裝飾器:
@app.template_global() # 全局函數 def ab(a,b):return a + b {{ab(1,2)}} # 調用ab函數@app.template_filter() # 偏函數 def abc(a, b, c):return a + b + c {{2|abc(2,2)}} # 調用abc函數@app.before_request # 請求進入視圖函數之前 def be1():return None # 跳過@app.after_request # 視圖函數結束之后,返回客戶端之前 def af1(response):return response正常: 請求-be1-be2-be3-af3-af2-af1-客戶端 # be是按照代碼執行順序走,af是按照代碼執行順序的反序走異常: 請求-be1-be2-af3-af2-af1-客戶端 # 斷掉以后be斷掉后面的就不走了,af還是都走@app.errorhandler(404) # 重定義錯誤信息 def error404(args): # args存放的是錯誤信息return render_template("error.html", args=args)
Flask CBV
from flask import viewsclass Login(views.MethodView):# methods = ["POST"]def get(self):passdef post(self):passapp.add_url_rule("/login",endpoint=None,view_func=Login.as_view(name="login"),methods=["POST"])WTForms
simple,core
flash
from flask import flash,get_flashed_messagesflash("66","tag")get_flashed_messages(category_filter=["tag"])
?
轉載于:https://www.cnblogs.com/wjs521/p/10145078.html
總結
- 上一篇: spring-service.xml 模
- 下一篇: 马达是什么意思