django - Code to run in all views in a views.py file -


what best way of putting bit of code run views in views.py file?

i come php background , put in constructor/index bit ran whatever page being requested. has specific views.py file though, want check user has access 'this app/module' , want avoid having use decorators on views if possible?

tl;dr

you should check middlewares. allows execute code before view execution, template rendering , other stuff.

some words middlewares

you can represent middlewares in head this:

middleware concept

as can see, request (orange arrow) go through every middleware before executing view , can hitting every middleware after (if want before template processing example).

using django 1.10

arcitecture of middlewares have changed in django 1.10, , represented simple function. example, here's counter of visits each page:

def simple_middleware(get_response):     # one-time configuration , initialization.      def middleware(request):         try:             p = page.objects.get(url=request.path)             p.nb_visits += 1             p.save()         except page.doesnotexist:              page(url=request.path).save()           response = get_response(request)         if p:             response.content += "this page has been seen {0} times.".format(p.nb_visits)          return response      return middleware 

and voilĂ .

using django

here's example of middleware, update counter each visit of page (admit page model exists 2 field : url , nb_visits)

class statsmiddleware(object):     def process_view(self, request, view_func, view_args, view_kwargs):         try:             p = page.objects.get(url=request.path)             p.nb_visits += 1             p.save()         except page.doesnotexist:              page(url=request.path).save()       def process_response(self, request, response):         if response.status_code == 200:             p = page.objects.get(url=request.path)             # let's add our info after html response (dirty, yeah know)             response.content += u"this page has been seen {0} times.".format(p.nb_visits)         return response 

hopes :)


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -