Why does Request class instantiated multiple times?

Hi @tom!
What is the reason to instantiate Request instance multiple times? I see that every middleware does it and views as well.

What if there will be a middleware that makes a request instance and adds it to the scope?

So third-party can override that behavior for own reasons.

Here’s two different approaches to middleware we could have taken in Starlette:

  • ASGI middleware. Middleware classes present the ASGI interface. The ASGI scope is the state, and a request instance is an interface onto that state. Instantiating a request instance is a cheap operation.
  • Starlette-specific request/response middleware. Instantiate a request prior to running the middleware, and pass the same instance all the way through.

We’re using the first approach. A benefit is that Starlette middleware is really portable across different ASGI frameworks - you could be using a completely different framework, and still be able to Starlette middleware implementations with it.

Hi @tom

I’ve come across some limitations with this approach, which I’m hoping you can help me with.

I wrote some CSRF middleware which needs to access the form data on the Request instance.

But if the middleware accesses the form data using request.form(), that data is no longer accessible in a HTTPEndpoint. This is because the _form attribute on the request is lost.

Does that make sense? A work around is for the middleware to add the form data to the scope, but I’m wondering if you can suggest any better alternatives.

Thanks