Flask-Cache
- pip install flask-caching安装
- flask_cache初始化
python
# ext.py
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_caching import Cache
db = 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)
python
# view.py
# 使用缓存
@blue.route('/')
@cache.cached(timeout=20) # 给视图函数加一个缓存20秒, 超过20秒就会重新请求,20秒内使用缓存
def index():
print('Index2')
print('index视图函数中:', g.star)
time.sleep(5)
return 'index2'
钩子
- 钩子或叫钩子函数,是指在执行函数和目标函数之间挂载的函数,框架开发者给调用方提供一个poit-挂载点,是-种AOP切面编程思想。
python
# view.py
# 钩子:钩子函数
# 也叫中间件
# before_request: 每一次请求之前访问
@blue.before_request
def before():
print('before_request')
# request
# print(request.path)
# print(request.method)
# print(request.remote_addr) # 客户端ip
# 简单的反爬
# print(request.user_agent) # python-requests/2.28.2
# if "python" in request.user_agent.string:
# return '您正在使用Python爬虫,再见!'
# 针对IP做反爬(简单)
ip = request.remote_addr
# cache.get()
# cache.set()
if cache.get(ip):
# 做了拦截,不会进入视图函数
return '小伙子,别爬了!'
else:
# 对每个IP设置一个缓存,1秒内不让重复访问
cache.set(ip, 'value', timeout=1)
Flask内置对象
python
# view.py
from flask import Blueprint, request, render_template, session, g, current_app
# Flask内置对象
# request:请求对象
# session:会话对象
# g:global全局对象
# current_app: Flask应用对象
g.star = '杰伦'
print(g.star)
print(current_app) # <Flask 'App'>
print(current_app.config) # <Config {'ENV': 'production', 'DEBU...
配置template和static
python
# __init__.py :初始化文件,创建Flask应用
from flask import Flask
from .views import blue
from .exts import init_exts
import os
# 项目目录
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print('BASE_DIR:', BASE_DIR)
# BASE_DIR: FlaskPro1_进阶 项目目录
def create_app():
# 配置静态文件和模板文件目录
# static_folder = '../static'
# template_folder = '../templates'
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' # sqlite配置
# db_uri = 'mysql+pymysql://root:123456@localhost:3306/flaskdb' # mysql的配置
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 禁止对象追踪修改
# 初始化插件
init_exts(app=app)
return app