views.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from rest_framework import parsers, renderers
  2. from rest_framework.authtoken.models import Token
  3. from rest_framework.authtoken.serializers import AuthTokenSerializer
  4. from rest_framework.compat import coreapi, coreschema
  5. from rest_framework.response import Response
  6. from rest_framework.schemas import ManualSchema
  7. from rest_framework.schemas import coreapi as coreapi_schema
  8. from rest_framework.views import APIView
  9. class ObtainAuthToken(APIView):
  10. throttle_classes = ()
  11. permission_classes = ()
  12. parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
  13. renderer_classes = (renderers.JSONRenderer,)
  14. serializer_class = AuthTokenSerializer
  15. if coreapi_schema.is_enabled():
  16. schema = ManualSchema(
  17. fields=[
  18. coreapi.Field(
  19. name="username",
  20. required=True,
  21. location='form',
  22. schema=coreschema.String(
  23. title="Username",
  24. description="Valid username for authentication",
  25. ),
  26. ),
  27. coreapi.Field(
  28. name="password",
  29. required=True,
  30. location='form',
  31. schema=coreschema.String(
  32. title="Password",
  33. description="Valid password for authentication",
  34. ),
  35. ),
  36. ],
  37. encoding="application/json",
  38. )
  39. def get_serializer_context(self):
  40. return {
  41. 'request': self.request,
  42. 'format': self.format_kwarg,
  43. 'view': self
  44. }
  45. def get_serializer(self, *args, **kwargs):
  46. kwargs['context'] = self.get_serializer_context()
  47. return self.serializer_class(*args, **kwargs)
  48. def post(self, request, *args, **kwargs):
  49. serializer = self.get_serializer(data=request.data)
  50. serializer.is_valid(raise_exception=True)
  51. user = serializer.validated_data['user']
  52. token, created = Token.objects.get_or_create(user=user)
  53. return Response({'token': token.key})
  54. obtain_auth_token = ObtainAuthToken.as_view()