Exemplo n.º 1
0
    def open_upload_stream_with_id(
        self,
        file_id: Any,
        filename: str,
        chunk_size_bytes: Optional[int] = None,
        metadata: Optional[Mapping[str, Any]] = None,
        session: Optional[ClientSession] = None,
    ) -> GridIn:
        """Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the file id and filename, and can choose to add
        any additional information in the metadata field of the file document
        or modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_in = fs.open_upload_stream_with_id(
                ObjectId(),
                "test_file",
                chunk_size_bytes=4,
                metadata={"contentType": "text/plain"})
          grid_in.write("data I want to store!")
          grid_in.close()  # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `file_id`: The id to use for this file. The id must not have
            already been used for another file.
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        """
        validate_string("filename", filename)

        opts = {
            "_id": file_id,
            "filename": filename,
            "chunk_size": (
                chunk_size_bytes if chunk_size_bytes is not None else self._chunk_size_bytes
            ),
        }
        if metadata is not None:
            opts["metadata"] = metadata

        return GridIn(self._collection, session=session, **opts)
Exemplo n.º 2
0
    def open_download_stream_by_name(self,
                                     filename,
                                     revision=-1,
                                     session=None):
        """Opens a Stream from which the application can read the contents of
        `filename` and optional `revision`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_out = fs.open_download_stream_by_name("test_file")
          contents = grid_out.read()

        Returns an instance of :class:`~gridfs.grid_file.GridOut`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        Raises :exc:`~ValueError` filename is not a string.

        :Parameters:
          - `filename`: The name of the file to read from.
          - `revision` (optional): Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        :Note: Revision numbers are defined as follows:

          - 0 = the original stored file
          - 1 = the first revision
          - 2 = the second revision
          - etc...
          - -2 = the second most recent revision
          - -1 = the most recent revision

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        """
        validate_string("filename", filename)

        query = {"filename": filename}

        cursor = self._files.find(query, session=session)
        if revision < 0:
            skip = abs(revision) - 1
            cursor.limit(-1).skip(skip).sort("uploadDate", DESCENDING)
        else:
            cursor.limit(-1).skip(revision).sort("uploadDate", ASCENDING)
        try:
            grid_file = next(cursor)
            return GridOut(self._collection,
                           file_document=grid_file,
                           session=session)
        except StopIteration:
            raise NoFile("no version %d for filename %r" %
                         (revision, filename))
Exemplo n.º 3
0
    def open_upload_stream_with_id(
            self, file_id, filename, chunk_size_bytes=None, metadata=None,
            session=None):
        """Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the file id and filename, and can choose to add
        any additional information in the metadata field of the file document
        or modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_in = fs.open_upload_stream_with_id(
                ObjectId(),
                "test_file",
                chunk_size_bytes=4,
                metadata={"contentType": "text/plain"})
          grid_in.write("data I want to store!")
          grid_in.close()  # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `file_id`: The id to use for this file. The id must not have
            already been used for another file.
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        """
        validate_string("filename", filename)

        opts = {"_id": file_id,
                "filename": filename,
                "chunk_size": (chunk_size_bytes if chunk_size_bytes
                               is not None else self._chunk_size_bytes)}
        if metadata is not None:
            opts["metadata"] = metadata

        return GridIn(
            self._collection,
            session=session,
            disable_md5=self._disable_md5,
            **opts)
Exemplo n.º 4
0
    def open_download_stream_by_name(self, filename, revision=-1, session=None):
        """Opens a Stream from which the application can read the contents of
        `filename` and optional `revision`.

        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_out = fs.open_download_stream_by_name("test_file")
          contents = grid_out.read()

        Returns an instance of :class:`~gridfs.grid_file.GridOut`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.

        Raises :exc:`~ValueError` filename is not a string.

        :Parameters:
          - `filename`: The name of the file to read from.
          - `revision` (optional): Which revision (documents with the same
            filename and different uploadDate) of the file to retrieve.
            Defaults to -1 (the most recent revision).
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`

        :Note: Revision numbers are defined as follows:

          - 0 = the original stored file
          - 1 = the first revision
          - 2 = the second revision
          - etc...
          - -2 = the second most recent revision
          - -1 = the most recent revision

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        """
        validate_string("filename", filename)

        query = {"filename": filename}

        cursor = self._files.find(query, session=session)
        if revision < 0:
            skip = abs(revision) - 1
            cursor.limit(-1).skip(skip).sort("uploadDate", DESCENDING)
        else:
            cursor.limit(-1).skip(revision).sort("uploadDate", ASCENDING)
        try:
            grid_file = next(cursor)
            return GridOut(
                self._collection, file_document=grid_file, session=session)
        except StopIteration:
            raise NoFile(
                "no version %d for filename %r" % (revision, filename))
Exemplo n.º 5
0
    def open_upload_stream(self,
                           filename,
                           chunk_size_bytes=None,
                           metadata=None):
        """Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the filename, and can choose to add any
        additional information in the metadata field of the file document or
        modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_in, file_id = fs.open_upload_stream(
                "test_file", chunk_size_bytes=4,
                metadata={"contentType": "text/plain"})
          grid_in.write("data I want to store!")
          grid_in.close()  # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn`.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        """
        validate_string("filename", filename)

        opts = {
            "filename":
            filename,
            "chunk_size": (chunk_size_bytes if chunk_size_bytes is not None
                           else self._chunk_size_bytes)
        }
        if metadata is not None:
            opts["metadata"] = metadata

        return GridIn(self._collection, **opts)
Exemplo n.º 6
0
    def open_upload_stream(self, filename, chunk_size_bytes=None,
                           metadata=None):
        """Opens a Stream that the application can write the contents of the
        file to.

        The user must specify the filename, and can choose to add any
        additional information in the metadata field of the file document or
        modify the chunk size.
        For example::

          my_db = MongoClient().test
          fs = GridFSBucket(my_db)
          grid_in, file_id = fs.open_upload_stream(
                "test_file", chunk_size_bytes=4,
                metadata={"contentType": "text/plain"})
          grid_in.write("data I want to store!")
          grid_in.close()  # uploaded on close

        Returns an instance of :class:`~gridfs.grid_file.GridIn` and the _id
        of the file to upload.

        Raises :exc:`~gridfs.errors.NoFile` if no such version of
        that file exists.
        Raises :exc:`~ValueError` if `filename` is not a string.

        :Parameters:
          - `filename`: The name of the file to upload.
          - `chunk_size_bytes` (options): The number of bytes per chunk of this
            file. Defaults to the chunk_size_bytes in :class:`GridFSBucket`.
          - `metadata` (optional): User data for the 'metadata' field of the
            files collection document. If not provided the metadata field will
            be omitted from the files collection document.
        """
        validate_string("filename", filename)

        opts = {"filename": filename,
                "chunk_size": (chunk_size_bytes if chunk_size_bytes
                               is not None else self._chunk_size_bytes)}
        if metadata is not None:
            opts["metadata"] = metadata

        gin = GridIn(self._collection, **opts)
        return gin, gin._id
Exemplo n.º 7
0
 def __init__(self,
              locale,
              caseLevel=None,
              caseFirst=None,
              strength=None,
              numericOrdering=None,
              alternate=None,
              maxVariable=None,
              normalization=None,
              backwards=None,
              **kwargs):
     locale = common.validate_string('locale', locale)
     self.__document = {'locale': locale}
     if caseLevel is not None:
         self.__document['caseLevel'] = common.validate_boolean(
             'caseLevel', caseLevel)
     if caseFirst is not None:
         self.__document['caseFirst'] = common.validate_string(
             'caseFirst', caseFirst)
     if strength is not None:
         self.__document['strength'] = common.validate_integer(
             'strength', strength)
     if numericOrdering is not None:
         self.__document['numericOrdering'] = common.validate_boolean(
             'numericOrdering', numericOrdering)
     if alternate is not None:
         self.__document['alternate'] = common.validate_string(
             'alternate', alternate)
     if maxVariable is not None:
         self.__document['maxVariable'] = common.validate_string(
             'maxVariable', maxVariable)
     if normalization is not None:
         self.__document['normalization'] = common.validate_boolean(
             'normalization', normalization)
     if backwards is not None:
         self.__document['backwards'] = common.validate_boolean(
             'backwards', backwards)
     self.__document.update(kwargs)
Exemplo n.º 8
0
 def __init__(self,
              locale: str,
              caseLevel: Optional[bool] = None,
              caseFirst: Optional[str] = None,
              strength: Optional[int] = None,
              numericOrdering: Optional[bool] = None,
              alternate: Optional[str] = None,
              maxVariable: Optional[str] = None,
              normalization: Optional[bool] = None,
              backwards: Optional[bool] = None,
              **kwargs: Any) -> None:
     locale = common.validate_string("locale", locale)
     self.__document: Dict[str, Any] = {"locale": locale}
     if caseLevel is not None:
         self.__document["caseLevel"] = common.validate_boolean(
             "caseLevel", caseLevel)
     if caseFirst is not None:
         self.__document["caseFirst"] = common.validate_string(
             "caseFirst", caseFirst)
     if strength is not None:
         self.__document["strength"] = common.validate_integer(
             "strength", strength)
     if numericOrdering is not None:
         self.__document["numericOrdering"] = common.validate_boolean(
             "numericOrdering", numericOrdering)
     if alternate is not None:
         self.__document["alternate"] = common.validate_string(
             "alternate", alternate)
     if maxVariable is not None:
         self.__document["maxVariable"] = common.validate_string(
             "maxVariable", maxVariable)
     if normalization is not None:
         self.__document["normalization"] = common.validate_boolean(
             "normalization", normalization)
     if backwards is not None:
         self.__document["backwards"] = common.validate_boolean(
             "backwards", backwards)
     self.__document.update(kwargs)
Exemplo n.º 9
0
 def __init__(self, locale,
              caseLevel=None,
              caseFirst=None,
              strength=None,
              numericOrdering=None,
              alternate=None,
              maxVariable=None,
              normalization=None,
              backwards=None,
              **kwargs):
     locale = common.validate_string('locale', locale)
     self.__document = {'locale': locale}
     if caseLevel is not None:
         self.__document['caseLevel'] = common.validate_boolean(
             'caseLevel', caseLevel)
     if caseFirst is not None:
         self.__document['caseFirst'] = common.validate_string(
             'caseFirst', caseFirst)
     if strength is not None:
         self.__document['strength'] = common.validate_integer(
             'strength', strength)
     if numericOrdering is not None:
         self.__document['numericOrdering'] = common.validate_boolean(
             'numericOrdering', numericOrdering)
     if alternate is not None:
         self.__document['alternate'] = common.validate_string(
             'alternate', alternate)
     if maxVariable is not None:
         self.__document['maxVariable'] = common.validate_string(
             'maxVariable', maxVariable)
     if normalization is not None:
         self.__document['normalization'] = common.validate_boolean(
             'normalization', normalization)
     if backwards is not None:
         self.__document['backwards'] = common.validate_boolean(
             'backwards', backwards)
     self.__document.update(kwargs)