본문 바로가기

Contact 日本語 English

【Python】 MinIO 유용 함수 모음

 

MinIO 유용 함수 모음

 

추천글 : 【Python】 파이썬 목차 


1. MinIO [본문]

2. 파이썬 유용 함수 모음 [본문]

3. 터미널 유용 커멘드 모음 [본문]


 

1. MinIO [목차]

⑴ AWS S3-compatible object storage system

⑵ Synology NAS의 상위 버전

이유 1. 한 번 업로드 하면 삭제가 불가능하도록 셋팅할 수 있음 

이유 2. 보안 수준이 더 높음

⑶ 사용법 

1단계. 여기에서 MinIO Client 설치 : Linux Intel인 경우 다음과 같음

 

curl https://dl.min.io/client/mc/release/linux-amd64/mc \
  --create-dirs \
  -o $HOME/minio-binaries/mc

chmod +x $HOME/minio-binaries/mc
export PATH=$PATH:$HOME/minio-binaries/

mc --help

 

2단계. MinIO Access Key, Secret Key 생성

3단계. mc alias set [MinIO Name] [MinIO URL] [ACCESSKEY] [SECRETKEY]

4단계. 아래 참고 

 

 

2. 파이썬 유용 함수 모음 [목차]

⑴ MinIO로부터 download (ver. 1)

 

!pip install boto3 minio
import boto3
from botocore.client import Config

def download_from_minio(endpoint_url, access_key, secret_key, bucket_name, object_name, file_path):
    s3 = boto3.resource('s3',
                        endpoint_url=endpoint_url,
                        aws_access_key_id=access_key,
                        aws_secret_access_key=secret_key,
                        config=Config(signature_version='s3v4'),
                        region_name='us-east-1')  # You can adjust the region accordingly.

    try:
        s3.Bucket(bucket_name).download_file(object_name, file_path)
        print(f"{object_name} has been downloaded successfully to {file_path}")
    except Exception as e:
        print(f"An error occurred: {e}")

endpoint_url = 'http://your-minio-server.com:port'
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'
bucket_name = 'YOUR_BUCKET_NAME'
object_name = 'YOUR_OBJECT_NAME'
file_path = '/path/on/your/local/machine' 

download_from_minio(endpoint_url, access_key, secret_key, bucket_name, object_name, file_path)

 

① access_key, secret_key 

○ MinIO > Access Keys > Create access key를 이용해 생성

○ secret_key는 맨 처음 생성될 때만 알 수 있으므로 꼭 메모해 둘 것

② object_name 

○ 예시 : "https://s3.AAA.co.kr/browser/bucket_name/folder1/subfolder2/myobject.txt"

○ object_name은 "folder1/subfolder2/myobject.txt"

③ file_path 

○ 예시 : "./myobject.txt"

트러블슈팅 1. An error occurred: An error occurred (400) when calling the HeadObject operation: Bad Request

○ 원인 : object_name이 적절하지 않은 경우

트러블슈팅 2. An error occurred: An error occurred (404) when calling the HeadObject operation: Not Found

○ 원인 : object_name이 적절하지 않은 경우

트러블슈팅 3. An error occurred: [Errno 20] Not a directory:

○ 원인 : file_path가 적절하지 않은 경우 

⑵ MinIO로부터 download (ver. 2) 

 

from minio import Minio
client = Minio(
    "your_minio_server.com:port",
    access_key="",
    secret_key="",
    region="gabia",
)
file = client.get_object('bucket', 'file_path')
with open(f'file_name, 'wb') as f:
    f.write(file.data)

 

⑶ MinIO에 upload

방법 1. put_object

 

! pip install minio
from minio import Minio
from minio.error import S3Error

endpoint_url = 'http://your-minio-server.com:port'
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'
bucket_name = 'YOUR_BUCKET_NAME'
object_name = 'YOUR_OBJECT_NAME'
file_path = 'myfile.txt' 

client = Minio(
    endpoint_url,
    access_key=access_key,
    secret_key=secret_key,
    secure=True,
)

with open(file_path, "rb") as file_data:
    file_stat = os.stat(file_path)
    client.put_object(bucket_name, object_name, file_data, file_stat.st_size)

 

방법 2. fput_object 

 

! pip install minio
from minio import Minio
from minio.error import S3Error

endpoint_url = 'http://your-minio-server.com:port'
access_key = 'YOUR_ACCESS_KEY'
secret_key = 'YOUR_SECRET_KEY'
bucket_name = 'YOUR_BUCKET_NAME'
object_name = 'YOUR_OBJECT_NAME'
file_path = 'myfile.txt' 

client = Minio(
    endpoint_url,
    access_key=access_key,
    secret_key=secret_key,
    secure=True,
)

client.fput_object(bucket_name, object_name, file_path)

 

트러블슈팅 1. InvalidEndpointError: InvalidEndpointError: message: Hostname cannot have a scheme.

○ 원인 : endpoint_url = "https://my-minio-server.com" 대신 endpoint_url = "my-minio-server.com"을 사용하여야 함

○ 더 구체적으로는, 포트 번호를 포함하여 endpoint_url = "my-minio-server.com:port"을 사용하여야 함 

트러블슈팅 2. InvalidArgument: InvalidArgument: message: Invalid Argument

○ 필자의 경우, endpoint_url에 포트 번호를 빼먹은 경우 위 메시지가 발생했음 

트러블슈팅 3. InvalidArgumentError: InvalidArgumentError: message: Part size * max_parts(10000) is  lesser than input length.

○ 파이썬으로 MinIO에 업로드 하면 파일 크기에 따라 안 되는 경우가 꽤 많음

⑷ 에러 로그 출력 

 

import boto3
import logging

# Set up logging
logging.basicConfig(level=logging.DEBUG)
boto3.set_stream_logger('botocore', level='DEBUG')

 

⑸ 에러 로그 출력 해제

 

# Get root logger
logger = logging.getLogger()
while logger.hasHandlers():
    logger.removeHandler(logger.handlers[0])

# Also, reset boto3 and botocore loggers
for log_name in ['boto3', 'botocore']:
    logger = logging.getLogger(log_name)
    while logger.hasHandlers():
        logger.removeHandler(logger.handlers[0])

 

⑸ 트러블슈팅

MaxRetryError: HTTPConnectionPool(host='#.#.#.#', port={port}): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at #>: Failed to establish a new connection: [WinError #] 연결된 구성원으로부터 응답이 없어 연결하지 못했거나, 호스트로부터 응답이 없어 연결이 끊어졌습니다'))

○ 해결방법 : VPN 연결 확인

 

 

3. 터미널 유용 커멘드 모음 [목차]

⑴ 설치 : MinIO Client 기술 문서 참고 (예 : 64-bit Intel)

 

curl https://dl.min.io/client/mc/release/linux-amd64/mc \
  --create-dirs \
  -o $HOME/minio-binaries/mc

chmod +x $HOME/minio-binaries/mc
export PATH=$PATH:$HOME/minio-binaries/

mc --help

 

CLI 설정 : MinIO 서버에 접속 허가를 얻는 개념. mc alias set 명령어 사용

⑶ 파일 입출력 : mc cp 명령어 사용

--recursive 

--limit-upload 

 

입력: 2023.08.20 10:33