How to make Restful Login API in python
Posted By : Rajat khurana | 08-Apr-2017
Hi everyone,
Here you learn how to create a restful API in Django. For making a login API in Django , you need to use Django authentication system , which will authenticate username and password from database. To use Django authentication system, you need to import this:
from django.contrib.auth import authenticate
From mporting this, you used authenticate function of Django auth module . See in code this line:
userobj = authenticate(username=uname, password=passw);
This line give authenticate username and password . To make a Login API in Python you need to create a class in handler.py and import different module you can use in API. Here is example of class :
class LoginHandler(BaseHandler):
"""
Interface for login API
TODO: remove target fields
"""
model = User
allowed_methods = ('POST',)
@staticmethod
def resource_uri():
return ('api3_login_handler', [])
@log_request
def create(self, request):
"""
Returns authentication token
"""
try: data = simplejson.loads(request.raw_post_data)
except:
msg = {'message':"Username or Password Not Present", 'response': { 'user' : " " } }
return sendResponse("BAD_REQUEST",msg)
uname = data.get('username', '')
passw = data.get('password', '')
if(uname == ""):
msg = {'message':"The server did not understand the request",'status': "BAD_REQUEST", 'response': { 'user' : " " } }
return sendResponse("BAD_REQUEST",msg);
if(passw == ""):
msg = {'message':"The server did not understand the request",'response': { 'user' : " " } }
return sendResponse("BAD_REQUEST",msg);
userobj = authenticate(username=uname, password=passw);
if user is None:
error = True;
msg = { 'error': error, 'message':"Authentication Failed", 'response': { 'user' : " " } , 'status': "BAD_REQUEST", }
return sendResponse("FORBIDDEN",msg)
else:
unique_token = uuid.uuid4()
unique_token = str(unique_token);
error = False
profile = {}
profile["id"] = userobj.id
profile["token"] = unique_token;
profile['username'] = userobj.uname;
profile['useremail']= user_email;
message = { 'error': error, 'message':"Authentication Successfully", 'response': { 'user' : profile } , 'status': "ACCEPTED", }
return sendResponse("ALL_OK",message)
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajat khurana
Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.