참고: Python 2.7은 2024년 1월 31일 지원 종료됩니다. 기존 Python 2.7 애플리케이션을 계속 실행하고 트래픽을 받을 수 있습니다. 그러나 지원 종료 날짜 이후에는 해당 런타임을 사용하는 애플리케이션의 재배포를 App Engine에서 차단할 수 있습니다.
지원되는 최신 Python 버전으로 마이그레이션하는 것이 좋습니다.
이 문서에서는 Cloud Storage 클라이언트 라이브러리를 사용하여 데이터를 저장 및 검색하는 방법을 설명합니다. 여기서는 Cloud Storage 설정에 설명된 작업을 완료하여 Cloud Storage 버킷을 활성화하고 클라이언트 라이브러리를 다운로드했다고 가정합니다. 또한 App Engine 애플리케이션을 빌드하는 방법을 알고 있다고 가정합니다.
클라이언트 라이브러리를 사용하여 Cloud Storage에 액세스하려면 아래의 코드 스니펫을 사용합니다.
# Imports the Google Cloud client libraryfromgoogle.cloudimportstorage# Instantiates a clientstorage_client=storage.Client()# The name for the new bucketbucket_name="my-new-bucket"# Creates the new bucketbucket=storage_client.create_bucket(bucket_name)print(f"Bucket {bucket.name} created.")
Cloud Storage 버킷 지정
Cloud Storage에서 작업을 수행하기 전에 버킷 이름을 제공해야 합니다.
# Imports the Google Cloud client libraryfromgoogle.cloudimportstorage# Instantiates a clientstorage_client=storage.Client()# The name for the new bucketbucket_name="my-new-bucket"# Creates the new bucketbucket=storage_client.create_bucket(bucket_name)print(f"Bucket {bucket.name} created.")
버킷 이름을 지정하는 가장 쉬운 방법은 프로젝트에 기본 버킷을 사용하는 것입니다.
프로젝트의 기본 버킷을 생성한 경우에만 get_default_gcs_bucket_name 호출이 성공합니다.
Cloud Storage에 쓰기
다음 샘플은 버킷에 쓰는 방법을 보여줍니다.
fromgoogle.cloudimportstoragedefwrite_read(bucket_name,blob_name):"""Write and read a blob from GCS using file-like IO"""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The ID of your new GCS object# blob_name = "storage-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)# Mode can be specified as wb/rb for bytes mode.# See: https://docs.python.org/3/library/io.htmlwithblob.open("w")asf:f.write("Hello world")withblob.open("r")asf:print(f.read())
다음에 유의하세요.
쓰기 위해 파일을 열기 위한 호출에서 이 샘플은 파일의 커스텀 메타데이터를 쓰는 특정 Cloud Storage 헤더를 지정합니다. cloudstorage.stat()을 사용하여 이 메타데이터를 검색할 수 있습니다. cloudstorage.open() 참조 문서에서 지원되는 헤더 목록을 확인할 수 있습니다.
x-goog-acl 헤더가 설정되지 않았습니다. 즉, 기본 Cloud Storage ACL의 공개 읽기는 버킷에 기록될 때 객체에 적용됩니다.
쓰기를 마친 후에는 파일을 닫는 함수를 호출해야 합니다. 그렇지 않으면 파일이 Cloud Storage에 기록되지 않습니다. Python 파일 함수 close()를 호출한 후에는 파일에 아무 것도 추가할 수 없습니다. 파일을 수정해야 하는 경우 Python 파일 함수 open()을 호출하여 쓰기 모드로 파일을 다시 열어야 하며, 이 경우 파일을 추가하지 않고 덮어씁니다.
Cloud Storage에서 읽기
다음 샘플은 버킷에서 전체 파일을 읽는 방법을 보여줍니다.
fromgoogle.cloudimportstoragedefwrite_read(bucket_name,blob_name):"""Write and read a blob from GCS using file-like IO"""# The ID of your GCS bucket# bucket_name = "your-bucket-name"# The ID of your new GCS object# blob_name = "storage-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)# Mode can be specified as wb/rb for bytes mode.# See: https://docs.python.org/3/library/io.htmlwithblob.open("w")asf:f.write("Hello world")withblob.open("r")asf:print(f.read())
두 예시에서 cloudstorage.open()에 전달하는 blob_name 인수는 YOUR_BUCKET_NAME/PATH_IN_GCS 형식의 파일 경로입니다. cloudstorage.open()의 기본값은 읽기 전용 모드입니다. 파일을 읽기 위해 파일을 열 때 모드를 지정할 필요는 없습니다.
버킷 콘텐츠 나열
샘플 코드는 blob 유형 콘텐츠를 사용해서 버킷을 통해 페이징하는 방법을 보여줍니다.
fromgoogle.cloudimportstoragedeflist_blobs(bucket_name):"""Lists all the blobs in the bucket."""# bucket_name = "your-bucket-name"storage_client=storage.Client()# Note: Client.list_blobs requires at least package version 1.17.0.blobs=storage_client.list_blobs(bucket_name)# Note: The call returns a response only when the iterator is consumed.forblobinblobs:print(blob.name)
전체 파일 이름은 디렉터리 구분 기호 없이 문자열 하나로 표시됩니다. 보기 쉽게 디렉터리 계층 구조로 파일을 표시하려면 사용할 디렉터리 구분 기호로 delimiter 매개변수를 설정합니다.
Cloud Storage의 파일 삭제
아래 코드는 cloudstorage.delete() 메서드(gcs로 가져옴)를 사용하여 Cloud Storage에서 파일을 삭제하는 방법을 보여줍니다.
fromgoogle.cloudimportstoragedefdelete_blob(bucket_name,blob_name):"""Deletes a blob from the bucket."""# bucket_name = "your-bucket-name"# blob_name = "your-object-name"storage_client=storage.Client()bucket=storage_client.bucket(bucket_name)blob=bucket.blob(blob_name)generation_match_precondition=None# Optional: set a generation-match precondition to avoid potential race conditions# and data corruptions. The request to delete is aborted if the object's# generation number does not match your precondition.blob.reload()# Fetch blob metadata to use in generation_match_precondition.generation_match_precondition=blob.generationblob.delete(if_generation_match=generation_match_precondition)print(f"Blob {blob_name} deleted.")
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-03-06(UTC)"],[[["This document guides you on how to store and retrieve data using the Cloud Storage client library, assuming you've already set up a Cloud Storage bucket and downloaded the necessary client libraries."],["The process starts by instantiating a storage client and creating a bucket, then to specify the correct bucket name to execute operations, you should utilize your project's default bucket."],["To write data, you use the `blob.open(\"w\")` method and to ensure the file is properly written, the `close()` function must be invoked, overwriting existing data if the file is reopened in write mode."],["To read a file, utilize `blob.open(\"r\")`, which is the default setting for reading; the path to the file is specified in `YOUR_BUCKET_NAME/PATH_IN_GCS` format."],["You can list the content of a bucket using the method `list_blobs`, and delete a file using `blob.delete`, optionally employing generation-match preconditions to prevent data corruption."]]],[]]