Beispiel #1
0
    def __validate(self, oid):
        """Validate and use the given id for this ObjectId.

        Raises TypeError if id is not an instance of
        (:class:`basestring` (:class:`str` or :class:`bytes`
        in python 3), ObjectId) and InvalidId if it is not a
        valid ObjectId.

        :Parameters:
          - `oid`: a valid ObjectId
        """
        if isinstance(oid, ObjectId):
            self.__id = oid.__id
        elif isinstance(oid, string_types):
            if len(oid) == 12:
                if isinstance(oid, binary_type):
                    self.__id = oid
                else:
                    raise InvalidId("%s is not a valid ObjectId" % oid)
            elif len(oid) == 24:
                try:
                    self.__id = bytes_from_hex(oid)
                except (TypeError, ValueError):
                    raise InvalidId("%s is not a valid ObjectId" % oid)
            else:
                raise InvalidId("%s is not a valid ObjectId" % oid)
        else:
            raise TypeError(
                "id must be an instance of (%s, %s, ObjectId), "
                "not %s" %
                (binary_type.__name__, text_type.__name__, type(oid)))
Beispiel #2
0
    def __validate(self, oid):
        """Validate and use the given id for this ObjectId.

        Raises TypeError if id is not an instance of
        (:class:`basestring` (:class:`str` or :class:`bytes`
        in python 3), ObjectId) and InvalidId if it is not a
        valid ObjectId.

        :Parameters:
          - `oid`: a valid ObjectId
        """
        if isinstance(oid, ObjectId):
            self.__id = oid.binary
        # bytes or unicode in python 2, str in python 3
        elif isinstance(oid, string_type):
            if len(oid) == 24:
                try:
                    self.__id = bytes_from_hex(oid)
                except (TypeError, ValueError):
                    _raise_invalid_id(oid)
            else:
                _raise_invalid_id(oid)
        else:
            raise TypeError("id must be an instance of (bytes, %s, ObjectId), "
                            "not %s" % (text_type.__name__, type(oid)))
 def str2hex(jsn):
     for key, val in jsn.items():
         if key in ("data", "source", "result"):
             if "$hex" in val:
                 jsn[key] = Binary(bytes_from_hex(val['$hex']))
         if isinstance(jsn[key], dict):
             str2hex(jsn[key])
         if isinstance(jsn[key], list):
             for k in jsn[key]:
                 str2hex(k)
 def str2hex(jsn):
     for key, val in jsn.items():
         if key in ("data", "source", "result"):
             if "$hex" in val:
                 jsn[key] = Binary(bytes_from_hex(val['$hex']))
         if isinstance(jsn[key], dict):
             str2hex(jsn[key])
         if isinstance(jsn[key], list):
             for k in jsn[key]:
                 str2hex(k)