views.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import json
  2. from functools import partial
  3. from rest_framework.renderers import JSONRenderer
  4. from rest_framework import status
  5. from rest_framework.viewsets import ModelViewSet
  6. from rest_framework.response import Response
  7. from rest_framework.generics import RetrieveAPIView
  8. from core.renderers import CSSRenderer
  9. from core import models, serializers, utils
  10. class FontViewSet(ModelViewSet):
  11. http_method_names = ['get']
  12. lookup_field = 'name'
  13. queryset = models.Font.objects.prefetch_related(
  14. 'files'
  15. ).all()
  16. serializer_class = serializers.FontSerializer
  17. class FontCSSView(RetrieveAPIView):
  18. queryset = models.Font.objects.prefetch_related(
  19. 'files',
  20. 'files__unicode_ranges'
  21. )
  22. lookup_field = 'name'
  23. serializer_class = partial(
  24. serializers.FontSerializer,
  25. expand=('files', 'files.unicode_ranges')
  26. )
  27. renderer_classes = (CSSRenderer, JSONRenderer)
  28. def retrieve(self, request, *args, **kwargs):
  29. font = self.get_object()
  30. query = request.GET
  31. query_s = serializers.FontCSSQuerySerializer(
  32. data=query,
  33. context=self.get_serializer_context()
  34. )
  35. if not query_s.is_valid():
  36. return Response(
  37. json.dumps(query_s.errors),
  38. content_type='application/json'
  39. )
  40. serializer = self.get_serializer(font)
  41. data = serializer.data
  42. body = query_s.data
  43. name = body['name']
  44. style = body['style']
  45. weight = body['weight']
  46. try:
  47. css = utils.font_to_css(data, name, style, weight)
  48. except ValueError as e:
  49. return Response(
  50. json.dumps({
  51. 'detail': str(e)
  52. }),
  53. status=status.HTTP_400_BAD_REQUEST,
  54. content_type='application/json'
  55. )
  56. return Response(css)