royal
royal

Reputation: 550

Best way to request-scope data in Django?

I'm wondering if there's a clever pattern for request-scoping arbitrary information without resorting to either TLS or putting the information in the session.

Really, this would be for contextual attributes that I'd like to not look up more than once in a request path, but which are tied to a request invocation and there's no good reason to let them thresh around in the session.

Something like a dict that's pinned to the request where I can shove things or lazy load them. I could write a wrapper for request and swap it out in a middleware, but I figured I'd check to see what best-practice might be here?

Upvotes: 1

Views: 1903

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 599866

Just assign the dictionary directly to the request. You can do that in middleware or in your view, as you like.

Upvotes: 2

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

Context processors. They are called once for every request and receive the actual request object - so you can add ANY data to the context, also based on the curent request!

Upvotes: 1

Related Questions