0

Here is my code looks like :-

url.py file :-

from rest_framework import routers
from view_user import user_signup,user_login

router = routers.DefaultRouter()

urlpatterns = [
   url(r'^api/v1/user_signup',csrf_exempt(user_signup)),
   url(r'^api/v1/user_login',csrf_exempt(user_login))
]

view_user.py file:-

def user_signup(request):
    try:
        if request.method == 'POST':
            json_data = json.loads(request.body)
        return JsonResponse(result, safe=False)
    except Exception as e:
                logger.error("at method user : %s", e)

So, when I call the url:- http://myserver/api/v1/user_signup it goes to "user_signup" method of view_user.py file.

But what I want is I should be able validate my request before it goes to the user_signup method.

I want this validation for all the requests that comes to my server for all methods (ex:- user_signup,user_login ...) before it goes to respective methods.

RejeeshChandran
  • 4,168
  • 3
  • 21
  • 32
Vinay
  • 705
  • 2
  • 7
  • 22

1 Answers1

2

Annotate the concerned views with a decorator that contains the logic you want to execute before the views are called.

See Python - Decorators for a head start.

And How to write a custom decorator in django?

If you want to do this on all requests, regardless of the associated view, then you should consider writing a middleware. See how to setup custom middleware in django

Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • Thanks alot for your suggestion. But decorators I have to add for every method. Is there a way I can validate all request that comes to Django, before I forward to the respective methods. – Vinay Sep 16 '16 at 13:23
  • 1
    @Vinay You should consider writing a [middleware](https://docs.djangoproject.com/en/1.10/topics/http/middleware/). See [how to setup custom middleware in django](http://stackoverflow.com/questions/18322262/how-to-setup-custom-middleware-in-django) – Moses Koledoye Sep 16 '16 at 13:24
  • 1
    Middleware is definitely the answer. One quick note on them. In v 1.10 there is a new style for creating custom Middleware that is not backwards compatible depending upon your settings.py. If you have MIDDLEWARE=(...) then you need a new style. – Adam Hopkins Sep 16 '16 at 14:36