/cartoview/app_manager/serializers.py

https://github.com/cartologic/cartoview · Python · 74 lines · 50 code · 16 blank · 8 comment · 8 complexity · a7ea1b7fdc224dc481ec1388a4dde1a7 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. from __future__ import (absolute_import, division, print_function,
  3. unicode_literals)
  4. import json
  5. from django.template.loader import render_to_string
  6. from django.utils import six
  7. from django.utils.encoding import force_text
  8. from future import standard_library
  9. from tastypie.exceptions import UnsupportedFormat
  10. from tastypie.serializers import Serializer
  11. standard_library.install_aliases()
  12. class HTMLSerializer(Serializer):
  13. def to_html(self, data, options=None):
  14. options = options or {}
  15. data = self.to_simple(data, options)
  16. json_data = json.dumps(
  17. data, cls=json.JSONEncoder, indent=4, sort_keys=True)
  18. return render_to_string('app_manager/rest_api/base.html',
  19. {'json_data': json_data})
  20. class MultipartFormSerializer(HTMLSerializer):
  21. def __init__(self, *args, **kwargs):
  22. self.content_types['file_upload'] = 'multipart/form-data'
  23. self.formats.append('file_upload')
  24. super(type(self), self).__init__(*args, **kwargs)
  25. def from_file_upload(self, data, options=None):
  26. request = options['request']
  27. deserialized = {}
  28. for k in request.POST:
  29. deserialized[str(k)] = str(request.POST[k])
  30. # for k in request.FILES:
  31. # deserialized[str(k)] = request.FILES[k]
  32. return deserialized
  33. # add request param to extract files
  34. def deserialize(self, content, request=None, format='application/json'):
  35. """
  36. Given some data and a format, calls the correct method to deserialize
  37. the data and returns the result.
  38. """
  39. desired_format = None
  40. format = format.split(';')[0]
  41. for short_format, long_format in list(self.content_types.items()):
  42. if format == long_format:
  43. if hasattr(self, "from_%s" % short_format):
  44. desired_format = short_format
  45. break
  46. if desired_format is None:
  47. raise UnsupportedFormat(
  48. "The format indicated '%s' had no available deserialization\
  49. method. Please check your ``formats`` and ``content_types``\
  50. on your Serializer." %
  51. format)
  52. if isinstance(content,
  53. six.binary_type) and desired_format != 'file_upload':
  54. content = force_text(content)
  55. deserialized = getattr(self, "from_%s" % desired_format)(content, {
  56. 'request': request
  57. })
  58. return deserialized