codememo

mongodb python 연결을 닫는 방법

tipmemo 2023. 2. 12. 17:55
반응형

mongodb python 연결을 닫는 방법

나는 mongodb에 데이터를 쓰는 python 스크립트를 만들고 있다.작업을 마치면 연결을 끊고 리소스를 확보해야 합니다.

Python에서는 어떻게 하나요?

에서 메서드 사용MongoClient인스턴스:

client = pymongo.MongoClient()

# some code here

client.close()

클라이언트 리소스를 정리하고 MongoDB와의 연결을 끊습니다.

하나 이상의 endSessions 명령을 전송하여 이 클라이언트가 작성한 모든 서버 세션을 종료합니다.

연결 풀의 모든 소켓을 닫고 모니터 스레드를 중지합니다.

pymongo 연결을 닫는 가장 안전한 방법은 'with'와 함께 사용하는 것입니다.

with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)

@alexce의 답변에 덧붙여, 그것이 항상 진실인 것은 아니다.연결이 암호화되어 있는 경우 MongoClient는 다시 연결하지 않습니다.

    def close(self):
        ...
        if self._encrypter:
            # TODO: PYTHON-1921 Encrypted MongoClients cannot be re-opened.
            self._encrypter.close()

또한 버전 4.0 이후 콜 후close()어떤 경우에도 클라이언트는 재접속되지 않습니다.

   def close(self) -> None:
        """Cleanup client resources and disconnect from MongoDB.
        End all server sessions created by this client by sending one or more
        endSessions commands.
        Close all sockets in the connection pools and stop the monitor threads.
        .. versionchanged:: 4.0
           Once closed, the client cannot be used again and any attempt will
           raise :exc:`~pymongo.errors.InvalidOperation`.

언급URL : https://stackoverflow.com/questions/18401015/how-to-close-a-mongodb-python-connection

반응형