[英]Reusing or creating a google storage.Client()
I'm working with Google Cloud Storage.我正在使用 Google Cloud Storage。 One of its best practices is to reuse the clients.
它的最佳实践之一是重用客户端。 I've written several functions which I would like to be run with the possibility of not reusing the client.
我已经编写了几个函数,我希望在不重用客户端的情况下运行这些函数。 The coder would be the one to decide that, by using the
reuse_cl
variable.编码器将通过使用
reuse_cl
变量来决定这一点。
I was wondering why the following script does not work:我想知道为什么以下脚本不起作用:
def test_storage(bucket_name,reuse_cl=True):
if not reuse_cl:
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
list_blobs = list(bucket.list_blobs())
if __name__ == "__main__":
storage_client = storage.Client()
test_storage(BUCKET_NAME)
If I comment out the if in the test_storage, then everything works out fine.如果我在 test_storage 中注释掉 if,那么一切正常。 Is there a way of making the script work, and preserve the ability to create a client inside the function?
有没有办法让脚本工作,并保留在 function 中创建客户端的能力?
Posting comments from @furas and @John Hanley for better visibility:发表@furas 和@John Hanley 的评论以获得更好的可见度:
You should change the parameters expected in the function, so that can receive the client instead of a flag.您应该更改 function 中预期的参数,以便可以接收客户端而不是标志。 You can take the following approach to do so:
您可以采用以下方法来执行此操作:
def test_storage(bucket_name, storage_client=None):
And when invoking the function you can do so with either: test_storage(BUCKET_NAME, storage_client)
or在调用 function 时,您可以使用以下任一方法:
test_storage(BUCKET_NAME, storage_client)
或
test_storage(BUCKET_NAME)
and add something like this to the function: if not storage_client: storage_client = storage.Client()
test_storage(BUCKET_NAME)
并将类似这样的内容添加到 function: if not storage_client: storage_client = storage.Client()
This way, you will create a client when you don't receive it on the invocation.这样,当您在调用时没有收到客户端时,您将创建一个客户端。 However, you have to take into consideration if reusing client brings you enough benefits, and if they outweigh increased code complexity making it worth it.
但是,您必须考虑重用客户端是否会给您带来足够的好处,以及它们是否比增加的代码复杂性更值得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.