끄적끄적 인턴생활 (2020)

Azure 컨테이너 생성, Blob 업로드 & 다운로드 , 컨테이너 삭제

jellylucy 2021. 12. 28. 13:05

 

프로젝트 만들기

출처 입력

1. 새로운 디렉터리 생성

mkdir blob-quickstart-v12
 

 

2. 그 안에 data 디렉터리 생성

: Blob 데이터 파일 생성%저장


cd blob-quickstart-v12

mkdir data

 

패키지 설치

출처 입력

pip install azure-storage-blob
 

앱 프레임워크 설정

출처 입력

import os, uuid
from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient, __version__

try:
    print("Azure Blob storage v" + __version__ + " - Python quickstart sample")
    # Quick start code goes here
except Exception as ex:
    print('Exception:')
    print(ex)
 

-> 저장 파일명 : blob-quickstart-v12.py

 

Azure Portal에서 자격 증명 복사

출처 입력

Azure potal 스토리지계정에 들어갈 수 있는 KEY를 받는다.

설정 -> 엑세스 키->연결 문자열 복사한다.

스토리지 연결 문자열 구성

출처 입력

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"
 

환경변수 넣은 후, 파이썬 프로그램 다시 시작.(Kernel restart)

 

개체 모델

출처 입력

Azure Blob storage는 대량의 비정형 데이터를 저장하도록 최적화되어 있습니다.

비정형 데이터는 텍스트 또는 이진 데이터와 같은 특정 데이터 모델 또는 정의를 따르지 않는 데이터.

Blob storage는 세 가지 유형의 리소스를 제공합니다.

1. 스토리지 계정 2. 스토리지 계정의 컨테이너 3. 컨테이너의 blob

사진 삭제

사진 설명을 입력하세요.

BlobServiceClient:

BlobServiceClient 클래스를 사용하여 Azure Storage 리소스 및 blob 컨테이너를 조작할 수 있습니다.

ContainerClient:

ContainerClient 클래스를 사용하여 Azure Storage 컨테이너 및 해당 blob을 조작할 수 있습니다.

BlobClient:

BlobClient 클래스를 사용하여 Azure Storage blob을 조작할 수 있습니다.

코드 예제

출처 입력

연결 문자열 가져오기

출처 입력

스토리지 연결 문자열 (환경변수 설정한거)으로 스토리지 계정에 대한 연결 문자열을 검색합니다.

# Retrieve the connection string for use with the application. The storage
# connection string is stored in an environment variable on the machine
# running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable is
# created after the application is launched in a console or with Visual Studio,
# the shell or application needs to be closed and reloaded to take the
# environment variable into account.
connect_str = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
 

컨테이너 만들기

출처 입력

# Create the BlobServiceClient object which will be used to create a container client
blob_service_client = BlobServiceClient.from_connection_string(connect_str)

# Create a unique name for the container
container_name = "quickstart" + str(uuid.uuid4())

# Create the container
container_client = blob_service_client.create_container(container_name)
 

1. BlobServiceClient 클래스의 인스턴스 만들기

blob_service_client = BlobServiceClient.from_connection_string(connect_str)

2. 컨테이너 이름 설정 / 생성

 

컨테이너 blob 업로드

출처 입력

# Create a file in local data directory to upload and download
local_path = "./data"
local_file_name = "quickstart" + str(uuid.uuid4()) + ".txt"
upload_file_path = os.path.join(local_path, local_file_name)

# Write text to the file
file = open(upload_file_path, 'w')
file.write("Hello, World!")
file.close()

# Create a blob client using the local file name as the name for the blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)

print("\nUploading to Azure Storage as blob:\n\t" + local_file_name)

# Upload the created file
with open(upload_file_path, "rb") as data:
    blob_client.upload_blob(data)
 

1. ./data(로컬 디렉터리) 에

quickstart 이라는 txt 파일 생성

 

2. 파일에 Hello world 작성

 

3. blob_service_client.get_blob_client() 호출

 

4.upload_blob(data) 이용해

quickstart.txt 파일을 blob에 업로드

 

컨테이너의 Blob 나열

출처 입력

print("\nListing blobs...")

# List the blobs in the container
blob_list = container_client.list_blobs()
for blob in blob_list:
    print("\t" + blob.name)
 

컨테이너 안에 Blob을 나열시킨다

 

Blob 업로드 확인 차원으로

 

Blob 다운로드

출처 입력

# Download the blob to a local file
# Add 'DOWNLOAD' before the .txt extension so you can see both files in the data directory
download_file_path = os.path.join(local_path, str.replace(local_file_name ,'.txt', 'DOWNLOAD.txt'))
print("\nDownloading blob to \n\t" + download_file_path)

with open(download_file_path, "wb") as download_file:
    download_file.write(blob_client.download_blob().readall())
 

 

컨테이너 삭제

출처 입력

# Clean up
print("\nPress the Enter key to begin clean up")
input()

print("Deleting blob container...")
container_client.delete_container()

print("Deleting the local source and downloaded files...")
os.remove(upload_file_path)
os.remove(download_file_path)

print("Done")
 

input() : 입력 일시중지. enter 치면 실행 .