Cloud Functions Read/Write Temp Files (Python)

Oct 19, 2019

https://cloud.google.com/functions/docs/concepts/exec#file_system

The only writeable part of the filesystem is the /tmp directory, which you can use to store temporary files in a function instance. This is a local disk mount point known as a "tmpfs" volume in which data written to the volume is stored in memory. Note that it will consume memory resources provisioned for the function.

The rest of the file system is read-only and accessible to the function.

https://cloud.google.com/functions/docs/bestpractices/tips#always_delete_temporary_files

Local disk storage in the temporary directory is an in-memory filesystem. Files that you write consume memory available to your function, and sometimes persist between invocations. Failing to explicitly delete these files may eventually lead to an out-of-memory error and a subsequent cold start.

import osdef test_read_write_tmp(requests):    file_path = '/tmp/test'    content = 'Hello World'    #  make sure dir exist    os.makedirs(os.path.dirname(file_path), exist_ok=True)    with open(file_path, 'wb') as f:        f.write(content)    if os.path.exists(file_path):        with open(file_path, 'rb') as f:            content = f.read()    return content

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.