開發過程中遇到的一個問題:就是想要修改request中的請求體,具體程式碼如下
class CustomMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
async def modify_body():
message = await receive()
assert message["type"] == "http.request"
body: bytes = message.get("body", b"")
body: str = body.decode()
data = json.loads(body)
data["value"] = "456"
message["body"] = json.dumps(data).encode()
return message
await self.app(scope, modify_body, send)
app.add_middleware(CustomMiddleware)
recive 是一個非同步函式