简体   繁体   English

使用 Pydantic.BaseModel 时如何访问 fastapi.Request.state

[英]How to access fastapi.Request.state when using Pydantic.BaseModel

I'm trying to create a pydantic BaseModel that will be able to map some data from the request body and also from the request.state.我正在尝试创建一个 pydantic BaseModel,它将能够 map 来自请求正文和 request.state 的一些数据。

How can this be accomplished?如何做到这一点?

Request metadata shouldn't be part of your model - the model should only be concerned with the actual request (ie the data submitted by the user).请求元数据不应该是您的 model 的一部分 - model 应该只关注实际请求(即用户提交的数据)。

To access metadata about the request, add a Request object to your view definition:要访问有关请求的元数据,请将Request object 添加到您的视图定义中:

def my_method(item: Item, request: Request):

This will magically give you all the metadata (including the .state entry) under the request variable in your view function.这将神奇地为您提供视图 function 中request变量下的所有元数据(包括.state条目)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 pydantic.BaseModel:父类的类方法 - pydantic.BaseModel: classmethod of a parent 如何使用 PATCH 使用 FastAPI 和 PyDantic BaseModel 部分更新数据 - How to partially update data with FastAPI and PyDantic BaseModel using PATCH 在 Fastapi 中找不到 pydantic BaseModel - pydantic BaseModel not found in Fastapi 如何在带有 typing.Union 的 pydantic.BaseModel 中使用两种变量类型? - How to use two variable types in a pydantic.BaseModel with typing.Union? 在从 pydantic.BaseModel 创建的 JSON 中,如果未设置,则排除可选 - In JSON created from a pydantic.BaseModel exclude Optional if not set 我们可以使用 FastAPI 直接在 model.predict() 内部使用 Pydantic 模型(Basemodel)吗?如果不能,为什么? - Can we use Pydantic models (Basemodel) directly inside model.predict() using FastAPI, and if not ,why? 如何使 Pydantic 的 BaseModel 接受 fastapi 应用程序中的一些特殊情况输入类型 - How to make Pydantic's BaseModel accept some special case input types in fastapi app 使用 FastApi 分页时出现 Pydantic 验证问题 - Pydantic validation issue when using pagination with FastApi pydantic basemodel 破坏了类方法对属性的访问 - pydantic basemodel breaks classmethod access to attributes 如何 JSON 序列化 Pydantic BaseModel 中的 ENum 类 - How to JSON serialize ENum classes in Pydantic BaseModel
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM