How can i route my URL to a common method before passing to actual view in Django
<p>Here is my code looks like :-</p>

<p>url.py file :-</p>

<pre><code>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))
]
</code></pre>

<p>view_user.py file:-</p>

<pre><code>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)
</code></pre>

<p>So, when I call the url:- <a href="http://myserver/api/v1/user_signup" rel="nofollow">http://myserver/api/v1/user_signup</a> 
it goes to "user_signup" method of view_user.py file. </p>

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

<p>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.</p>

<p>Annotate the concerned views with a <a href="https://wiki.python.org/moin/PythonDecorators" rel="nofollow">decorator</a> that contains the logic you want to execute before the views are called.</p>

<p>See <a href="http://stackoverflow.com/questions/20945366/python-decorators">Python - Decorators</a> for a head start.</p>

<p>And <a href="http://stackoverflow.com/questions/5469159/how-to-write-a-custom-decorator-in-django">How to write a custom decorator in django?</a></p>

<p>If you want to do this on all requests, regardless of the associated view, then you should consider writing a <a href="https://docs.djangoproject.com/en/1.10/topics/http/middleware/" rel="nofollow">middleware</a>. See <a href="http://stackoverflow.com/questions/18322262/how-to-setup-custom-middleware-in-django">how to setup custom middleware in django</a></p>

python django django-models django-views django-rest-framework