16
16
17
17
import os
18
18
import re
19
- import warnings
20
19
import sys
20
+ import warnings
21
+ import weakref
21
22
22
- from requests .exceptions import ConnectionError
23
-
24
- from hopsworks .decorators import connected , not_connected
25
23
from hopsworks import client , version
26
24
from hopsworks .core import project_api , secret_api , variable_api
25
+ from hopsworks .decorators import connected , not_connected
26
+ from requests .exceptions import ConnectionError
27
+
27
28
28
29
HOPSWORKS_PORT_DEFAULT = 443
29
30
HOSTNAME_VERIFICATION_DEFAULT = True
@@ -241,6 +242,7 @@ def connect(self):
241
242
"""
242
243
client .stop ()
243
244
self ._connected = True
245
+ finalizer = weakref .finalize (self , self .close )
244
246
try :
245
247
# init client
246
248
if client .base .Client .REST_ENDPOINT not in os .environ :
@@ -263,6 +265,7 @@ def connect(self):
263
265
self ._variable_api = variable_api .VariableApi ()
264
266
except (TypeError , ConnectionError ):
265
267
self ._connected = False
268
+ finalizer .detach ()
266
269
raise
267
270
print (
268
271
"Connected. Call `.close()` to terminate connection gracefully." ,
@@ -278,7 +281,7 @@ def close(self):
278
281
This will clean up any materialized certificates on the local file system of
279
282
external environments such as AWS SageMaker.
280
283
281
- Usage is recommended but optional.
284
+ Usage is optional.
282
285
"""
283
286
from hsfs import client as hsfs_client
284
287
from hsfs import engine as hsfs_engine
@@ -299,6 +302,9 @@ def close(self):
299
302
except : # noqa: E722
300
303
pass
301
304
305
+ if not self ._connected :
306
+ return # the connection is already closed
307
+
302
308
client .stop ()
303
309
self ._connected = False
304
310
0 commit comments