Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Wraps the best available JSON implementation available in a common
  2. interface"""
  3. import sys
  4. VERSION = (0, 3, 3)
  5. __version__ = ".".join(map(str, VERSION[0:3])) + "".join(VERSION[3:])
  6. __author__ = "Rune Halvorsen"
  7. __contact__ = "runefh@gmail.com"
  8. __homepage__ = "http://bitbucket.org/runeh/anyjson/"
  9. __docformat__ = "restructuredtext"
  10. # -eof meta-
  11. #: The json implementation object. This is probably not useful to you,
  12. #: except to get the name of the implementation in use. The name is
  13. #: available through ``implementation.name``.
  14. implementation = None
  15. # json.loads does not support buffer() objects,
  16. # so we load() and StringIO instead, and it won't copy.
  17. if sys.version_info[0] == 3:
  18. from io import StringIO
  19. else:
  20. try:
  21. from io import StringIO # noqa
  22. except ImportError:
  23. from io import StringIO # noqa
  24. #: List of known json modules, and the names of their loads/dumps
  25. #: methods, as well as the exceptions they throw. Exception can be either
  26. #: an exception class or a string.
  27. _modules = [("yajl", "dumps", TypeError, "loads", ValueError, "load"),
  28. ("jsonlib2", "write", "WriteError", "read", "ReadError", None),
  29. ("jsonlib", "write", "WriteError", "read", "ReadError", None),
  30. ("simplejson", "dumps", TypeError, "loads", ValueError, "load"),
  31. ("json", "dumps", TypeError, "loads", ValueError, "load"),
  32. ("django.utils.simplejson", "dumps", TypeError, "loads", ValueError, "load"),
  33. ("cjson", "encode", "EncodeError", "decode", "DecodeError", None)
  34. ]
  35. _fields = ("modname", "encoder", "encerror",
  36. "decoder", "decerror", "filedecoder")
  37. class _JsonImplementation(object):
  38. """Incapsulates a JSON implementation"""
  39. def __init__(self, modspec):
  40. modinfo = dict(list(zip(_fields, modspec)))
  41. if modinfo["modname"] == "cjson":
  42. import warnings
  43. warnings.warn("cjson is deprecated! See http://pypi.python.org/pypi/python-cjson/1.0.5", DeprecationWarning)
  44. # No try block. We want importerror to end up at caller
  45. module = self._attempt_load(modinfo["modname"])
  46. self.implementation = modinfo["modname"]
  47. self._encode = getattr(module, modinfo["encoder"])
  48. self._decode = getattr(module, modinfo["decoder"])
  49. fdec = modinfo["filedecoder"]
  50. self._filedecode = fdec and getattr(module, fdec)
  51. self._encode_error = modinfo["encerror"]
  52. self._decode_error = modinfo["decerror"]
  53. if isinstance(modinfo["encerror"], str):
  54. self._encode_error = getattr(module, modinfo["encerror"])
  55. if isinstance(modinfo["decerror"], str):
  56. self._decode_error = getattr(module, modinfo["decerror"])
  57. self.name = modinfo["modname"]
  58. def __repr__(self):
  59. return "<_JsonImplementation instance using %s>" % self.name
  60. def _attempt_load(self, modname):
  61. """Attempt to load module name modname, returning it on success,
  62. throwing ImportError if module couldn't be imported"""
  63. __import__(modname)
  64. return sys.modules[modname]
  65. def dumps(self, data):
  66. """Serialize the datastructure to json. Returns a string. Raises
  67. TypeError if the object could not be serialized."""
  68. try:
  69. return self._encode(data)
  70. except self._encode_error as exc:
  71. raise TypeError(TypeError(*exc.args)).with_traceback(sys.exc_info()[2])
  72. serialize = dumps
  73. def loads(self, s):
  74. """deserialize the string to python data types. Raises
  75. ValueError if the string could not be parsed."""
  76. # uses StringIO to support buffer objects.
  77. try:
  78. if self._filedecode and not isinstance(s, str):
  79. return self._filedecode(StringIO(s))
  80. return self._decode(s)
  81. except self._decode_error as exc:
  82. raise ValueError(ValueError(*exc.args)).with_traceback(sys.exc_info()[2])
  83. deserialize = loads
  84. def force_implementation(modname):
  85. """Forces anyjson to use a specific json module if it's available"""
  86. global implementation
  87. for name, spec in [(e[0], e) for e in _modules]:
  88. if name == modname:
  89. implementation = _JsonImplementation(spec)
  90. return
  91. raise ImportError("No module named: %s" % modname)
  92. if __name__ == "__main__":
  93. # If run as a script, we do nothing but print an error message.
  94. # We do NOT try to load a compatible module because that may throw an
  95. # exception, which renders the package uninstallable with easy_install
  96. # (It trys to execfile the script when installing, to make sure it works)
  97. print("Running anyjson as a stand alone script is not supported")
  98. sys.exit(1)
  99. else:
  100. for modspec in _modules:
  101. try:
  102. implementation = _JsonImplementation(modspec)
  103. break
  104. except ImportError:
  105. pass
  106. else:
  107. raise ImportError("No supported JSON module found")
  108. def loads(value):
  109. """Serialize the object to JSON."""
  110. return implementation.loads(value)
  111. deserialize = loads # compat
  112. def dumps(value):
  113. """Deserialize JSON-encoded object to a Python object."""
  114. return implementation.dumps(value)
  115. serialize = dumps