四、Flask进阶

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
相关推荐
m0_7349497911 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_5145205712 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
2601_9498177212 小时前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
H Journey12 小时前
Python 国内pip install 安装缓慢
python·pip·install 加速
uNke DEPH12 小时前
Spring Boot的项目结构
java·spring boot·后端
zhenxin012213 小时前
Spring Boot 3.x 系列【3】Spring Initializr快速创建Spring Boot项目
spring boot·后端·spring
Polar__Star13 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
前端一小卒13 小时前
前端工程师的全栈焦虑,我用 60 天治好了
前端·javascript·后端
不停喝水13 小时前
【AI+Cursor】 告别切图仔,拥抱Vibe Coding: AI + Cursor 开启多模态全栈新纪元 (1)
前端·人工智能·后端·ai·ai编程·cursor
oyzz12013 小时前
Spring EL 表达式的简单介绍和使用
java·后端·spring