python - 在 Fastapi 中将依赖/依赖项放在哪里进行身份验证?
问题描述
我在 Fastapi 身份验证中看到了两种不同的使用依赖的方法:
方法一:
@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
return user
和方法2:
@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
return user
方法 1 和方法 2 有什么区别,哪一种更适合保护 API,即需要身份验证?
解决方案
在某些情况下,您实际上并不需要路径操作函数中依赖项的返回值。或者依赖不返回值。但是您仍然需要执行/解决它。对于这些情况,您可以将依赖项列表添加到路径操作装饰器中,而不是使用 Depends 声明路径操作函数参数。
更多细节和技巧可以在这里找到:https ://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/
推荐阅读
- java - 如何在java中从数据库中获取arraylist数据
- c++ - MQTT 客户端(Esp32)中的多个主题要发送到 Raspberry Pi(MQTT 代理)
- javascript - 我正在使用来自 w3school 的灯箱代码..位置固定的模态 div 正在关闭屏幕在 microsoft edge 但在 chrome 中它适合屏幕如何
- sql - 选择不同条件的多个计数,只计数不同,在一行中返回结果
- html - 屏幕阅读器不会读取列表大小/数量
- 内的元素
- 或者
- 内的元素
- mysql - 如何编写这些复杂的 MySQL 查询?
- r - 如何使用winzip解压缩R中的.Z文件
- reactjs - Nextjs 和 Material UI
- angular - 具有strictPropertyInitialization = true的角度HTTP绑定和服务中的HTTP请求?
- string - 如何使用 C++98 将字符串分配给枚举?