四、Flask进阶

Flask-Cache

  • pip install flask-caching安装
  • flask_cache初始化
# 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)
# 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切面编程思想。
    在这里插入图片描述
# 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内置对象

在这里插入图片描述

# 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

在这里插入图片描述

# __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

相关推荐

  1. 章:模板

    2024-04-25 07:36:04       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 07:36:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 07:36:04       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 07:36:04       82 阅读
  4. Python语言-面向对象

    2024-04-25 07:36:04       91 阅读

热门阅读

  1. 哈希封装unordered系列关联式容器

    2024-04-25 07:36:04       35 阅读
  2. Git 流程和命令

    2024-04-25 07:36:04       138 阅读
  3. 【算法模版】数据结构模版

    2024-04-25 07:36:04       114 阅读
  4. radware负载均衡简介及应用场景

    2024-04-25 07:36:04       37 阅读
  5. MIL-STD-1553B和FC-AE-1553的主要区别

    2024-04-25 07:36:04       50 阅读
  6. 十大经典排序算法之选择排序。

    2024-04-25 07:36:04       39 阅读
  7. springboot 集成 activemq

    2024-04-25 07:36:04       43 阅读
  8. Centos 7.9 一键安装 Oracle 12CR2(240116)单机 PDB

    2024-04-25 07:36:04       39 阅读
  9. 415. 字符串相加

    2024-04-25 07:36:04       34 阅读