zdppy_api如何实现带参数的中间件

2024-06-04 22:36

本文主要是介绍zdppy_api如何实现带参数的中间件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考代码

import timefrom api.middleware import Middleware
from api.middleware.base import BaseHTTPMiddleware
from api.exceptions import AuthException
import jwthas_logger = False
try:from log import loggerhas_logger = True
except:passdef roleapi(has_auth_func, jwtkey=None):"""判断用户角色是否有某个接口的权限:param has_auth_func 考虑到可能使用异步的MySQL库,此函数必须是一个异步函数接受Token中解析出来的role和request中的method和path作为参数,用于判断用户对该路径是否有访问权限"""return Middleware(RoleAPIAuthMiddleware, has_auth_func=has_auth_func, jwtkey=jwtkey)class RoleAPIAuthMiddleware(BaseHTTPMiddleware):def __init__(self, has_auth_func, jwtkey, app):super().__init__(app)self.has_auth_func = has_auth_funcself.jwtkey = jwtkeyasync def dispatch(self, request, call_next):# 判断是否需要跳过校验if "/login" in str(request.url) or "/register" in str(request.url):if has_logger:logger.debug("识别到正在访问不需要校验的路径", method=request.method, url=request.url)return await call_next(request)if has_logger:msg = f"开始进行基于角色和接口的高级别权限校验:method={request.method} url={request.url}"logger.debug(msg)# 获取tokentoken = request.headers.get("Authorization")if token is None:if has_logger:logger.error("权限不足:没有携带Token", token=token)raise AuthException("权限不足:没有携带Token")# 解析tokendata = Nonetry:if isinstance(self.jwtkey, str):data = jwt.parse_token(token, key=self.jwtkey)else:data = jwt.parse_token(token)except Exception as e:if has_logger:logger.error("获取用户Token失败", headers=request.headers, token=token, error=e)raise AuthException("无效的Token")# token的结果必须是字典类型if not isinstance(data, dict):if has_logger:logger.error("Token的解析结果不是字典类型", data=data)raise AuthException("无效的Token")# 必须要有过期时间expired = data.get("expired")if expired is None:if has_logger:logger.error("该Token没有设置过期时间", data=data, expired=expired)raise AuthException("无效的Token")# 校验过期时间的类型if not (isinstance(expired, int) or isinstance(expired, float)):if has_logger:logger.error("该Token的过期时间不是数字类型", expired=expired)raise AuthException("无效的Token")# 校验是否过期now = time.time()if now > expired:if has_logger:logger.warning("Token已过期", expired=expired)raise AuthException("Token已过期")# 必须要有用户名和用户IDuserid = data.get("id")username = data.get("username")userrole = data.get("role")if not (userid or username or userrole):if has_logger:logger.error("Token中应该包含用户ID,用户名和用户角色",userid=userid,username=username,userrole=userrole,token=token,data=data,)raise AuthException("无效的Token")# 获取请求方法和请求路径base_url = request.base_urlurl = request.urlmethod = request.methodpath = str(url).replace(str(base_url), "")if has_logger:logger.debug("开始查询用户是否具备接口级别的权限",method=method,path=path,userid=userid,username=username,userrole=userrole,)has_auth = Falsetry:has_auth = await self.has_auth_func(userrole, method, path)except Exception as e:if has_logger:logger.error("查询用户接口级别权限失败",method=method,path=path,userid=userid,username=username,userrole=userrole,error=e,)raise AuthException("无效的Token")if has_logger:logger.debug("成功查询用户是否具备接口级别的权限",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)if not has_auth:if has_logger:logger.warning("权限不足",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)raise AuthException("权限不足")# 权限充足,发送请求,获取响应response = await call_next(request)return response

调用栈分析

使用中间件

app1 = api.Api(routes=[api.resp.get("/", index),api.resp.get("/1", index),api.resp.post("/login", login),],middleware=[# 默认是:zhangdapeng zhangdapng520# 可以传入账号和密码进行覆盖apimidauth.roleapi(has_auth_func)]
)

apimidauth.roleapi(has_auth_func) 实例化了一个中间件对象。

has_auth_func 是一个函数

这个函数,会在中间件里面,被调用到,完整代码如下。

async def has_auth_func(role, method, path):"""校验角色对method和path是否有访问权限"""print(role, method, path)if not str(path).startswith("/"):path = f"/{path}"# GET:/1auth = str(method).upper() + ":" + path# 判断是否有权限role_auth_dict = auth_dict.get(role)if not isinstance(role_auth_dict, dict):return Falseif not role_auth_dict.get(auth):return Falsereturn True

roleapi 方法

完整代码如下:

def roleapi(has_auth_func, jwtkey=None):"""判断用户角色是否有某个接口的权限:param has_auth_func 考虑到可能使用异步的MySQL库,此函数必须是一个异步函数接受Token中解析出来的role和request中的method和path作为参数,用于判断用户对该路径是否有访问权限"""return Middleware(RoleAPIAuthMiddleware, has_auth_func=has_auth_func, jwtkey=jwtkey)

这个其实就是一个普通的函数。
不过比较特殊的地方在于,这个函数的返回值是一个Middleware类的实例。这个类接收如下参数:

  • RoleAPIAuthMiddleware:自定义的中间件
  • has_auth_func:实际上是自定义中间件需要的一个参数
  • jwtkey:实际上也是自定义中间件需要的一个参数

注意:has_auth_func 和 jwtkey 这两个参数,不是 Middleware 类必须的,而是我们自定义的 RoleAPIAuthMiddleware 需要的。

RoleAPIAuthMiddleware 的代码分析

完整代码:

class RoleAPIAuthMiddleware(BaseHTTPMiddleware):def __init__(self, has_auth_func, jwtkey, app):super().__init__(app)self.has_auth_func = has_auth_funcself.jwtkey = jwtkeyasync def dispatch(self, request, call_next):# 判断是否需要跳过校验if "/login" in str(request.url) or "/register" in str(request.url):if has_logger:logger.debug("识别到正在访问不需要校验的路径", method=request.method, url=request.url)return await call_next(request)if has_logger:msg = f"开始进行基于角色和接口的高级别权限校验:method={request.method} url={request.url}"logger.debug(msg)# 获取tokentoken = request.headers.get("Authorization")if token is None:if has_logger:logger.error("权限不足:没有携带Token", token=token)raise AuthException("权限不足:没有携带Token")# 解析tokendata = Nonetry:if isinstance(self.jwtkey, str):data = jwt.parse_token(token, key=self.jwtkey)else:data = jwt.parse_token(token)except Exception as e:if has_logger:logger.error("获取用户Token失败", headers=request.headers, token=token, error=e)raise AuthException("无效的Token")# token的结果必须是字典类型if not isinstance(data, dict):if has_logger:logger.error("Token的解析结果不是字典类型", data=data)raise AuthException("无效的Token")# 必须要有过期时间expired = data.get("expired")if expired is None:if has_logger:logger.error("该Token没有设置过期时间", data=data, expired=expired)raise AuthException("无效的Token")# 校验过期时间的类型if not (isinstance(expired, int) or isinstance(expired, float)):if has_logger:logger.error("该Token的过期时间不是数字类型", expired=expired)raise AuthException("无效的Token")# 校验是否过期now = time.time()if now > expired:if has_logger:logger.warning("Token已过期", expired=expired)raise AuthException("Token已过期")# 必须要有用户名和用户IDuserid = data.get("id")username = data.get("username")userrole = data.get("role")if not (userid or username or userrole):if has_logger:logger.error("Token中应该包含用户ID,用户名和用户角色",userid=userid,username=username,userrole=userrole,token=token,data=data,)raise AuthException("无效的Token")# 获取请求方法和请求路径base_url = request.base_urlurl = request.urlmethod = request.methodpath = str(url).replace(str(base_url), "")if has_logger:logger.debug("开始查询用户是否具备接口级别的权限",method=method,path=path,userid=userid,username=username,userrole=userrole,)has_auth = Falsetry:has_auth = await self.has_auth_func(userrole, method, path)except Exception as e:if has_logger:logger.error("查询用户接口级别权限失败",method=method,path=path,userid=userid,username=username,userrole=userrole,error=e,)raise AuthException("无效的Token")if has_logger:logger.debug("成功查询用户是否具备接口级别的权限",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)if not has_auth:if has_logger:logger.warning("权限不足",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)raise AuthException("权限不足")# 权限充足,发送请求,获取响应response = await call_next(request)return response

基本结构分析

class RoleAPIAuthMiddleware(BaseHTTPMiddleware):def __init__(self, has_auth_func, jwtkey, app):super().__init__(app)self.has_auth_func = has_auth_funcself.jwtkey = jwtkey

自定义的中间件类,需要继承:BaseHTTPMiddleware,这个类来自于 from api.middleware.base import BaseHTTPMiddleware 。

初始化方法:

def __init__(self, has_auth_func, jwtkey, app):super().__init__(app)self.has_auth_func = has_auth_funcself.jwtkey = jwtkey

在这个初始化方法中,我们定义了此中间件需要的参数。

我们在这里定义的是类的参数,但是实际上最后传递参数的方式是:

return Middleware(RoleAPIAuthMiddleware, has_auth_func=has_auth_func, jwtkey=jwtkey)

这里的 app 是没有传参的。

核心是 dispatch 方法

async def dispatch(self, request, call_next):# 判断是否需要跳过校验if "/login" in str(request.url) or "/register" in str(request.url):if has_logger:logger.debug("识别到正在访问不需要校验的路径", method=request.method, url=request.url)return await call_next(request)if has_logger:msg = f"开始进行基于角色和接口的高级别权限校验:method={request.method} url={request.url}"logger.debug(msg)# 获取tokentoken = request.headers.get("Authorization")if token is None:if has_logger:logger.error("权限不足:没有携带Token", token=token)raise AuthException("权限不足:没有携带Token")# 解析tokendata = Nonetry:if isinstance(self.jwtkey, str):data = jwt.parse_token(token, key=self.jwtkey)else:data = jwt.parse_token(token)except Exception as e:if has_logger:logger.error("获取用户Token失败", headers=request.headers, token=token, error=e)raise AuthException("无效的Token")# token的结果必须是字典类型if not isinstance(data, dict):if has_logger:logger.error("Token的解析结果不是字典类型", data=data)raise AuthException("无效的Token")# 必须要有过期时间expired = data.get("expired")if expired is None:if has_logger:logger.error("该Token没有设置过期时间", data=data, expired=expired)raise AuthException("无效的Token")# 校验过期时间的类型if not (isinstance(expired, int) or isinstance(expired, float)):if has_logger:logger.error("该Token的过期时间不是数字类型", expired=expired)raise AuthException("无效的Token")# 校验是否过期now = time.time()if now > expired:if has_logger:logger.warning("Token已过期", expired=expired)raise AuthException("Token已过期")# 必须要有用户名和用户IDuserid = data.get("id")username = data.get("username")userrole = data.get("role")if not (userid or username or userrole):if has_logger:logger.error("Token中应该包含用户ID,用户名和用户角色",userid=userid,username=username,userrole=userrole,token=token,data=data,)raise AuthException("无效的Token")# 获取请求方法和请求路径base_url = request.base_urlurl = request.urlmethod = request.methodpath = str(url).replace(str(base_url), "")if has_logger:logger.debug("开始查询用户是否具备接口级别的权限",method=method,path=path,userid=userid,username=username,userrole=userrole,)has_auth = Falsetry:has_auth = await self.has_auth_func(userrole, method, path)except Exception as e:if has_logger:logger.error("查询用户接口级别权限失败",method=method,path=path,userid=userid,username=username,userrole=userrole,error=e,)raise AuthException("无效的Token")if has_logger:logger.debug("成功查询用户是否具备接口级别的权限",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)if not has_auth:if has_logger:logger.warning("权限不足",has_auth=has_auth,method=method,path=path,userid=userid,username=username,userrole=userrole,)raise AuthException("权限不足")# 权限充足,发送请求,获取响应response = await call_next(request)return response

中间件核心方法分析

参数是什么

async def dispatch(self, request, call_next):

首先,这个方法是一个异步方法。
第一个参数是请求对象,存储了客户端的所有请求信息。
第二个参数是调用下一个中间件的对象,如果成功了,则调用此方法得到一个response对象,返回response对象即可。

如果成功了返回什么?

如果成功了,则调用此 call_next 方法得到一个response对象,返回response对象即可。

response = await call_next(request)
return response

如果失败了,该返回什么?

示例代码如下:

if has_logger:logger.error("Token的解析结果不是字典类型", data=data)
raise AuthException("无效的Token")

首先,我们是记录错误日志。
然后,抛出一个异常。
因为 zdppy_api 已经内部封装了全局异常处理,所以这个异常,最终会被全局异常错误处理器自动捕获,并返回给客户端一个比较通用且友好的错误信息。

支持哪些异常类

首先是 AuthException,这个来源于:

from api.exceptions import AuthException

通过查看源码,我们可以知道, zdppy_api 框架,目前内置了如下异常处理器:

default_exception_handlers = {404: not_found,500: server_error,HTTPException: handle_http_exception,AuthException: handle_auth_exception,Exception: handle_exception,
}

最终总结

如果,我们要实现 db 请求上下文中间件:

  • 请求开始时,自动建立连接
  • 请求结束是,自动断开连接

那么,我们的实现思路如下:

  • 1、实现一个 OrmRequestMiddleware 中间件类。这个类继承 api.middleware.base.BaseHTTPMiddleware,接收一个 db 作为参数。
  • 2、实现一个 apimidorm.request(db) 方法,这个方法的返回值是 Middleware(OrmRequestMiddleware, db=db)
  • 3、在 OrmRequestMiddleware 自定义中间件类中,重写 async def dispatch(self, request, call_next) 方法
  • 4、方法体中实现具体的逻辑。请求开始之前,调用 db.connect(),调用 response = call_next(),之后调用 db.colse(),最后返回 response。

以上是一个具体的实现思路,仅供参考。

这篇关于zdppy_api如何实现带参数的中间件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1031317

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM