@@ -109,11 +109,8 @@ def put(self, data: Any, **kwargs: Any) -> Any:
109109
110110 Equivalent to doing::
111111
112- try:
113- f = new_file(**kwargs)
112+ with fs.new_file(**kwargs) as f:
114113 f.write(data)
115- finally:
116- f.close()
117114
118115 `data` can be either an instance of :class:`bytes` or a file-like
119116 object providing a :meth:`read` method. If an `encoding` keyword
@@ -134,13 +131,10 @@ def put(self, data: Any, **kwargs: Any) -> Any:
134131 .. versionchanged:: 3.0
135132 w=0 writes to GridFS are now prohibited.
136133 """
137- grid_file = GridIn (self .__collection , ** kwargs )
138- try :
139- grid_file .write (data )
140- finally :
141- grid_file .close ()
142134
143- return grid_file ._id
135+ with GridIn (self .__collection , ** kwargs ) as grid_file :
136+ grid_file .write (data )
137+ return grid_file ._id
144138
145139 def get (self , file_id : Any , session : Optional [ClientSession ] = None ) -> GridOut :
146140 """Get a file from GridFS by ``"_id"``.
@@ -528,11 +522,11 @@ def open_upload_stream(
528522
529523 my_db = MongoClient().test
530524 fs = GridFSBucket(my_db)
531- grid_in = fs.open_upload_stream(
525+ with fs.open_upload_stream(
532526 "test_file", chunk_size_bytes=4,
533- metadata={"contentType": "text/plain"})
534- grid_in.write("data I want to store!")
535- grid_in.close() # uploaded on close
527+ metadata={"contentType": "text/plain"}) as grid_in:
528+ grid_in.write("data I want to store!")
529+ # uploaded on close
536530
537531 Returns an instance of :class:`~gridfs.grid_file.GridIn`.
538532
@@ -584,13 +578,13 @@ def open_upload_stream_with_id(
584578
585579 my_db = MongoClient().test
586580 fs = GridFSBucket(my_db)
587- grid_in = fs.open_upload_stream_with_id(
581+ with fs.open_upload_stream_with_id(
588582 ObjectId(),
589583 "test_file",
590584 chunk_size_bytes=4,
591- metadata={"contentType": "text/plain"})
592- grid_in.write("data I want to store!")
593- grid_in.close() # uploaded on close
585+ metadata={"contentType": "text/plain"}) as grid_in:
586+ grid_in.write("data I want to store!")
587+ # uploaded on close
594588
595589 Returns an instance of :class:`~gridfs.grid_file.GridIn`.
596590
0 commit comments