四、Flask進階
1. Flask插件
I. flask-caching
-
安裝
pip install flask-caching
-
初始化
from flask_cache import Cache cache = Cache(config=('CACHE_TYPE':"simple" )) cache.init_app(app=app)
-
使用
在視圖函數上添加緩存@blue.route("/") @cache.cached(timeout=30) def home():print("加載數據")return "home
2. 鉤子(中間件Middleware)
-
什么是鉤子(中間件Middleware)
鉤子或叫鉤子函數,是指在執行函數和目標函數之間掛載的函數,框架開發者給調用方提供一個point-掛載點,是一種AOP切面編程思想
-
常用的鉤子函數
before_first_request
: 處理第一次請求之前執行
before_request
:在每次請求之前執行,通常使用這個鉤子函數預處理一些變量,實現反爬等
after_request
:注冊一個函數,如果沒有未處理的異常拋出,在每次請求之后運行.
teardown_appcontext
:當APP上下文被移除之后執行的函數,可以進行數據庫的提交或者回滾 -
AOP反爬策略
# 利用緩存反爬,相同ip地址1秒內不允許重復訪問 key = requestremote addr + "before" value = cache.get(key) if value:return小伙子,別爬了 else:cache.set(key,"aa',timeout=1) #反爬,防止非瀏覽器訪問 ua= request.user_agent # 用戶代理 if not ua:return "hello"# abort(400) # 可以拋出錯誤給用戶
3. Flask內置對象
I. g
- global全局對象
- g對象是專門用來保存用戶的數據的
- g對象在一次請求中的所有的代碼的地方,都是可以使用的
- 突破變量存儲位置限制,為數據傳遞添加了新的方式,比如我們在
before_request
產生一個數據在后面需要使用,可以保存在g對象中,在其他視圖函數中就可以使用這個數據
II. request
請求對象,可以獲取客戶端提交過來的所有請求信息
III. session
會話技術,服務端會話技術的接口
current_app
:
app的配置信息,app對象獲取,
current_app
使用獲取當前app需要注意,一定要在程序初始化完成之后
4. 配置templates和static
如果想要修改
templates
模板目錄或static
靜態目錄,可以自己配置
-
在
settings.py
文件中添加BASEDIR:import os BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
在
__init__.py
文件中添加static
路徑和templates
路徑:static_path = os.path.join(settings.BASE_DIR,'static') template_path = os.path.join(settings.BASE_DIR,'templates') app = Flask(__name__, static_folder=static_path, template_folder=template_path)
在views.py文件中訪問模板:
@blue.route('/hello/') def hello():return render_template("hello.html")
在模板中使用靜態資源:
<link rel="stylesheet" href="{{ url_for('static', filename='css/hello.css') }}">