Skip to content

When use middleware found problem #193

@Shengshenlan

Description

@Shengshenlan

It is a simple middware example.

@app.middleware("http")
async def add_process_time_header(
            request: Request, call_next: Callable[[Request], Awaitable[Response]]
        ) -> Response:
            start_time = time.time()
            response = await call_next(request)
            process_time = time.time() - start_time
            response.headers["X-Process-Time"] = str(process_time)
            return response

error:

File "/home/u/miniconda3/envs/dev/lib/python3.12/site-packages/starlette/middleware/base.py", line 163, in body_stream
    assert message["type"] == "http.response.body"
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError

I noticed that the final response contains an error, and I'm unsure of the cause. I would appreciate it if you could help me understand it.

{'type': 'http.response.body', 'body': b''}
{'type': 'http.response.body', 'body': b'{"message":"Accepted"}'}
{'type': 'http.response.body', 'body': b'{"message":"Accepted"}'}
{'type': 'http.response.body', 'body': b'event: message\r\ndata: {"jsonrpc":"2.0","id":1,"result":{"tools":[]}}\r\n\r\n', 'more_body': True}
{'type': 'http.response.start', 'status': 200, 'headers': [(b'content-length', b'4'), (b'content-type', b'application/json')]}

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions