반응형
데이터 관련 개발을 하다보면 외부에 대용량 데이터들이 구글 클라우드 저장소에 있는 경우가 많다. 공개된 저장소에 있는 데이터를 가져오는 방법을 정리해보았다.
1. Google Cloud Storage 라이브러리 설치
무료 공간을 사용할 때에는 특별히 프로젝트 설정이나 로그인 과정마저도 모두 생략할 수 있다.
아래와 같이 파이썬 라이브러리만 설치하면 된다. 업데이트가 자주 되므로 업그레이드 옵션을 주어 사용할 때마다 반복해주면 좋다.
pip install --upgrade google-cloud-storage
2. Google Cloud Client 생성
storage.를 import 해준후, 로그인이 필요없는 anonymous 모드로 Client를 생성해 준다.
from google.cloud import storage
client = storage.Client.create_anonymous_client()
3. Bucket, Blob 이해하기
구글 저장소를 사용하려면 Bucket과 Blob을 이해하여야 한다.
기본적으로 파일명을 지칭할때에는 디렉토리까지 포함하여 된다는 걸 인지해야한다. 의외로 디렉토리와 파일은 별도의 것이라고 생각하는 습관이 있기 때문이다. 이것만 이해되면 나머지는 쉽다.
버킷은 가장 큰 단위로써 C: 드라이브라고 생각하면 되고 그 안에 다양한 경로를 통해 오브젝트들을 담아 둘텐데 그 오브젝트들을 지칭하는 것을 Blob이라고 한다. 오브젝트는 파일이라고 생각하면 된다.
4. 샘플코드
import time
from google.cloud import storage
def download_public_file(bucket_name, source_blob_name, destination_file_name):
"""Downloads a public blob from the bucket."""
# bucket_name = "your-bucket-name"
# source_blob_name = "storage-object-name"
# destination_file_name = "local/path/to/file"
storage_client = storage.Client.create_anonymous_client()
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(
"Downloaded public blob {} from bucket {} to {}.".format(
source_blob_name, bucket.name, destination_file_name
)
)
if __name__ == '__main__':
bucket_name = 'x-dataset'
source_blob_name = 'x/x/pdf/2106/2106.12423v4.pdf'
destination_file_name = 'download.pdf'
start = time.time()
download_public_file(bucket_name, source_blob_name, destination_file_name)
print(f'duration: {time.time() - start}')
반응형
댓글