Flask高级 钩子(中间件Middleware)

发布时间 2023-07-04 11:27:49作者: 春游去动物园

Flask高级 钩子(中间件Middleware)

什么是钩子(中间件Middleware)

	钩子或叫钩子函数,是指在执行函数和目标函数之间挂载的函数,框架开发者给调用方提供一个point-挂载点,是一种AOP切面编程思想.

    常用的钩子函数
			before_first_request:处理第一次请求之前执行.
			before_request:在每次请求之前执行.通常使用这个钩子函数预处理一些变量,实现反爬等.
			after_request:注册一个函数,如果没有未处理的异常抛出,在每次请求之后运行.
			teardown_appcontext:当APP上下文被移除之后执行的函数,可以进行数据库的提交或者回滚.

案例

from .exts import cache
import time
@blueprints1.route('/cache/')
@cache.cached(timeout=20)  # 给视图函数加一个缓存20秒
def cache11():
    print('cache')
    time.sleep(5)
    return 'OK!'
    
    
# 钩子:钩子函数,也叫中间件
# before_request: 每次请求之前访问(每次请求之前调用)
@blueprints1.before_request
def befor():
    print('befor_request')

    # request
    print(request.method)
    print(request.path)
    print(request.remote_addr)  # 客户端的ip

    # 实现简单的反爬
    print(request.user_agent)
    # python requests模块 python-requests/2.29.0
    # 正常浏览器 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
    if "python" in request.user_agent.string:
        return '您正在使用python爬虫,再见!'

    # 针对IP做反爬(简单)
    ip = request.remote_addr

    # cache.set()   设置缓存
    # cache.get()   获取缓存
    if cache.get(ip):
        # 做了拦截,不会进入视图函数
        return '小伙子,别爬了!'
    else:
        # 对每一个IP设置一个缓存,1秒内不让重复访问
        cache.set(ip,'value',timeout=1)
        
 '''
 	这里的cache就是在前面 flaks-caching那一节中的cache
 '''
# 爬虫小脚本(配合使用)
import requests

res = requests.get("http://127.0.0.1:5000/index/cache/")
print(res.text)

for i in range(10):
    res = requests.get("http://127.0.0.1:5000/index/cache/")
    print(res.text)