27 lines
808 B
Python
27 lines
808 B
Python
# ④ 编写一个中间文件midlleware.py文件,写两个中间件,一个中间件函数是用来拦截ip黑名单的,黑名单自定义,
|
|
# 另一个中间件是用来记录每个访问接口的执行时间的,在main.py文件里调用中间件
|
|
from fastapi import Request,Response
|
|
from datetime import datetime
|
|
from time import time
|
|
|
|
async def m1(req:Request,next):
|
|
if req.client.host not in ['192.168.5.20','192.168.5.17']:
|
|
r1 = await next(req)
|
|
return r1
|
|
else:
|
|
return Response(content='别上网了,去学习吧')
|
|
|
|
async def m2(req:Request,next):
|
|
start = datetime.now()
|
|
print(f'请求执行的时间:{start}')
|
|
r2 = await next(req)
|
|
end = datetime.now()
|
|
print(f'请求执行的时间:{end}')
|
|
return r2
|
|
|
|
|
|
|
|
|
|
|
|
|