Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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.

like image 882
Tigran Bayburtsyan Avatar asked Dec 08 '22 07:12

Tigran Bayburtsyan


1 Answers

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

like image 191
iskorum Avatar answered Dec 11 '22 08:12

iskorum