Alright, this is probably a really silly question but I am new to Python/Django so I can't really wrap my head around its scoping concepts just yet. Right now I am writing a middleware class to handle some stuff, and I want to set 'global' variables that my views and templates can access. What is the "right" way of doing this? I considered doing something like this:
middleware.py
from django.conf import settings
class BeforeFilter(object):
def process_request(self, request):
settings.my_var = 'Hello World'
return None
views.py
from django.conf import settings
from django.http import HttpResponse
def myview(request):
return HttpResponse(settings.my_var)
Although this works, I am not sure if it is the "Django way" or the "Python way" of doing this.
So, my questions are:
1. Is this the right way?
2. If it is the right way, what is the right way of adding variables that can be used in the actual template from the middleware? Say I want to evaluate something and I want to set a variable headername
as 'My Site Name' in the middleware, and I want to be able to do {{ headername }}
in all templates. Doing it the way I have it now I'd have to add headername
to the context inside every view. Is there anyway to bypass this? I am thinking something along the lines of CakePHP's $this->set('headername','My Site Name');
3. I am using the middleware class as an equivalent of CakePHP's beforeFilter
that runs before every view (or controller in CakePHP) is called. Is this the right way of doing this?
4. Completely unrelated but it is a small question, what is a nice way of printing out the contents of a variable to the browser ala print_r
? Say I want to see all the stuff inside the request
that is passed into the view? Is pprint
the answer?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…