因为在调试时我需要得到客户端向服务器端发送的原始数据,而在查看Fastapi框架这一块时发现这个功能不是很好用。之前也了解过如何提取fastapi的请求数据,有篇文章:http://www.04007.cn/article/924.html 不过更多的是取得一些请求的header信息等,取post请求的主体信息有提到使用request.body,但在使用时发现只能显示出一个对象,并没有方法从body对象中提取出原始的请求数据。本文地址:http://www.04007.cn/article/957.html,未经许可,不得转载.
在Fastapi框架的官方文档中 https://fastapi.tiangolo.com/advanced/using-request-directly/ 找到了这段话:And by doing so, FastAPI is validating that data, converting it and generating documentation for your API automatically.But there are situations where you might need to access the Request object directly. 即框架开发者也很清楚肯定有时有需求去直接访问原始的请求数据。同时也给了一个starlette框架的链接,Request documentation¶ You can read more details about the Request object in the official Starlette documentation site. 因为Fastapi框架底层用的是starlette。进到starlette的官网: https://www.starlette.io/requests/#body 有提示得取body有些不同,这也就是为什么之前使用requesty.body()提到不到目标数据的原因了。本文地址:http://www.04007.cn/article/957.html,未经许可,不得转载.
Body,There are a few different interfaces for returning the body of the request:
The request body as bytes: await request.body()
The request body, parsed as form data or multipart: await request.form()
The request body, parsed as JSON: await request.json()
You can also access the request body as a stream, using the async for syntax。If you access .stream() then the byte chunks are provided without storing the entire body to memory. Any subsequent calls to .body(), .form(), or .json() will raise an error.本文地址:http://www.04007.cn/article/957.html,未经许可,不得转载.
看文档我们应该使用:await request.body() 来得取目标数据,但我在实际使用中使用await request.body()时发现会导致请求一直等待直至请求中断。并没有完全实现,之后我自己用了一个其它的办法,在捕获框架验证异常的时候为了不抛出422错误,我们会自己去定义异常捕获,详见文章: http://www.04007.cn/article/923.html 而在这里有一个Class: RequestValidationError。我发现可以通过里来拿到body数据。本文地址:http://www.04007.cn/article/957.html,未经许可,不得转载.
async def request_exception_handler(request: Request, exc: RequestValidationError): #通过exc.body可以直接拿到请求的原始数据 logger.info("Request-Body:" + str(exc.body))本文地址:http://www.04007.cn/article/957.html,未经许可,不得转载.
本文地址:http://www.04007.cn/article/957.html 未经许可,不得转载. 手机访问本页请扫描右下方二维码.
![]() |
![]() |
手机扫码直接打开本页面 |