1

As far as I understand, flask.g offers temporary storage for the current request context (even though it's technically the application context as described here). Accessing g.my_data during a request handler will ensure that my_data is for the current request. Does Django have something equivalent to this?

In my experimentation, Django's request object, which is passed into view functions, can be used the same as flask.g. I can simply use request.my_data and be ensured that my_data is for the current request.

Noticing, this I tried using flask.request similar to how I used flask.g, with equivalent results. This begs the question what does flask.g provide over flask.request, just peace of mind that flask.request attributes will not be overwritten?

FYI on use case, I'm sharing data between the actual request handler (flask) or view functions (django), and the middleware (django) or @before_request (flask) handlers.

This source seems to recommend putting data on the request.

As does this source.

This leads me to answer yes for number 1 below, but wonder even more about number 2??

TLDR:

  1. Can Django request be used equivalently to flask.g?
  2. Can flask.request be used equivalently to flask.g, or what is the benefit of flask.g over flask.request?
davidism
  • 121,510
  • 29
  • 395
  • 339
Panda
  • 690
  • 1
  • 6
  • 19

1 Answers1

-1

Django has the context_data and the get_context() method. To access this data override the get_context_data() method in your view like this.

def get_context_data(self, **kwargs):
  context = super(NameOfView, self).get_context_data(**kwargs)
  context.update(...)
  return context
Dan
  • 1,874
  • 1
  • 16
  • 21
  • I don't think you understood my use case. I want to set data in a middleware handler, that is then accessible in my view handler. I was planning on just adding it to the request object since that's what django does with request.user. – Panda May 23 '17 at 18:36
  • @Panda did you ever find a solution to this? I want to do the same thing – Robin Winslow Apr 12 '18 at 08:09
  • If I remember correctly, I used Django's `request` object – Panda Apr 12 '18 at 14:49