Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. from django.shortcuts import render
  2.  
  3. # Create your views here.
  4.  
  5. from django.contrib.auth import authenticate
  6. from rest_framework import status
  7. from rest_framework.response import Response
  8. from rest_framework.permissions import AllowAny
  9. from rest_framework.authtoken.models import Token
  10. from rest_framework.decorators import api_view, permission_classes
  11. from django.views.decorators.csrf import csrf_exempt
  12.  
  13. from datetime import datetime
  14.  
  15.  
  16. @csrf_exempt
  17. @api_view(["GET"])
  18. def sample_login(request):
  19. data = {'sample_data': 123}
  20. return Response(data, status=status.HTTP_200_OK)
  21.  
  22.  
  23. @csrf_exempt
  24. @api_view(["POST"])
  25. @permission_classes((AllowAny,))
  26. def login(request):
  27. username = request.data.get("username")
  28. password = request.data.get("password")
  29. if username is None or password is None:
  30. return Response({'error': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST)
  31. user = authenticate(username=username, password=password)
  32. if not user:
  33. return Response({'error': 'Invalid Credentials'}, status=status.HTTP_404_NOT_FOUND)
  34. token, _ = Token.objects.get_or_create(user=user)
  35.  
  36. # token will need to be stored on the client side in the session, or in local storage and send the token in the
  37. # header as authorization with every API call
  38. return Response({'token': token.key}, status=status.HTTP_200_OK)
  39.  
  40. # the following code shows how to store the token in the header for a request call
  41. # url = 'http://127.0.0.1:8000/hello/'
  42. # headers = {'Authorization': 'Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'}
  43. # r = requests.get(url, headers=headers)
  44.  
  45. # check that server is working
  46. @api_view(['GET'])
  47. def index(request):
  48. date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
  49. message = "server is live, current time is:"
  50. return Response(data=message + date, status=status.HTTP_200_OK)
  51.  
  52. # from django.contrib.auth import authenticate
  53. # user = authenticate(username='john', password='secret')
  54. # if user is not None:
  55. # # A backend authenticated the credentials
  56. # else:
  57. # # No backend authenticated the credentials
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement