如果我使用request.body()
方法,它是工作的。但是是字节类型,我想获得json或dict类型的数据,以便获得用户名和密码密钥内容
async def set_body(request: Request):
receive_ = await request._receive()
async def receive() -> Message:
return receive_
request._receive = receive
@app.middleware("http")
async def demo(request: Request, call_next):
await set_body(request)
jsob_body = await request.json()
print(jsob_body)
response = await call_next(request)
retu**strong text**rn response
import requests
url = "http://127.0.0.1:8000/token"
payload={'username': 'test',
'password': 'test_pw'}
files=[
]
headers = {}
response = requests.request("POST", url, headers=headers, data=payload, files=files)
我可以得到这个,但有一个错误,将打破POST请求
Traceback (most recent call last):
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 372, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\fastapi\applications.py", line 269, in __call__
await super().__call__(scope, receive, send)
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\starlette\applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\starlette\middleware\errors.py", line 184, in __call__
raise exc
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\starlette\middleware\base.py", line 68, in __call__
response = await self.dispatch_func(request, call_next)
File "D:\codes\ocr_server\.\main.py", line 43, in middle
jsob_body = await request.json()
File "D:\devtools\anaconda3\envs\fastapi\lib\site-packages\starlette\requests.py", line 242, in json
self._json = json.loads(body)
File "D:\devtools\anaconda3\envs\fastapi\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "D:\devtools\anaconda3\envs\fastapi\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "D:\devtools\anaconda3\envs\fastapi\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
1条答案
按热度按时间vyu0f0g11#
使用
json
代替data
: