00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 """Tools for representing BSON binary data.
00016 """
00017
00018 BINARY_SUBTYPE = 0
00019 """BSON binary subtype for binary data.
00020
00021 This is becomming the default subtype and should be the most commonly
00022 used.
00023
00024 .. versionadded:: 1.5
00025 """
00026
00027 FUNCTION_SUBTYPE = 1
00028 """BSON binary subtype for functions.
00029
00030 .. versionadded:: 1.5
00031 """
00032
00033 OLD_BINARY_SUBTYPE = 2
00034 """Old BSON binary subtype for binary data.
00035
00036 This is still the default subtype, but that is changing to
00037 :data:`BINARY_SUBTYPE`.
00038
00039 .. versionadded:: 1.7
00040 """
00041
00042 UUID_SUBTYPE = 3
00043 """BSON binary subtype for a UUID.
00044
00045 :class:`uuid.UUID` instances will automatically be encoded
00046 by :mod:`bson` using this subtype.
00047
00048 .. versionadded:: 1.5
00049 """
00050
00051 MD5_SUBTYPE = 5
00052 """BSON binary subtype for an MD5 hash.
00053
00054 .. versionadded:: 1.5
00055 """
00056
00057 USER_DEFINED_SUBTYPE = 128
00058 """BSON binary subtype for any user defined structure.
00059
00060 .. versionadded:: 1.5
00061 """
00062
00063
00064 class Binary(str):
00065 """Representation of BSON binary data.
00066
00067 This is necessary because we want to represent Python strings as
00068 the BSON string type. We need to wrap binary data so we can tell
00069 the difference between what should be considered binary data and
00070 what should be considered a string when we encode to BSON.
00071
00072 Raises TypeError if `data` is not an instance of str or `subtype`
00073 is not an instance of int. Raises ValueError if `subtype` is not
00074 in [0, 256).
00075
00076 :Parameters:
00077 - `data`: the binary data to represent
00078 - `subtype` (optional): the `binary subtype
00079 <http://bsonspec.org/#/specification>`_
00080 to use
00081 """
00082
00083 def __new__(cls, data, subtype=OLD_BINARY_SUBTYPE):
00084 if not isinstance(data, str):
00085 raise TypeError("data must be an instance of str")
00086 if not isinstance(subtype, int):
00087 raise TypeError("subtype must be an instance of int")
00088 if subtype >= 256 or subtype < 0:
00089 raise ValueError("subtype must be contained in [0, 256)")
00090 self = str.__new__(cls, data)
00091 self.__subtype = subtype
00092 return self
00093
00094 @property
00095 def subtype(self):
00096 """Subtype of this binary data.
00097 """
00098 return self.__subtype
00099
00100 def __eq__(self, other):
00101 if isinstance(other, Binary):
00102 return (self.__subtype, str(self)) == (other.subtype, str(other))
00103
00104
00105
00106 return False
00107
00108 def __ne__(self, other):
00109 return not self == other
00110
00111 def __repr__(self):
00112 return "Binary(%s, %s)" % (str.__repr__(self), self.__subtype)