Flask-Cache
pip install flask-caching安装 flask_cache初始化
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_caching import Cachedb = SQLAlchemy( )
migrate = Migrate( )
cache = Cache( config= { 'CACHE_TYPE' : 'simple'
} ) def init_exts ( app) : db. init_app( app= app) migrate. init_app( app= app, db= db) cache. init_app( app= app)
@blue. route ( '/' )
@cache. cached ( timeout= 20 )
def index ( ) : print ( 'Index2' ) print ( 'index视图函数中:' , g. star) time. sleep( 5 ) return 'index2'
钩子
钩子或叫钩子函数,是指在执行函数和目标函数之间挂载的函数,框架开发者给调用方提供一个poit-挂载点,是-种AOP切面编程思想。
@blue. before_request
def before ( ) : print ( 'before_request' ) ip = request. remote_addrif cache. get( ip) : return '小伙子,别爬了!' else : cache. set ( ip, 'value' , timeout= 1 )
Flask内置对象
from flask import Blueprint, request, render_template, session, g, current_appg. star = '杰伦' print ( g. star) print ( current_app) print ( current_app. config)
配置template和static
from flask import Flask
from . views import blue
from . exts import init_extsimport os
BASE_DIR = os. path. dirname( os. path. dirname( os. path. abspath( __file__) ) )
print ( 'BASE_DIR:' , BASE_DIR)
def create_app ( ) : static_folder = os. path. join( BASE_DIR, 'static' ) template_folder = os. path. join( BASE_DIR, 'templates' ) app = Flask( __name__, static_folder= static_folder, template_folder= template_folder) app. register_blueprint( blueprint= blue) db_uri = 'sqlite:///sqlite3.db' app. config[ 'SQLALCHEMY_DATABASE_URI' ] = db_uriapp. config[ 'SQLALCHEMY_TRACK_MODIFICATIONS' ] = False init_exts( app= app) return app