LoginSignup
2
2

More than 3 years have passed since last update.

【Python】Cloud StorageにアップロードするオブジェクトのCache-Controlを変更する

Last updated at Posted at 2020-05-14

目標

PythonでCloud StorageにアップロードするオブジェクトのCache-Controlを変更します。

公式のドキュメントにPythonのサンプルコードがなく、ハマりポイントがあったので書き残します。

コード

upload.py
def main():
    _, temp_local_filename = tempfile.mkstemp()
    with codecs.open(temp_local_filename, 'w', 'utf_8') as f:
        f.write('テキスト')

    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = 'credencialsファイル名'
    client = storage.Client()
    bucket = client.get_bucket('バケット名')
    blob = bucket.blob('アップロード先ファイル名')
    blob.upload_from_filename(filename=temp_local_filename)
    blob.cache_control = 'no-cache'
    blob.patch()
    return "success"

正しい方法

upload.py
    blob.cache_control = 'no-cache'
    blob.patch()

設定されているか確認します。

bash
$ curl -v "https://storage.googleapis.com/バケット名/ファイル名" 2>&1 | grep -i Cache-Control
* h2 header: cache-control: no-cache
< cache-control: no-cache

screenshot-console.cloud.google.com-2020.05.15-09_50_17.png

Cache-Controlがno-cacheになりました。

間違った方法

metadataには

があり、Cache-Controlは固定キーデータにあたります。以下のコードはカスタムメタデータを設定するため、Cache-Controlが正常に設定されません。

upload.py
    blob.metadata['Cache-Control'] = 'no-cache'

どのように設定されているか確認します。

bash
$ curl -v "https://storage.googleapis.com/バケット名/ファイル名" 2>&1 | grep -i Cache-Control
* h2 header: cache-control: public, max-age=3600
* h2 header: x-goog-meta-cache-control: no-cache
< cache-control: public, max-age=3600
< x-goog-meta-cache-control: no-cache

x-goog-meta-cache-controlに設定されてしまっています。

screenshot-console.cloud.google.com-2020.05.15-09_36_16.png

コンソールで見ても本来のCache-Controlとは別項目に値が設定されています。

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2