'Python Django 1.6 execute function for every request before getting to view

I'm writing some API functionality for my project using Python 3.4 and Django 1.6.

All functionality works fine, but I want execute one function for all that kind of requests.
For Example: I have following urls.py file in my API application in Django project

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',

    url(r'^getposts', 'Postigs.views.get_posts', name='getPosts'),
    url(r'^addpost', 'Postigs.views.add_post', name='addPost'),
    url(r'^addcomment', 'Postigs.views.add_comment', name='addComment'),
)


And views.py for that URL requests handling.

So is it possible to execute some function for Example:

def pre_execute(request):
    do_something_before_view_function()


I've worked before with many PHP frameworks , there are always some pre_execute() function ... also I've worked with ASP.NET MVC , Node.js Express.js , and all have that function which is firing before request action.

I don't believe that Django didn't have it , but I can't find how implement that functionality.

Thanks.



Solution 1:[1]

Middlewares are what you want: https://docs.djangoproject.com/en/dev/topics/http/middleware/

example middleware: https://github.com/django/django/blob/master/django/middleware/common.py

Solution 2:[2]

Like iskorum mentioned above, Middlewares is the answer. Or there is also a chance that you are looking for View Decorators. Here is the link https://docs.djangoproject.com/en/dev/topics/http/decorators/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 iskorum
Solution 2 Natnael A.