1

I read the cookbook article on making user objects avail to all requests but I may not understand it fully because I can't see if it is related to my problem.

I render quite a few templates on a site I'm working on and there's different user info each templates needs. For example, like this page on SO my every page needs to display my username, points, number of notifications, number of badges, etc. I have all this information but I find myself having to add it to each request dictionary I send to the template like so:

return dict(page=page, name=name, save_url=save_url,
                logged_in=authenticated_userid(request), title='add new', url='/new', points=points, num_badges=badges)

Is there a way to combine all this once so I can just send one entry to each view? I'm sure its not good to run the same query every time but its also annoying to have to type it for every view. Any suggestions?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Lostsoul
  • 25,013
  • 48
  • 144
  • 239

1 Answers1

1

The simplest method would be to generate your 'common' information in one method, returning a dict, then updating your local view dict with that information

local = dict(page=page, name=name, save_url=save_url, title='add new',
     url='/new', points=points, num_badges=badges)
local.update(retrieve_common_information(request))
return local

Another method is to use something like the pyramid_viewgroup (documentation now located at a new location), where you delegate the rendering of common 'snippets' of your pages to separate views.

One such view could take care of the common user information you want to render, and be reused everywhere.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks Marijin..I guess I was asking two questions the easiest way to do it(which it seems you answered and I'll play around with testing it) but wouldn't it be re-running this query constantly? Like if a user is browsing the site regardless of the content on the page this general information query will be ran. I'm uber new to web dev so sorry if this is kind of querying is normal. – Lostsoul Jul 08 '12 at 20:37
  • 1
    Yup, such querying is normal; HTTP is stateless, every time a query comes in you need to rebuild that state. There are tricks such as sessions, but they have a cost in scalability too. – Martijn Pieters Jul 08 '12 at 21:37
  • ahh..always a trade off. Thanks makes sense now. – Lostsoul Jul 08 '12 at 22:04