Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.shortcuts import render
- # Create your views here.
- from django.contrib.auth import authenticate
- from rest_framework import status
- from rest_framework.response import Response
- from rest_framework.permissions import AllowAny
- from rest_framework.authtoken.models import Token
- from rest_framework.decorators import api_view, permission_classes
- from django.views.decorators.csrf import csrf_exempt
- from datetime import datetime
- @csrf_exempt
- @api_view(["GET"])
- def sample_login(request):
- data = {'sample_data': 123}
- return Response(data, status=status.HTTP_200_OK)
- @csrf_exempt
- @api_view(["POST"])
- @permission_classes((AllowAny,))
- def login(request):
- username = request.data.get("username")
- password = request.data.get("password")
- if username is None or password is None:
- return Response({'error': 'Please provide both username and password'}, status=status.HTTP_400_BAD_REQUEST)
- user = authenticate(username=username, password=password)
- if not user:
- return Response({'error': 'Invalid Credentials'}, status=status.HTTP_404_NOT_FOUND)
- token, _ = Token.objects.get_or_create(user=user)
- # token will need to be stored on the client side in the session, or in local storage and send the token in the
- # header as authorization with every API call
- return Response({'token': token.key}, status=status.HTTP_200_OK)
- # the following code shows how to store the token in the header for a request call
- # url = 'http://127.0.0.1:8000/hello/'
- # headers = {'Authorization': 'Token 9054f7aa9305e012b3c2300408c3dfdf390fcddf'}
- # r = requests.get(url, headers=headers)
- # check that server is working
- @api_view(['GET'])
- def index(request):
- date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
- message = "server is live, current time is:"
- return Response(data=message + date, status=status.HTTP_200_OK)
- # from django.contrib.auth import authenticate
- # user = authenticate(username='john', password='secret')
- # if user is not None:
- # # A backend authenticated the credentials
- # else:
- # # No backend authenticated the credentials
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement