From 8d8f5068e12dc5feb79aebe41fd1111b3e941d98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Tue, 26 Jul 2016 12:17:38 +0200 Subject: [PATCH] Store GCS client on global level Without this, every query to the GCS would have to re-establish a TCP/IP connection and perform an OAuth handshake. --- pillar/application/utils/gcs.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/pillar/application/utils/gcs.py b/pillar/application/utils/gcs.py index 23b336c7..c43687bd 100644 --- a/pillar/application/utils/gcs.py +++ b/pillar/application/utils/gcs.py @@ -6,11 +6,30 @@ import logging from bson import ObjectId from gcloud.storage.client import Client from gcloud.exceptions import NotFound -from flask import current_app +from flask import current_app, g +from werkzeug.local import LocalProxy log = logging.getLogger(__name__) +def get_client(): + """Stores the GCS client on the global Flask object. + + The GCS client is not user-specific anyway. + """ + + _gcs = getattr(g, '_gcs_client', None) + if _gcs is None: + _gcs = g._gcs_client = Client() + return _gcs + + +# This hides the specifics of how/where we store the GCS client, +# and allows the rest of the code to use 'gcs' as a simple variable +# that does the right thing. +gcs = LocalProxy(get_client) + + class GoogleCloudStorageBucket(object): """Cloud Storage bucket interface. We create a bucket for every project. In the bucket we create first level subdirs as follows: @@ -28,7 +47,6 @@ class GoogleCloudStorageBucket(object): """ def __init__(self, bucket_name, subdir='_/'): - gcs = Client() try: self.bucket = gcs.get_bucket(bucket_name) except NotFound: