[英]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.