├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CNAME ├── CONTRIBUTING.md ├── LICENSE ├── MAINTAINERS.md ├── MANIFEST.in ├── Makefile ├── NOTICE ├── README.md ├── README_zh_CN.md ├── docs ├── API.md └── zh_CN │ ├── API.md │ └── CONTRIBUTING.md ├── examples ├── append_object.py ├── bucket_exists.py ├── compose_object.py ├── copy_object.py ├── delete_bucket_encryption.py ├── delete_bucket_lifecycle.py ├── delete_bucket_notification.py ├── delete_bucket_policy.py ├── delete_bucket_replication.py ├── delete_bucket_tags.py ├── delete_object_lock_config.py ├── delete_object_tags.py ├── disable_object_legal_hold.py ├── enable_object_legal_hold.py ├── fget_object.py ├── fput_object.py ├── get_bucket_encryption.py ├── get_bucket_lifecycle.py ├── get_bucket_notification.py ├── get_bucket_policy.py ├── get_bucket_replication.py ├── get_bucket_tags.py ├── get_bucket_versioning.py ├── get_object.py ├── get_object_lock_config.py ├── get_object_retention.py ├── get_object_tags.py ├── get_presigned_url.py ├── is_object_legal_hold_enabled.py ├── list_buckets.py ├── list_objects.py ├── listen_bucket_notification.py ├── make_bucket.py ├── minio_with_assume_role_provider.py ├── minio_with_aws_config_provider.py ├── minio_with_certificate_identity_provider.py ├── minio_with_chained_provider.py ├── minio_with_client_grants_provider.py ├── minio_with_env_aws_provider.py ├── minio_with_env_minio_provider.py ├── minio_with_iam_aws_provider.py ├── minio_with_ldap_identity_provider.py ├── minio_with_minio_client_config_provider.py ├── minio_with_web_identity_provider.py ├── presigned_get_object.py ├── presigned_post_policy.py ├── presigned_put_object.py ├── progress.py ├── put_object.py ├── remove_bucket.py ├── remove_object.py ├── remove_objects.py ├── select_object_content.py ├── set_bucket_encryption.py ├── set_bucket_lifecycle.py ├── set_bucket_notification.py ├── set_bucket_policy.py ├── set_bucket_replication.py ├── set_bucket_tags.py ├── set_bucket_versioning.py ├── set_object_lock_config.py ├── set_object_retention.py ├── set_object_tags.py ├── stat_object.py └── upload_snowball_objects.py ├── minio ├── __init__.py ├── api.py ├── commonconfig.py ├── credentials │ ├── __init__.py │ ├── credentials.py │ └── providers.py ├── crypto.py ├── datatypes.py ├── deleteobjects.py ├── error.py ├── helpers.py ├── legalhold.py ├── lifecycleconfig.py ├── minioadmin.py ├── notificationconfig.py ├── objectlockconfig.py ├── py.typed ├── replicationconfig.py ├── retention.py ├── select.py ├── signer.py ├── sse.py ├── sseconfig.py ├── tagging.py ├── time.py ├── versioningconfig.py └── xml.py ├── pylintrc ├── run_functional_tests.sh ├── setup.py └── tests ├── __init__.py ├── certs ├── private.key └── public.crt ├── functional ├── play.min.io.kes.root.cert ├── play.min.io.kes.root.key └── tests.py └── unit ├── __init__.py ├── bucket_exist_test.py ├── config.json.sample ├── copy_object_test.py ├── credentials.empty ├── credentials.sample ├── credentials_test.py ├── crypto_test.py ├── get_bucket_policy_test.py ├── get_object_test.py ├── helpers.py ├── legelhold_test.py ├── lifecycleconfig_test.py ├── list_buckets_test.py ├── list_objects_test.py ├── list_objects_v1_test.py ├── make_bucket_test.py ├── minio_mocks.py ├── minio_test.py ├── notificationconfig_test.py ├── objectlockconfig_test.py ├── presigned_get_object_test.py ├── presigned_put_object_test.py ├── put_object_test.py ├── remove_bucket_test.py ├── remove_object_test.py ├── remove_objects_test.py ├── replicationconfig_test.py ├── retention_test.py ├── sign_test.py ├── sseconfig_test.py ├── stat_object_test.py ├── tagging_test.py ├── time_test.py ├── trace_test.py └── versioningconfig_test.py /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - master 7 | push: 8 | branches: 9 | - master 10 | 11 | env: 12 | MINIO_ROOT_USER: minio 13 | MINIO_ROOT_PASSWORD: minio123 14 | MINIO_CI_CD: 1 15 | MINT_MODE: full 16 | SERVER_ENDPOINT: localhost:9000 17 | ACCESS_KEY: minio 18 | SECRET_KEY: minio123 19 | ENABLE_HTTPS: 1 20 | 21 | # This ensures that previous jobs for the PR are canceled when the PR is 22 | # updated. 23 | concurrency: 24 | group: ${{ github.workflow }}-${{ github.head_ref }} 25 | cancel-in-progress: true 26 | 27 | jobs: 28 | build: 29 | name: Test on python ${{ matrix.python-version }} and ${{ matrix.os }} 30 | runs-on: ${{ matrix.os }} 31 | strategy: 32 | matrix: 33 | python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] 34 | os: [ubuntu-latest, windows-latest, macos-latest] 35 | 36 | steps: 37 | - uses: actions/checkout@v4 38 | - name: Run spell check on Ubuntu 39 | if: matrix.os == 'ubuntu-latest' 40 | uses: codespell-project/actions-codespell@master 41 | with: 42 | ignore_words_list: assertIn 43 | - name: Set up Python ${{ matrix.python-version }} 44 | uses: actions/setup-python@v5 45 | with: 46 | python-version: ${{ matrix.python-version }} 47 | - name: Install dependencies 48 | run: | 49 | python -m pip install --upgrade pip setuptools 50 | pip install certifi urllib3 mock pytest argon2-cffi pycryptodome 51 | - name: Run check if Ubuntu 52 | if: matrix.os == 'ubuntu-latest' 53 | run: | 54 | export PATH=${HOME}/.local/bin:${PATH} 55 | make check 56 | - name: Setup PATH if macOS 57 | if: matrix.os == 'macos-latest' 58 | run: | 59 | echo "/Users/runner/Library/Python/3.11/bin" >> $GITHUB_PATH 60 | echo "$HOME/.local/bin" >> $GITHUB_PATH 61 | echo "/Users/runner/.local/bin" >> $GITHUB_PATH 62 | - name: Run unit tests 63 | run: | 64 | pip install -e . 65 | pytest 66 | - name: Run functional tests on Ubuntu 67 | if: matrix.os == 'ubuntu-latest' 68 | run: | 69 | wget --quiet -O /tmp/minio https://dl.min.io/server/minio/release/linux-amd64/minio 70 | chmod +x /tmp/minio 71 | mkdir -p /tmp/minio-config/certs/ 72 | cp tests/certs/* /tmp/minio-config/certs/ 73 | /tmp/minio --certs-dir /tmp/minio-config/certs server /tmp/fs{1...4} & 74 | SSL_CERT_FILE=/tmp/minio-config/certs/public.crt python tests/functional/tests.py 75 | - name: Run functional tests on Windows 76 | if: matrix.os == 'windows-latest' 77 | run: | 78 | New-Item -ItemType Directory -Path "$env:temp/minio-config/certs/" 79 | Copy-Item -Path tests\certs\* -Destination "$env:temp/minio-config/certs/" 80 | Invoke-WebRequest -Uri https://dl.minio.io/server/minio/release/windows-amd64/minio.exe -OutFile $HOME/minio.exe 81 | Start-Process -NoNewWindow -FilePath "$HOME/minio.exe" -ArgumentList "--certs-dir", "$env:temp/minio-config/certs", "server", "$env:temp/fs{1...4}" 82 | $env:SSL_CERT_FILE = "$env:temp/minio-config/certs/public.crt" 83 | python tests/functional/tests.py 84 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | *~ 26 | .#* 27 | .vscode 28 | .idea 29 | #* 30 | tests/functional/.* 31 | tests/functional/minio* 32 | -------------------------------------------------------------------------------- /CNAME: -------------------------------------------------------------------------------- 1 | minio-py.min.io -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributors Guide 2 | ``minio-py`` welcomes your contribution. Below steps can be followed to create a pull request. 3 | 4 | * Fork this minio-py repository into your account. 5 | * Create a feature branch in your fork (`$ git checkout -b my-new-feature`). 6 | * Hack, hack, hack... 7 | * Run checks. (`$ make check`). 8 | * Commit your changes (`$ git commit -am 'Add some feature'`). 9 | * Push the feature branch into your fork (`$ git push origin -u my-new-feature`). 10 | * Create new pull request to `master` branch. 11 | -------------------------------------------------------------------------------- /MAINTAINERS.md: -------------------------------------------------------------------------------- 1 | # For maintainers only 2 | 3 | ## Responsibilities 4 | Please go through this link [Maintainer Responsibility](https://gist.github.com/abperiasamy/f4d9b31d3186bbd26522) 5 | 6 | ### Setup your minio-py Github Repository 7 | Fork [minio-py upstream](https://github.com/minio/minio-py/fork) source repository to your own personal repository. 8 | ```sh 9 | $ git clone git@github.com:minio/minio-py 10 | $ cd minio-py 11 | $ pip install --user --upgrade twine 12 | ``` 13 | 14 | ### Modify package version 15 | ```sh 16 | $ cat minio/__init__.py 17 | ... 18 | ... 19 | __version__ = '2.2.5' 20 | ... 21 | ... 22 | 23 | ``` 24 | 25 | ### Build and verify 26 | ```sh 27 | $ make 28 | $ python setup.py register 29 | $ python setup.py sdist bdist bdist_wheel 30 | ``` 31 | 32 | ### Publishing new packages 33 | 34 | #### Setup your pypirc 35 | Create a new `pypirc` 36 | 37 | ```sh 38 | $ cat >> $HOME/.pypirc << EOF 39 | [distutils] 40 | index-servers = 41 | pypi 42 | 43 | [pypi] 44 | username:minio 45 | password:**REDACTED** 46 | EOF 47 | 48 | ``` 49 | 50 | #### Sign 51 | Sign the release artifacts, this step requires you to have access to MinIO's trusted private key. 52 | ```sh 53 | $ export GNUPGHOME=/media/${USER}/minio/trusted 54 | $ gpg --detach-sign -a dist/minio-2.2.5.tar.gz 55 | $ gpg --detach-sign -a dist/minio-2.2.5.linux-x86_64.tar.gz 56 | $ gpg --detach-sign -a dist/minio-2.2.5-py2.py3-none-any.whl 57 | ``` 58 | 59 | #### Upload to pypi 60 | Upload the signed release artifacts, please install twine v1.8.0+ for following steps to work properly. 61 | ```sh 62 | $ twine upload dist/* 63 | ``` 64 | 65 | ### Tag 66 | Tag and sign your release commit, additionally this step requires you to have access to MinIO's trusted private key. 67 | ``` 68 | $ export GNUPGHOME=/media/${USER}/minio/trusted 69 | $ git tag -s 2.2.5 70 | $ git push 71 | $ git push --tags 72 | ``` 73 | 74 | ### Announce 75 | Announce new release by adding release notes at https://github.com/minio/minio-py/releases from `trusted@min.io` account. Release notes requires two sections `highlights` and `changelog`. Highlights is a bulleted list of salient features in this release and Changelog contains list of all commits since the last release. 76 | 77 | To generate `changelog` 78 | ```sh 79 | git log --no-color --pretty=format:'-%d %s (%cr) <%an>' .. 80 | ``` 81 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE README* 2 | recursive-include docs *.md 3 | recursive-include examples *.py 4 | recursive-include tests *.py *.sh *.crt *.key *.sample *.empty 5 | 6 | prune .github 7 | prune Makefile 8 | prune pylintrc 9 | prune CONTRIBUTING.md 10 | prune MAINTAINERS.md 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: default 2 | default: tests 3 | 4 | getdeps: 5 | @echo "Installing required dependencies" 6 | @pip install --user --upgrade autopep8 certifi pytest pylint urllib3 argon2-cffi pycryptodome typing-extensions mypy 7 | 8 | check: getdeps 9 | @echo "Running checks" 10 | @pylint --reports=no --score=no --disable=R0401,R0801,R0917 minio/*py minio/credentials tests/functional 11 | @isort --diff . 12 | @find . -name "*.py" -exec autopep8 --diff --exit-code {} + 13 | @mypy minio 14 | 15 | apply: getdeps 16 | @isort . 17 | @find . -name "*.py" -exec autopep8 --in-place {} + 18 | 19 | tests: check 20 | @echo "Running unit tests" 21 | @pytest 22 | @echo "Running functional tests" 23 | @env bash run_functional_tests.sh 24 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | MinIO Cloud Storage, (C) 2014-2023 MinIO, Inc. 2 | 3 | This product includes software developed at MinIO, Inc. 4 | (https://min.io/). 5 | 6 | The MinIO project contains unmodified/modified subcomponents too with 7 | separate copyright notices and license terms. Your use of the source 8 | code for these subcomponents is subject to the terms and conditions 9 | of Apache License Version 2.0 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MinIO Python Client SDK for Amazon S3 Compatible Cloud Storage [![Slack](https://slack.min.io/slack?type=svg)](https://slack.min.io) [![Apache V2 License](https://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/minio/minio-py/blob/master/LICENSE) 2 | 3 | The MinIO Python Client SDK provides high level APIs to access any MinIO Object Storage or other Amazon S3 compatible service. 4 | 5 | This Quickstart Guide covers how to install the MinIO client SDK, connect to the object storage service, and create a sample file uploader. 6 | 7 | The example below uses: 8 | - [Python version 3.7+](https://www.python.org/downloads/) 9 | - The [MinIO `mc` command line tool](https://min.io/docs/minio/linux/reference/minio-mc.html) 10 | - The MinIO `play` test server 11 | 12 | The `play` server is a public MinIO cluster located at [https://play.min.io](https://play.min.io). 13 | This cluster runs the latest stable version of MinIO and may be used for testing and development. 14 | The access credentials in the example are open to the public and all data uploaded to `play` should be considered public and world-readable. 15 | 16 | For a complete list of APIs and examples, see the [Python Client API Reference](https://min.io/docs/minio/linux/developers/python/API.html) 17 | 18 | ## Install the MinIO Python SDK 19 | 20 | The Python SDK requires Python version 3.7+. 21 | You can install the SDK with `pip` or from the [`minio/minio-py` GitHub repository](https://github.com/minio/minio-py): 22 | 23 | ### Using `pip` 24 | 25 | ```sh 26 | pip3 install minio 27 | ``` 28 | 29 | ### Using Source From GitHub 30 | 31 | ```sh 32 | git clone https://github.com/minio/minio-py 33 | cd minio-py 34 | python setup.py install 35 | ``` 36 | 37 | ## Create a MinIO Client 38 | 39 | To connect to the target service, create a MinIO client using the `Minio()` method with the following required parameters: 40 | 41 | | Parameter | Description | 42 | |--------------|--------------------------------------------------------| 43 | | `endpoint` | URL of the target service. | 44 | | `access_key` | Access key (user ID) of a user account in the service. | 45 | | `secret_key` | Secret key (password) for the user account. | 46 | 47 | For example: 48 | 49 | ```py 50 | from minio import Minio 51 | 52 | client = Minio("play.min.io", 53 | access_key="Q3AM3UQ867SPQQA43P2F", 54 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 55 | ) 56 | ``` 57 | 58 | ## Example - File Uploader 59 | 60 | This example does the following: 61 | 62 | - Connects to the MinIO `play` server using the provided credentials. 63 | - Creates a bucket named `python-test-bucket` if it does not already exist. 64 | - Uploads a file named `test-file.txt` from `/tmp`, renaming it `my-test-file.txt`. 65 | - Verifies the file was created using [`mc ls`](https://min.io/docs/minio/linux/reference/minio-mc/mc-ls.html). 66 | 67 | ### `file_uploader.py` 68 | 69 | ```py 70 | # file_uploader.py MinIO Python SDK example 71 | from minio import Minio 72 | from minio.error import S3Error 73 | 74 | def main(): 75 | # Create a client with the MinIO server playground, its access key 76 | # and secret key. 77 | client = Minio("play.min.io", 78 | access_key="Q3AM3UQ867SPQQA43P2F", 79 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 80 | ) 81 | 82 | # The file to upload, change this path if needed 83 | source_file = "/tmp/test-file.txt" 84 | 85 | # The destination bucket and filename on the MinIO server 86 | bucket_name = "python-test-bucket" 87 | destination_file = "my-test-file.txt" 88 | 89 | # Make the bucket if it doesn't exist. 90 | found = client.bucket_exists(bucket_name) 91 | if not found: 92 | client.make_bucket(bucket_name) 93 | print("Created bucket", bucket_name) 94 | else: 95 | print("Bucket", bucket_name, "already exists") 96 | 97 | # Upload the file, renaming it in the process 98 | client.fput_object( 99 | bucket_name, destination_file, source_file, 100 | ) 101 | print( 102 | source_file, "successfully uploaded as object", 103 | destination_file, "to bucket", bucket_name, 104 | ) 105 | 106 | if __name__ == "__main__": 107 | try: 108 | main() 109 | except S3Error as exc: 110 | print("error occurred.", exc) 111 | ``` 112 | 113 | To run this example: 114 | 115 | 1. Create a file in `/tmp` named `test-file.txt`. 116 | To use a different path or filename, modify the value of `source_file`. 117 | 118 | 2. Run `file_uploader.py` with the following command: 119 | 120 | ```sh 121 | python file_uploader.py 122 | ``` 123 | 124 | If the bucket does not exist on the server, the output resembles the following: 125 | 126 | ```sh 127 | Created bucket python-test-bucket 128 | /tmp/test-file.txt successfully uploaded as object my-test-file.txt to bucket python-test-bucket 129 | ``` 130 | 131 | 3. Verify the uploaded file with `mc ls`: 132 | 133 | ```sh 134 | mc ls play/python-test-bucket 135 | [2023-11-03 22:18:54 UTC] 20KiB STANDARD my-test-file.txt 136 | ``` 137 | 138 | ## More References 139 | 140 | * [Python Client API Reference](https://min.io/docs/minio/linux/developers/python/API.html) 141 | * [Examples](https://github.com/minio/minio-py/tree/master/examples) 142 | 143 | ## Explore Further 144 | 145 | * [Complete Documentation](https://min.io/docs/minio/kubernetes/upstream/index.html) 146 | 147 | ## Contribute 148 | 149 | [Contributors Guide](https://github.com/minio/minio-py/blob/master/CONTRIBUTING.md) 150 | 151 | ## License 152 | 153 | This SDK is distributed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0), see [LICENSE](https://github.com/minio/minio-py/blob/master/LICENSE) and [NOTICE](https://github.com/minio/minio-go/blob/master/NOTICE) for more information. 154 | 155 | [![PYPI](https://img.shields.io/pypi/v/minio.svg)](https://pypi.python.org/pypi/minio) 156 | -------------------------------------------------------------------------------- /docs/zh_CN/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ### 设置你的minio-py Github仓库 2 | Fork [minio-py upstream](https://github.com/minio/minio-py/fork)源码仓库到你自己的仓库。 3 | 4 | ```sh 5 | $ git clone https://github.com/$USER_ID/minio-py 6 | $ cd minio-py 7 | $ python setup.py install 8 | ... 9 | ``` 10 | 11 | ### 开发者指南 12 | 13 | ``minio-py``欢迎你的贡献。为了让大家配合的更加默契,我们做出如下约定: 14 | 15 | * fork项目并修改,我们鼓励大家使用pull requests进行代码相关的讨论。 16 | - Fork项目 17 | - 创建你的特性分支 (git checkout -b my-new-feature) 18 | - Commit你的修改(git commit -am 'Add some feature') 19 | - Push到远程分支(git push origin my-new-feature) 20 | - 创建一个Pull Request 21 | -------------------------------------------------------------------------------- /examples/append_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2025 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import io 18 | from urllib.request import urlopen 19 | 20 | from examples.progress import Progress 21 | from minio import Minio 22 | 23 | client = Minio( 24 | "play.min.io", 25 | access_key="Q3AM3UQ867SPQQA43P2F", 26 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 27 | ) 28 | 29 | # Upload data. 30 | result = client.put_object( 31 | "my-bucket", "my-object", io.BytesIO(b"hello, "), 7, 32 | ) 33 | print(f"created {result.object_name} object; etag: {result.etag}") 34 | 35 | # Append data. 36 | result = client.append_object( 37 | "my-bucket", "my-object", io.BytesIO(b"world"), 5, 38 | ) 39 | print(f"appended {result.object_name} object; etag: {result.etag}") 40 | 41 | # Append data in chunks. 42 | data = urlopen( 43 | "https://www.kernel.org/pub/linux/kernel/v6.x/linux-6.13.12.tar.xz", 44 | ) 45 | result = client.append_object( 46 | "my-bucket", "my-object", data, 148611164, 5*1024*1024, 47 | ) 48 | print(f"appended {result.object_name} object; etag: {result.etag}") 49 | 50 | # Append unknown sized data. 51 | data = urlopen( 52 | "https://www.kernel.org/pub/linux/kernel/v6.x/linux-6.14.3.tar.xz", 53 | ) 54 | result = client.append_object( 55 | "my-bucket", "my-object", data, 149426584, 5*1024*1024, 56 | ) 57 | print(f"appended {result.object_name} object; etag: {result.etag}") 58 | -------------------------------------------------------------------------------- /examples/bucket_exists.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | if client.bucket_exists("my-bucket"): 26 | print("my-bucket exists") 27 | else: 28 | print("my-bucket does not exist") 29 | -------------------------------------------------------------------------------- /examples/compose_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import ComposeSource 19 | from minio.sse import SseS3 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | sources = [ 28 | ComposeSource("my-job-bucket", "my-object-part-one"), 29 | ComposeSource("my-job-bucket", "my-object-part-two"), 30 | ComposeSource("my-job-bucket", "my-object-part-three"), 31 | ] 32 | 33 | # Create my-bucket/my-object by combining source object 34 | # list. 35 | result = client.compose_object("my-bucket", "my-object", sources) 36 | print(result.object_name, result.version_id) 37 | 38 | # Create my-bucket/my-object with user metadata by combining 39 | # source object list. 40 | result = client.compose_object( 41 | "my-bucket", 42 | "my-object", 43 | sources, 44 | metadata={"test_meta_key": "test_meta_value"}, 45 | ) 46 | print(result.object_name, result.version_id) 47 | 48 | # Create my-bucket/my-object with user metadata and 49 | # server-side encryption by combining source object list. 50 | client.compose_object("my-bucket", "my-object", sources, sse=SseS3()) 51 | print(result.object_name, result.version_id) 52 | -------------------------------------------------------------------------------- /examples/copy_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2016-2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import datetime, timezone 18 | 19 | from minio import Minio 20 | from minio.commonconfig import REPLACE, CopySource 21 | 22 | client = Minio( 23 | "play.min.io", 24 | access_key="Q3AM3UQ867SPQQA43P2F", 25 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 26 | ) 27 | 28 | # copy an object from a bucket to another. 29 | result = client.copy_object( 30 | "my-bucket", 31 | "my-object", 32 | CopySource("my-sourcebucket", "my-sourceobject"), 33 | ) 34 | print(result.object_name, result.version_id) 35 | 36 | # copy an object with condition. 37 | result = client.copy_object( 38 | "my-bucket", 39 | "my-object", 40 | CopySource( 41 | "my-sourcebucket", 42 | "my-sourceobject", 43 | modified_since=datetime(2014, 4, 1, tzinfo=timezone.utc), 44 | ), 45 | ) 46 | print(result.object_name, result.version_id) 47 | 48 | # copy an object from a bucket with replacing metadata. 49 | metadata = {"test_meta_key": "test_meta_value"} 50 | result = client.copy_object( 51 | "my-bucket", 52 | "my-object", 53 | CopySource("my-sourcebucket", "my-sourceobject"), 54 | metadata=metadata, 55 | metadata_directive=REPLACE, 56 | ) 57 | print(result.object_name, result.version_id) 58 | -------------------------------------------------------------------------------- /examples/delete_bucket_encryption.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_encryption("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_bucket_lifecycle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_lifecycle("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_bucket_notification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_notification("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_bucket_policy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_policy("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_bucket_replication.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_replication("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_bucket_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_bucket_tags("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_object_lock_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_object_lock_config("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/delete_object_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.delete_object_tags("my-bucket", "my-object") 26 | -------------------------------------------------------------------------------- /examples/disable_object_legal_hold.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.disable_object_legal_hold("my-bucket", "my-object") 26 | -------------------------------------------------------------------------------- /examples/enable_object_legal_hold.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.enable_object_legal_hold("my-bucket", "my-object") 26 | -------------------------------------------------------------------------------- /examples/fget_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.sse import SseCustomerKey 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | # Download data of an object. 27 | client.fget_object("my-bucket", "my-object", "my-filename") 28 | 29 | # Download data of an object of version-ID. 30 | client.fget_object( 31 | "my-bucket", "my-object", "my-filename", 32 | version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", 33 | ) 34 | 35 | # Download data of an SSE-C encrypted object. 36 | client.fget_object( 37 | "my-bucket", "my-object", "my-filename", 38 | ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), 39 | ) 40 | -------------------------------------------------------------------------------- /examples/fput_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import datetime, timedelta 18 | 19 | from examples.progress import Progress 20 | from minio import Minio 21 | from minio.commonconfig import GOVERNANCE, Tags 22 | from minio.retention import Retention 23 | from minio.sse import SseCustomerKey, SseKMS, SseS3 24 | 25 | client = Minio( 26 | "play.min.io", 27 | access_key="Q3AM3UQ867SPQQA43P2F", 28 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 29 | ) 30 | 31 | # Upload data. 32 | result = client.fput_object( 33 | "my-bucket", "my-object", "my-filename", 34 | ) 35 | print( 36 | "created {0} object; etag: {1}, version-id: {2}".format( 37 | result.object_name, result.etag, result.version_id, 38 | ), 39 | ) 40 | 41 | # Upload data with content-type. 42 | result = client.fput_object( 43 | "my-bucket", "my-object", "my-filename", 44 | content_type="application/csv", 45 | ) 46 | print( 47 | "created {0} object; etag: {1}, version-id: {2}".format( 48 | result.object_name, result.etag, result.version_id, 49 | ), 50 | ) 51 | 52 | # Upload data with metadata. 53 | result = client.fput_object( 54 | "my-bucket", "my-object", "my-filename", 55 | metadata={"My-Project": "one"}, 56 | ) 57 | print( 58 | "created {0} object; etag: {1}, version-id: {2}".format( 59 | result.object_name, result.etag, result.version_id, 60 | ), 61 | ) 62 | 63 | # Upload data with customer key type of server-side encryption. 64 | result = client.fput_object( 65 | "my-bucket", "my-object", "my-filename", 66 | sse=SseCustomerKey(b"32byteslongsecretkeymustprovided"), 67 | ) 68 | print( 69 | "created {0} object; etag: {1}, version-id: {2}".format( 70 | result.object_name, result.etag, result.version_id, 71 | ), 72 | ) 73 | 74 | # Upload data with KMS type of server-side encryption. 75 | result = client.fput_object( 76 | "my-bucket", "my-object", "my-filename", 77 | sse=SseKMS("KMS-KEY-ID", {"Key1": "Value1", "Key2": "Value2"}), 78 | ) 79 | print( 80 | "created {0} object; etag: {1}, version-id: {2}".format( 81 | result.object_name, result.etag, result.version_id, 82 | ), 83 | ) 84 | 85 | # Upload data with S3 type of server-side encryption. 86 | result = client.fput_object( 87 | "my-bucket", "my-object", "my-filename", 88 | sse=SseS3(), 89 | ) 90 | print( 91 | "created {0} object; etag: {1}, version-id: {2}".format( 92 | result.object_name, result.etag, result.version_id, 93 | ), 94 | ) 95 | 96 | # Upload data with tags, retention and legal-hold. 97 | date = datetime.utcnow().replace( 98 | hour=0, minute=0, second=0, microsecond=0, 99 | ) + timedelta(days=30) 100 | tags = Tags(for_object=True) 101 | tags["User"] = "jsmith" 102 | result = client.fput_object( 103 | "my-bucket", "my-object", "my-filename", 104 | tags=tags, 105 | retention=Retention(GOVERNANCE, date), 106 | legal_hold=True, 107 | ) 108 | print( 109 | "created {0} object; etag: {1}, version-id: {2}".format( 110 | result.object_name, result.etag, result.version_id, 111 | ), 112 | ) 113 | 114 | # Upload data with progress bar. 115 | result = client.fput_object( 116 | "my-bucket", "my-object", "my-filename", 117 | progress=Progress(), 118 | ) 119 | print( 120 | "created {0} object; etag: {1}, version-id: {2}".format( 121 | result.object_name, result.etag, result.version_id, 122 | ), 123 | ) 124 | -------------------------------------------------------------------------------- /examples/get_bucket_encryption.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_bucket_encryption("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_lifecycle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_bucket_lifecycle("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_notification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_bucket_notification("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_policy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | policy = client.get_bucket_policy("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_replication.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_bucket_replication("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | tags = client.get_bucket_tags("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_bucket_versioning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_bucket_versioning("my-bucket") 26 | print(config.status) 27 | -------------------------------------------------------------------------------- /examples/get_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.sse import SseCustomerKey 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | # Get data of an object. 27 | response = None 28 | try: 29 | response = client.get_object("my-bucket", "my-object") 30 | # Read data from response. 31 | finally: 32 | if response: 33 | response.close() 34 | response.release_conn() 35 | 36 | # Get data of an object of version-ID. 37 | response = None 38 | try: 39 | response = client.get_object( 40 | "my-bucket", "my-object", 41 | version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", 42 | ) 43 | # Read data from response. 44 | finally: 45 | if response: 46 | response.close() 47 | response.release_conn() 48 | 49 | # Get data of an object from offset and length. 50 | response = None 51 | try: 52 | response = client.get_object( 53 | "my-bucket", "my-object", offset=512, length=1024, 54 | ) 55 | # Read data from response. 56 | finally: 57 | if response: 58 | response.close() 59 | response.release_conn() 60 | 61 | # Get data of an SSE-C encrypted object. 62 | response = None 63 | try: 64 | response = client.get_object( 65 | "my-bucket", "my-object", 66 | ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), 67 | ) 68 | # Read data from response. 69 | finally: 70 | if response: 71 | response.close() 72 | response.release_conn() 73 | -------------------------------------------------------------------------------- /examples/get_object_lock_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_object_lock_config("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/get_object_retention.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | config = client.get_object_retention("my-bucket", "my-object") 26 | -------------------------------------------------------------------------------- /examples/get_object_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | tags = client.get_object_tags("my-bucket", "my-object") 26 | -------------------------------------------------------------------------------- /examples/get_presigned_url.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import timedelta 18 | 19 | from minio import Minio 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | # Get presigned URL string to delete 'my-object' in 28 | # 'my-bucket' with one day expiry. 29 | url = client.get_presigned_url( 30 | "DELETE", 31 | "my-bucket", 32 | "my-object", 33 | expires=timedelta(days=1), 34 | ) 35 | print(url) 36 | 37 | # Get presigned URL string to upload 'my-object' in 38 | # 'my-bucket' with response-content-type as application/json 39 | # and one day expiry. 40 | url = client.get_presigned_url( 41 | "PUT", 42 | "my-bucket", 43 | "my-object", 44 | expires=timedelta(days=1), 45 | response_headers={"response-content-type": "application/json"}, 46 | ) 47 | print(url) 48 | 49 | # Get presigned URL string to download 'my-object' in 50 | # 'my-bucket' with two hours expiry. 51 | url = client.get_presigned_url( 52 | "GET", 53 | "my-bucket", 54 | "my-object", 55 | expires=timedelta(hours=2), 56 | ) 57 | print(url) 58 | -------------------------------------------------------------------------------- /examples/is_object_legal_hold_enabled.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | if client.is_object_legal_hold_enabled("my-bucket", "my-object"): 26 | print("legal hold is enabled on my-object") 27 | else: 28 | print("legal hold is not enabled on my-object") 29 | -------------------------------------------------------------------------------- /examples/list_buckets.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | buckets = client.list_buckets() 26 | for bucket in buckets: 27 | print(bucket.name, bucket.creation_date) 28 | -------------------------------------------------------------------------------- /examples/list_objects.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | # List objects information. 26 | objects = client.list_objects("my-bucket") 27 | for obj in objects: 28 | print(obj) 29 | 30 | # List objects information whose names starts with "my/prefix/". 31 | objects = client.list_objects("my-bucket", prefix="my/prefix/") 32 | for obj in objects: 33 | print(obj) 34 | 35 | # List objects information recursively. 36 | objects = client.list_objects("my-bucket", recursive=True) 37 | for obj in objects: 38 | print(obj) 39 | 40 | # List objects information recursively whose names starts with 41 | # "my/prefix/". 42 | objects = client.list_objects( 43 | "my-bucket", prefix="my/prefix/", recursive=True, 44 | ) 45 | for obj in objects: 46 | print(obj) 47 | 48 | # List objects information recursively after object name 49 | # "my/prefix/world/1". 50 | objects = client.list_objects( 51 | "my-bucket", recursive=True, start_after="my/prefix/world/1", 52 | ) 53 | for obj in objects: 54 | print(obj) 55 | -------------------------------------------------------------------------------- /examples/listen_bucket_notification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | with client.listen_bucket_notification( 26 | "my-bucket", 27 | prefix="my-prefix/", 28 | events=["s3:ObjectCreated:*", "s3:ObjectRemoved:*"], 29 | ) as events: 30 | for event in events: 31 | print(event) 32 | -------------------------------------------------------------------------------- /examples/make_bucket.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | # Create bucket. 26 | client.make_bucket("my-bucket") 27 | 28 | # Create bucket on specific region. 29 | client.make_bucket("my-bucket", "us-west-1") 30 | 31 | # Create bucket with object-lock feature on specific region. 32 | client.make_bucket("my-bucket", "eu-west-2", object_lock=True) 33 | -------------------------------------------------------------------------------- /examples/minio_with_assume_role_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import AssumeRoleProvider 20 | 21 | # STS endpoint usually point to MinIO server. 22 | sts_endpoint = "http://STS-HOST:STS-PORT/" 23 | 24 | # Access key to fetch credentials from STS endpoint. 25 | access_key = "YOUR-ACCESSKEY" 26 | 27 | # Secret key to fetch credentials from STS endpoint. 28 | secret_key = "YOUR-SECRETACCESSKEY" 29 | 30 | # Role ARN if available. 31 | role_arn = "ROLE-ARN" 32 | 33 | # Role session name if available. 34 | role_session_name = "ROLE-SESSION-NAME" 35 | 36 | # External ID if available. 37 | external_id = "EXTERNAL-ID" 38 | 39 | # Policy if available. 40 | policy = "POLICY" 41 | 42 | # Region if available. 43 | region = "REGION" 44 | 45 | provider = AssumeRoleProvider( 46 | sts_endpoint, 47 | access_key, 48 | secret_key, 49 | policy=policy, 50 | region=region, 51 | role_arn=role_arn, 52 | role_session_name=role_session_name, 53 | external_id=external_id, 54 | ) 55 | 56 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) 57 | 58 | # Get information of an object. 59 | stat = client.stat_object("my-bucket", "my-object") 60 | print(stat) 61 | -------------------------------------------------------------------------------- /examples/minio_with_aws_config_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import AWSConfigProvider 20 | 21 | client = Minio("s3.amazonaws.com", credentials=AWSConfigProvider()) 22 | 23 | # Get information of an object. 24 | stat = client.stat_object("my-bucket", "my-object") 25 | print(stat) 26 | -------------------------------------------------------------------------------- /examples/minio_with_certificate_identity_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2022 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import CertificateIdentityProvider 20 | 21 | # STS endpoint usually point to MinIO server. 22 | sts_endpoint = "https://STS-HOST:STS-PORT/" 23 | 24 | # client certificate file 25 | cert_file = "/path/to/client.pem" 26 | 27 | # client private key 28 | key_file = "/path/to/client.key" 29 | 30 | provider = CertificateIdentityProvider( 31 | sts_endpoint, cert_file=cert_file, key_file=key_file, 32 | ) 33 | 34 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) 35 | 36 | # Get information of an object. 37 | stat = client.stat_object("my-bucket", "my-object") 38 | print(stat) 39 | -------------------------------------------------------------------------------- /examples/minio_with_chained_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | # A Chain credentials provider, provides a way of chaining multiple providers 18 | # together and will pick the first available using priority order of the 19 | # 'providers' list 20 | 21 | from minio import Minio 22 | from minio.credentials import (AWSConfigProvider, ChainedProvider, 23 | EnvAWSProvider, IamAwsProvider) 24 | 25 | client = Minio( 26 | "s3.amazonaws.com", 27 | credentials=ChainedProvider( 28 | [ 29 | IamAwsProvider(), 30 | AWSConfigProvider(), 31 | EnvAWSProvider(), 32 | ] 33 | ) 34 | ) 35 | 36 | # Get information of an object. 37 | stat = client.stat_object("my-bucket", "my-object") 38 | print(stat) 39 | -------------------------------------------------------------------------------- /examples/minio_with_client_grants_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import json 18 | 19 | import urllib3 20 | 21 | from minio import Minio 22 | from minio.credentials import ClientGrantsProvider 23 | 24 | 25 | def get_jwt(client_id, client_secret, idp_endpoint): 26 | res = urllib3.PoolManager().request( 27 | "POST", 28 | idp_endpoint, 29 | fields={ 30 | "username": client_id, 31 | "password": client_secret, 32 | "grant_type": "client_credentials", 33 | }, 34 | ) 35 | 36 | return json.loads(res.data.encode()) 37 | 38 | 39 | # IDP endpoint. 40 | idp_endpoint = ( 41 | "https://IDP-HOST:IDP-PORT/auth/realms/master" 42 | "/protocol/openid-connect/token" 43 | ) 44 | 45 | # Client-ID to fetch JWT. 46 | client_id = "USER-ID" 47 | 48 | # Client secret to fetch JWT. 49 | client_secret = "PASSWORD" 50 | 51 | # STS endpoint usually point to MinIO server. 52 | sts_endpoint = "http://STS-HOST:STS-PORT/" 53 | 54 | provider = ClientGrantsProvider( 55 | lambda: get_jwt(client_id, client_secret, idp_endpoint), sts_endpoint, 56 | ) 57 | 58 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) 59 | 60 | # Get information of an object. 61 | stat = client.stat_object("my-bucket", "my-object") 62 | print(stat) 63 | -------------------------------------------------------------------------------- /examples/minio_with_env_aws_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import EnvAWSProvider 20 | 21 | client = Minio("s3.amazonaws.com", credentials=EnvAWSProvider()) 22 | 23 | # Get information of an object. 24 | stat = client.stat_object("my-bucket", "my-object") 25 | print(stat) 26 | -------------------------------------------------------------------------------- /examples/minio_with_env_minio_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import EnvMinioProvider 20 | 21 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=EnvMinioProvider()) 22 | 23 | # Get information of an object. 24 | stat = client.stat_object("my-bucket", "my-object") 25 | print(stat) 26 | -------------------------------------------------------------------------------- /examples/minio_with_iam_aws_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import IamAwsProvider 20 | 21 | client = Minio("s3.amazonaws.com", credentials=IamAwsProvider()) 22 | 23 | # Get information of an object. 24 | stat = client.stat_object("my-bucket", "my-object") 25 | print(stat) 26 | -------------------------------------------------------------------------------- /examples/minio_with_ldap_identity_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import LdapIdentityProvider 20 | 21 | # STS endpoint usually point to MinIO server. 22 | sts_endpoint = "http://STS-HOST:STS-PORT/" 23 | 24 | # LDAP username. 25 | ldap_username = "LDAP-USERNAME" 26 | 27 | # LDAP password. 28 | ldap_password = "LDAP-PASSWORD" 29 | 30 | provider = LdapIdentityProvider(sts_endpoint, ldap_username, ldap_password) 31 | 32 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) 33 | 34 | # Get information of an object. 35 | stat = client.stat_object("my-bucket", "my-object") 36 | print(stat) 37 | -------------------------------------------------------------------------------- /examples/minio_with_minio_client_config_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | from minio import Minio 19 | from minio.credentials import MinioClientConfigProvider 20 | 21 | client = Minio( 22 | "MINIO-HOST:MINIO-PORT", credentials=MinioClientConfigProvider(), 23 | ) 24 | 25 | # Get information of an object. 26 | stat = client.stat_object("my-bucket", "my-object") 27 | print(stat) 28 | -------------------------------------------------------------------------------- /examples/minio_with_web_identity_provider.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | import json 19 | 20 | import urllib3 21 | 22 | from minio import Minio 23 | from minio.credentials import WebIdentityProvider 24 | 25 | 26 | def get_jwt(client_id, client_secret, idp_client_id, idp_endpoint): 27 | res = urllib3.PoolManager().request( 28 | "POST", 29 | idp_endpoint, 30 | fields={ 31 | "username": client_id, 32 | "password": client_secret, 33 | "grant_type": "password", 34 | "client_id": idp_client_id, 35 | }, 36 | ) 37 | 38 | return json.loads(res.data.encode()) 39 | 40 | 41 | # IDP endpoint. 42 | idp_endpoint = ( 43 | "https://IDP-HOST:IDP-PORT/auth/realms/master" 44 | "/protocol/openid-connect/token" 45 | ) 46 | 47 | # Client-ID to fetch JWT. 48 | client_id = "USER-ID" 49 | 50 | # Client secret to fetch JWT. 51 | client_secret = "PASSWORD" 52 | 53 | # Client-ID of MinIO service on IDP. 54 | idp_client_id = "MINIO-CLIENT-ID" 55 | 56 | # STS endpoint usually point to MinIO server. 57 | sts_endpoint = "http://STS-HOST:STS-PORT/" 58 | 59 | # Role ARN if available. 60 | role_arn = "ROLE-ARN" 61 | 62 | # Role session name if available. 63 | role_session_name = "ROLE-SESSION-NAME" 64 | 65 | provider = WebIdentityProvider( 66 | lambda: get_jwt(client_id, client_secret, idp_client_id, idp_endpoint), 67 | sts_endpoint, 68 | role_arn=role_arn, 69 | role_session_name=role_session_name, 70 | ) 71 | 72 | client = Minio("MINIO-HOST:MINIO-PORT", credentials=provider) 73 | 74 | # Get information of an object. 75 | stat = client.stat_object("my-bucket", "my-object") 76 | print(stat) 77 | -------------------------------------------------------------------------------- /examples/presigned_get_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import timedelta 18 | 19 | from minio import Minio 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | # Get presigned URL string to download 'my-object' in 28 | # 'my-bucket' with default expiry (i.e. 7 days). 29 | url = client.presigned_get_object("my-bucket", "my-object") 30 | print(url) 31 | 32 | # Get presigned URL string to download 'my-object' in 33 | # 'my-bucket' with two hours expiry. 34 | url = client.presigned_get_object( 35 | "my-bucket", "my-object", expires=timedelta(hours=2), 36 | ) 37 | print(url) 38 | -------------------------------------------------------------------------------- /examples/presigned_post_policy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 to 2023 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import datetime, timedelta 18 | 19 | from minio import Minio 20 | from minio.datatypes import PostPolicy 21 | 22 | client = Minio( 23 | "play.min.io", 24 | access_key="Q3AM3UQ867SPQQA43P2F", 25 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 26 | ) 27 | 28 | policy = PostPolicy( 29 | "my-bucket", datetime.utcnow() + timedelta(days=10), 30 | ) 31 | policy.add_starts_with_condition("key", "my/object/prefix/") 32 | policy.add_content_length_range_condition(1*1024*1024, 10*1024*1024) 33 | 34 | form_data = client.presigned_post_policy(policy) 35 | 36 | curl_cmd = ( 37 | "curl -X POST " 38 | "https://play.min.io/my-bucket " 39 | "{0} -F file=@ -F key=" 40 | ).format( 41 | " ".join(["-F {0}={1}".format(k, v) for k, v in form_data.items()]), 42 | ) 43 | print(curl_cmd) 44 | -------------------------------------------------------------------------------- /examples/presigned_put_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import timedelta 18 | 19 | from minio import Minio 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | # Get presigned URL string to upload data to 'my-object' in 28 | # 'my-bucket' with default expiry (i.e. 7 days). 29 | url = client.presigned_put_object("my-bucket", "my-object") 30 | print(url) 31 | 32 | # Get presigned URL string to upload data to 'my-object' in 33 | # 'my-bucket' with two hours expiry. 34 | url = client.presigned_put_object( 35 | "my-bucket", "my-object", expires=timedelta(hours=2), 36 | ) 37 | print(url) 38 | -------------------------------------------------------------------------------- /examples/put_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import io 18 | from datetime import datetime, timedelta 19 | from urllib.request import urlopen 20 | 21 | from examples.progress import Progress 22 | from minio import Minio 23 | from minio.commonconfig import GOVERNANCE, Tags 24 | from minio.retention import Retention 25 | from minio.sse import SseCustomerKey, SseKMS, SseS3 26 | 27 | client = Minio( 28 | "play.min.io", 29 | access_key="Q3AM3UQ867SPQQA43P2F", 30 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 31 | ) 32 | 33 | # Upload data. 34 | result = client.put_object( 35 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 36 | ) 37 | print( 38 | "created {0} object; etag: {1}, version-id: {2}".format( 39 | result.object_name, result.etag, result.version_id, 40 | ), 41 | ) 42 | 43 | # Upload unknown sized data. 44 | data = urlopen( 45 | "https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.4.81.tar.xz", 46 | ) 47 | result = client.put_object( 48 | "my-bucket", "my-object", data, length=-1, part_size=10*1024*1024, 49 | ) 50 | print( 51 | "created {0} object; etag: {1}, version-id: {2}".format( 52 | result.object_name, result.etag, result.version_id, 53 | ), 54 | ) 55 | 56 | # Upload data with content-type. 57 | result = client.put_object( 58 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 59 | content_type="application/csv", 60 | ) 61 | print( 62 | "created {0} object; etag: {1}, version-id: {2}".format( 63 | result.object_name, result.etag, result.version_id, 64 | ), 65 | ) 66 | 67 | # Upload data with metadata. 68 | result = client.put_object( 69 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 70 | metadata={"My-Project": "one"}, 71 | ) 72 | print( 73 | "created {0} object; etag: {1}, version-id: {2}".format( 74 | result.object_name, result.etag, result.version_id, 75 | ), 76 | ) 77 | 78 | # Upload data with customer key type of server-side encryption. 79 | result = client.put_object( 80 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 81 | sse=SseCustomerKey(b"32byteslongsecretkeymustprovided"), 82 | ) 83 | print( 84 | "created {0} object; etag: {1}, version-id: {2}".format( 85 | result.object_name, result.etag, result.version_id, 86 | ), 87 | ) 88 | 89 | # Upload data with KMS type of server-side encryption. 90 | result = client.put_object( 91 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 92 | sse=SseKMS("KMS-KEY-ID", {"Key1": "Value1", "Key2": "Value2"}), 93 | ) 94 | print( 95 | "created {0} object; etag: {1}, version-id: {2}".format( 96 | result.object_name, result.etag, result.version_id, 97 | ), 98 | ) 99 | 100 | # Upload data with S3 type of server-side encryption. 101 | result = client.put_object( 102 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 103 | sse=SseS3(), 104 | ) 105 | print( 106 | "created {0} object; etag: {1}, version-id: {2}".format( 107 | result.object_name, result.etag, result.version_id, 108 | ), 109 | ) 110 | 111 | # Upload data with tags, retention and legal-hold. 112 | date = datetime.utcnow().replace( 113 | hour=0, minute=0, second=0, microsecond=0, 114 | ) + timedelta(days=30) 115 | tags = Tags(for_object=True) 116 | tags["User"] = "jsmith" 117 | result = client.put_object( 118 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 119 | tags=tags, 120 | retention=Retention(GOVERNANCE, date), 121 | legal_hold=True, 122 | ) 123 | print( 124 | "created {0} object; etag: {1}, version-id: {2}".format( 125 | result.object_name, result.etag, result.version_id, 126 | ), 127 | ) 128 | 129 | # Upload data with progress bar. 130 | result = client.put_object( 131 | "my-bucket", "my-object", io.BytesIO(b"hello"), 5, 132 | progress=Progress(), 133 | ) 134 | print( 135 | "created {0} object; etag: {1}, version-id: {2}".format( 136 | result.object_name, result.etag, result.version_id, 137 | ), 138 | ) 139 | -------------------------------------------------------------------------------- /examples/remove_bucket.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | client.remove_bucket("my-bucket") 26 | -------------------------------------------------------------------------------- /examples/remove_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | 19 | client = Minio( 20 | "play.min.io", 21 | access_key="Q3AM3UQ867SPQQA43P2F", 22 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 23 | ) 24 | 25 | # Remove object. 26 | client.remove_object("my-bucket", "my-object") 27 | 28 | # Remove version of an object. 29 | client.remove_object( 30 | "my-bucket", "my-object", 31 | version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", 32 | ) 33 | -------------------------------------------------------------------------------- /examples/remove_objects.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.deleteobjects import DeleteObject 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | # Remove list of objects. 27 | errors = client.remove_objects( 28 | "my-bucket", 29 | [ 30 | DeleteObject("my-object1"), 31 | DeleteObject("my-object2"), 32 | DeleteObject("my-object3", "13f88b18-8dcd-4c83-88f2-8631fdb6250c"), 33 | ], 34 | ) 35 | for error in errors: 36 | print("error occurred when deleting object", error) 37 | 38 | # Remove a prefix recursively. 39 | delete_object_list = map( 40 | lambda x: DeleteObject(x.object_name), 41 | client.list_objects("my-bucket", "my/prefix/", recursive=True), 42 | ) 43 | errors = client.remove_objects("my-bucket", delete_object_list) 44 | for error in errors: 45 | print("error occurred when deleting object", error) 46 | -------------------------------------------------------------------------------- /examples/select_object_content.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2019 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from minio import Minio 19 | from minio.select import (CSVInputSerialization, CSVOutputSerialization, 20 | SelectRequest) 21 | 22 | client = Minio( 23 | "play.min.io", 24 | access_key="Q3AM3UQ867SPQQA43P2F", 25 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 26 | ) 27 | 28 | with client.select_object_content( 29 | "my-bucket", 30 | "my-object.csv", 31 | SelectRequest( 32 | "select * from S3Object", 33 | CSVInputSerialization(), 34 | CSVOutputSerialization(), 35 | request_progress=True, 36 | ), 37 | ) as result: 38 | for data in result.stream(): 39 | print(data.decode()) 40 | print(result.stats()) 41 | -------------------------------------------------------------------------------- /examples/set_bucket_encryption.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.sseconfig import Rule, SSEConfig 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | client.set_bucket_encryption( 27 | "my-bucket", SSEConfig(Rule.new_sse_s3_rule()), 28 | ) 29 | -------------------------------------------------------------------------------- /examples/set_bucket_lifecycle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import ENABLED, Filter 19 | from minio.lifecycleconfig import Expiration, LifecycleConfig, Rule, Transition 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | config = LifecycleConfig( 28 | [ 29 | Rule( 30 | ENABLED, 31 | rule_filter=Filter(prefix="documents/"), 32 | rule_id="rule1", 33 | transition=Transition(days=30, storage_class="GLACIER"), 34 | ), 35 | Rule( 36 | ENABLED, 37 | rule_filter=Filter(prefix="logs/"), 38 | rule_id="rule2", 39 | expiration=Expiration(days=365), 40 | ), 41 | ], 42 | ) 43 | client.set_bucket_lifecycle("my-bucket", config) 44 | -------------------------------------------------------------------------------- /examples/set_bucket_notification.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.notificationconfig import (NotificationConfig, PrefixFilterRule, 19 | QueueConfig) 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | config = NotificationConfig( 28 | queue_config_list=[ 29 | QueueConfig( 30 | "QUEUE-ARN-OF-THIS-BUCKET", 31 | ["s3:ObjectCreated:*"], 32 | config_id="1", 33 | prefix_filter_rule=PrefixFilterRule("abc"), 34 | ), 35 | ], 36 | ) 37 | client.set_bucket_notification("my-bucket", config) 38 | -------------------------------------------------------------------------------- /examples/set_bucket_policy.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import json 18 | 19 | from minio import Minio 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | # Example anonymous read-only bucket policy. 28 | policy = { 29 | "Version": "2012-10-17", 30 | "Statement": [ 31 | { 32 | "Effect": "Allow", 33 | "Principal": {"AWS": "*"}, 34 | "Action": ["s3:GetBucketLocation", "s3:ListBucket"], 35 | "Resource": "arn:aws:s3:::my-bucket", 36 | }, 37 | { 38 | "Effect": "Allow", 39 | "Principal": {"AWS": "*"}, 40 | "Action": "s3:GetObject", 41 | "Resource": "arn:aws:s3:::my-bucket/*", 42 | }, 43 | ], 44 | } 45 | client.set_bucket_policy("my-bucket", json.dumps(policy)) 46 | 47 | # Example anonymous read-write bucket policy. 48 | policy = { 49 | "Version": "2012-10-17", 50 | "Statement": [ 51 | { 52 | "Effect": "Allow", 53 | "Principal": {"AWS": "*"}, 54 | "Action": [ 55 | "s3:GetBucketLocation", 56 | "s3:ListBucket", 57 | "s3:ListBucketMultipartUploads", 58 | ], 59 | "Resource": "arn:aws:s3:::my-bucket", 60 | }, 61 | { 62 | "Effect": "Allow", 63 | "Principal": {"AWS": "*"}, 64 | "Action": [ 65 | "s3:GetObject", 66 | "s3:PutObject", 67 | "s3:DeleteObject", 68 | "s3:ListMultipartUploadParts", 69 | "s3:AbortMultipartUpload", 70 | ], 71 | "Resource": "arn:aws:s3:::my-bucket/images/*", 72 | }, 73 | ], 74 | } 75 | client.set_bucket_policy("my-bucket", json.dumps(policy)) 76 | -------------------------------------------------------------------------------- /examples/set_bucket_replication.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import DISABLED, ENABLED, AndOperator, Filter 19 | from minio.replicationconfig import (DeleteMarkerReplication, Destination, 20 | ReplicationConfig, Rule) 21 | 22 | client = Minio( 23 | "play.min.io", 24 | access_key="Q3AM3UQ867SPQQA43P2F", 25 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 26 | ) 27 | 28 | config = ReplicationConfig( 29 | "REPLACE-WITH-ACTUAL-ROLE", 30 | [ 31 | Rule( 32 | Destination( 33 | "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", 34 | ), 35 | ENABLED, 36 | delete_marker_replication=DeleteMarkerReplication( 37 | DISABLED, 38 | ), 39 | rule_filter=Filter( 40 | AndOperator( 41 | "TaxDocs", 42 | {"key1": "value1", "key2": "value2"}, 43 | ), 44 | ), 45 | rule_id="rule1", 46 | priority=1, 47 | ), 48 | ], 49 | ) 50 | client.set_bucket_replication("my-bucket", config) 51 | -------------------------------------------------------------------------------- /examples/set_bucket_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import Tags 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | tags = Tags.new_bucket_tags() 27 | tags["Project"] = "Project One" 28 | tags["User"] = "jsmith" 29 | client.set_bucket_tags("my-bucket", tags) 30 | -------------------------------------------------------------------------------- /examples/set_bucket_versioning.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import ENABLED 19 | from minio.versioningconfig import VersioningConfig 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | client.set_bucket_versioning("my-bucket", VersioningConfig(ENABLED)) 28 | -------------------------------------------------------------------------------- /examples/set_object_lock_config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import GOVERNANCE 19 | from minio.objectlockconfig import DAYS, ObjectLockConfig 20 | 21 | client = Minio( 22 | "play.min.io", 23 | access_key="Q3AM3UQ867SPQQA43P2F", 24 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ) 26 | 27 | config = ObjectLockConfig(GOVERNANCE, 15, DAYS) 28 | client.set_object_lock_config("my-bucket", config) 29 | -------------------------------------------------------------------------------- /examples/set_object_retention.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import datetime, timedelta 18 | 19 | from minio import Minio 20 | from minio.commonconfig import GOVERNANCE 21 | from minio.retention import Retention 22 | 23 | client = Minio( 24 | "play.min.io", 25 | access_key="Q3AM3UQ867SPQQA43P2F", 26 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 27 | ) 28 | 29 | config = Retention(GOVERNANCE, datetime.utcnow() + timedelta(days=10)) 30 | client.set_object_retention("my-bucket", "my-object", config) 31 | -------------------------------------------------------------------------------- /examples/set_object_tags.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage. 3 | # Copyright (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.commonconfig import Tags 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | tags = Tags.new_object_tags() 27 | tags["Project"] = "Project One" 28 | tags["User"] = "jsmith" 29 | client.set_object_tags("my-bucket", "my-object", tags) 30 | -------------------------------------------------------------------------------- /examples/stat_object.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from minio import Minio 18 | from minio.sse import SseCustomerKey 19 | 20 | client = Minio( 21 | "play.min.io", 22 | access_key="Q3AM3UQ867SPQQA43P2F", 23 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 24 | ) 25 | 26 | # Get object information. 27 | result = client.stat_object("my-bucket", "my-object") 28 | print( 29 | "last-modified: {0}, size: {1}".format( 30 | result.last_modified, result.size, 31 | ), 32 | ) 33 | 34 | # Get object information of version-ID. 35 | result = client.stat_object( 36 | "my-bucket", "my-object", 37 | version_id="dfbd25b3-abec-4184-a4e8-5a35a5c1174d", 38 | ) 39 | print( 40 | "last-modified: {0}, size: {1}".format( 41 | result.last_modified, result.size, 42 | ), 43 | ) 44 | 45 | # Get SSE-C encrypted object information. 46 | result = client.stat_object( 47 | "my-bucket", "my-object", 48 | ssec=SseCustomerKey(b"32byteslongsecretkeymustprovided"), 49 | ) 50 | print( 51 | "last-modified: {0}, size: {1}".format( 52 | result.last_modified, result.size, 53 | ), 54 | ) 55 | -------------------------------------------------------------------------------- /examples/upload_snowball_objects.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2023 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import io 18 | from datetime import datetime 19 | 20 | from minio import Minio 21 | from minio.commonconfig import SnowballObject 22 | 23 | client = Minio( 24 | "play.min.io", 25 | access_key="Q3AM3UQ867SPQQA43P2F", 26 | secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 27 | ) 28 | 29 | client.upload_snowball_objects( 30 | "my-bucket", 31 | [ 32 | SnowballObject("my-object1", filename="/etc/hostname"), 33 | SnowballObject( 34 | "my-object2", data=io.BytesIO(b"hello"), length=5, 35 | ), 36 | SnowballObject( 37 | "my-object3", data=io.BytesIO(b"world"), length=5, 38 | mod_time=datetime.now(), 39 | ), 40 | ], 41 | ) 42 | -------------------------------------------------------------------------------- /minio/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015, 2016, 2017 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | minio - MinIO Python SDK for Amazon S3 Compatible Cloud Storage 19 | 20 | >>> from minio import Minio 21 | >>> client = Minio( 22 | ... "play.min.io", 23 | ... access_key="Q3AM3UQ867SPQQA43P2F", 24 | ... secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 25 | ... ) 26 | >>> buckets = client.list_buckets() 27 | >>> for bucket in buckets: 28 | ... print(bucket.name, bucket.creation_date) 29 | 30 | :copyright: (C) 2015-2020 MinIO, Inc. 31 | :license: Apache 2.0, see LICENSE for more details. 32 | """ 33 | 34 | __title__ = "minio-py" 35 | __author__ = "MinIO, Inc." 36 | __version__ = "7.2.16" 37 | __license__ = "Apache 2.0" 38 | __copyright__ = "Copyright 2015, 2016, 2017, 2018, 2019, 2020 MinIO, Inc." 39 | 40 | # pylint: disable=unused-import,useless-import-alias 41 | from .api import Minio as Minio 42 | from .error import InvalidResponseError as InvalidResponseError 43 | from .error import S3Error as S3Error 44 | from .error import ServerError as ServerError 45 | from .minioadmin import MinioAdmin as MinioAdmin 46 | -------------------------------------------------------------------------------- /minio/credentials/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Credential module.""" 18 | 19 | # pylint: disable=unused-import 20 | from .credentials import Credentials 21 | from .providers import (AssumeRoleProvider, AWSConfigProvider, 22 | CertificateIdentityProvider, ChainedProvider, 23 | ClientGrantsProvider, EnvAWSProvider, EnvMinioProvider, 24 | IamAwsProvider, LdapIdentityProvider, 25 | MinioClientConfigProvider, Provider, StaticProvider, 26 | WebIdentityProvider) 27 | -------------------------------------------------------------------------------- /minio/credentials/credentials.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Credential definitions to access S3 service.""" 18 | from __future__ import annotations 19 | 20 | from datetime import datetime, timedelta, timezone 21 | 22 | 23 | class Credentials: 24 | """ 25 | Represents credentials access key, secret key and session token. 26 | """ 27 | 28 | _access_key: str 29 | _secret_key: str 30 | _session_token: str | None 31 | _expiration: datetime | None 32 | 33 | def __init__( 34 | self, 35 | access_key: str, 36 | secret_key: str, 37 | session_token: str | None = None, 38 | expiration: datetime | None = None, 39 | ): 40 | if not access_key: 41 | raise ValueError("Access key must not be empty") 42 | 43 | if not secret_key: 44 | raise ValueError("Secret key must not be empty") 45 | 46 | self._access_key = access_key 47 | self._secret_key = secret_key 48 | self._session_token = session_token 49 | if expiration and expiration.tzinfo: 50 | expiration = ( 51 | expiration.astimezone(timezone.utc).replace(tzinfo=None) 52 | ) 53 | self._expiration = expiration 54 | 55 | @property 56 | def access_key(self) -> str: 57 | """Get access key.""" 58 | return self._access_key 59 | 60 | @property 61 | def secret_key(self) -> str: 62 | """Get secret key.""" 63 | return self._secret_key 64 | 65 | @property 66 | def session_token(self) -> str | None: 67 | """Get session token.""" 68 | return self._session_token 69 | 70 | def is_expired(self) -> bool: 71 | """Check whether this credentials expired or not.""" 72 | return ( 73 | self._expiration < (datetime.utcnow() + timedelta(seconds=10)) 74 | if self._expiration else False 75 | ) 76 | -------------------------------------------------------------------------------- /minio/legalhold.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Request/response of PutObjectLegalHold and GetObjectLegalHold S3 APIs.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | from typing import Type, TypeVar 22 | from xml.etree import ElementTree as ET 23 | 24 | from .xml import Element, SubElement, findtext 25 | 26 | A = TypeVar("A", bound="LegalHold") 27 | 28 | 29 | class LegalHold: 30 | """Legal hold configuration.""" 31 | 32 | def __init__(self, status: bool = False): 33 | self._status = status 34 | 35 | @property 36 | def status(self) -> bool: 37 | """Get status.""" 38 | return self._status 39 | 40 | @classmethod 41 | def fromxml(cls: Type[A], element: ET.Element) -> A: 42 | """Create new object with values from XML element.""" 43 | status = findtext(element, "Status") 44 | return cls(status == "ON") 45 | 46 | def toxml(self, element: ET.Element | None) -> ET.Element: 47 | """Convert to XML.""" 48 | element = Element("LegalHold") 49 | SubElement(element, "Status", "ON" if self._status is True else "OFF") 50 | return element 51 | -------------------------------------------------------------------------------- /minio/objectlockconfig.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | Request/response of PutObjectLockConfiguration and GetObjectLockConfiguration 19 | APIs. 20 | """ 21 | 22 | from __future__ import absolute_import, annotations 23 | 24 | from typing import Type, TypeVar, cast 25 | from xml.etree import ElementTree as ET 26 | 27 | from .commonconfig import COMPLIANCE, ENABLED, GOVERNANCE 28 | from .xml import Element, SubElement, find, findtext 29 | 30 | DAYS = "Days" 31 | YEARS = "Years" 32 | 33 | A = TypeVar("A", bound="ObjectLockConfig") 34 | 35 | 36 | class ObjectLockConfig: 37 | """Object lock configuration.""" 38 | 39 | def __init__( 40 | self, 41 | mode: str | None, 42 | duration: int | None, 43 | duration_unit: str | None, 44 | ): 45 | if (mode is not None) ^ (duration is not None): 46 | if mode is None: 47 | raise ValueError("mode must be provided") 48 | raise ValueError("duration must be provided") 49 | if mode is not None and mode not in [GOVERNANCE, COMPLIANCE]: 50 | raise ValueError(f"mode must be {GOVERNANCE} or {COMPLIANCE}") 51 | if duration_unit: 52 | duration_unit = duration_unit.title() 53 | if duration is not None and duration_unit not in [DAYS, YEARS]: 54 | raise ValueError(f"duration unit must be {DAYS} or {YEARS}") 55 | self._mode = mode 56 | self._duration = duration 57 | self._duration_unit = duration_unit 58 | 59 | @property 60 | def mode(self) -> str | None: 61 | """Get mode.""" 62 | return self._mode 63 | 64 | @property 65 | def duration(self) -> tuple[int | None, str | None]: 66 | """Get duration and it's unit.""" 67 | return self._duration, self._duration_unit 68 | 69 | @classmethod 70 | def fromxml(cls: Type[A], element: ET.Element) -> A: 71 | """Create new object with values from XML element.""" 72 | elem = find(element, "Rule") 73 | if elem is None: 74 | return cls(None, None, None) 75 | elem = cast(ET.Element, find(elem, "DefaultRetention", True)) 76 | mode = findtext(elem, "Mode") 77 | duration_unit = DAYS 78 | duration = findtext(elem, duration_unit) 79 | if not duration: 80 | duration_unit = YEARS 81 | duration = findtext(elem, duration_unit) 82 | if not duration: 83 | raise ValueError(f"XML element <{DAYS}> or <{YEARS}> not found") 84 | return cls(mode, int(duration), duration_unit) 85 | 86 | def toxml(self, element: ET.Element | None) -> ET.Element: 87 | """Convert to XML.""" 88 | element = Element("ObjectLockConfiguration") 89 | SubElement(element, "ObjectLockEnabled", ENABLED) 90 | if self._mode: 91 | rule = SubElement(element, "Rule") 92 | retention = SubElement(rule, "DefaultRetention") 93 | SubElement(retention, "Mode", self._mode) 94 | if not self._duration_unit: 95 | raise ValueError("duration unit must be provided") 96 | SubElement(retention, self._duration_unit, str(self._duration)) 97 | return element 98 | -------------------------------------------------------------------------------- /minio/py.typed: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minio/minio-py/817235ba9ae9b204db073901411e92f5aeabc3bd/minio/py.typed -------------------------------------------------------------------------------- /minio/retention.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Request/response of PutObjectRetention and GetObjectRetention APIs.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | from datetime import datetime 22 | from typing import Type, TypeVar, cast 23 | from xml.etree import ElementTree as ET 24 | 25 | from .commonconfig import COMPLIANCE, GOVERNANCE 26 | from .time import from_iso8601utc, to_iso8601utc 27 | from .xml import Element, SubElement, findtext 28 | 29 | A = TypeVar("A", bound="Retention") 30 | 31 | 32 | class Retention: 33 | """Retention configuration.""" 34 | 35 | def __init__(self, mode: str, retain_until_date: datetime): 36 | if mode not in [GOVERNANCE, COMPLIANCE]: 37 | raise ValueError(f"mode must be {GOVERNANCE} or {COMPLIANCE}") 38 | if not isinstance(retain_until_date, datetime): 39 | raise ValueError( 40 | "retain until date must be datetime type", 41 | ) 42 | self._mode = mode 43 | self._retain_until_date = retain_until_date 44 | 45 | @property 46 | def mode(self) -> str: 47 | """Get mode.""" 48 | return self._mode 49 | 50 | @property 51 | def retain_until_date(self) -> datetime: 52 | """Get retain util date.""" 53 | return self._retain_until_date 54 | 55 | @classmethod 56 | def fromxml(cls: Type[A], element: ET.Element) -> A: 57 | """Create new object with values from XML element.""" 58 | mode = cast(str, findtext(element, "Mode", True)) 59 | retain_until_date = cast( 60 | datetime, 61 | from_iso8601utc( 62 | cast(str, findtext(element, "RetainUntilDate", True)), 63 | ), 64 | ) 65 | return cls(mode, retain_until_date) 66 | 67 | def toxml(self, element: ET.Element | None) -> ET.Element: 68 | """Convert to XML.""" 69 | element = Element("Retention") 70 | SubElement(element, "Mode", self._mode) 71 | SubElement( 72 | element, 73 | "RetainUntilDate", 74 | to_iso8601utc(self._retain_until_date), 75 | ) 76 | return element 77 | -------------------------------------------------------------------------------- /minio/sse.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2018 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """ 18 | minio.sse 19 | ~~~~~~~~~~~~~~~~~~~ 20 | 21 | This module contains core API parsers. 22 | 23 | :copyright: (c) 2018 by MinIO, Inc. 24 | :license: Apache 2.0, see LICENSE for more details. 25 | 26 | """ 27 | from __future__ import absolute_import, annotations 28 | 29 | import base64 30 | import json 31 | from abc import ABCMeta, abstractmethod 32 | from typing import Any, cast 33 | 34 | 35 | class Sse: 36 | """Server-side encryption base class.""" 37 | __metaclass__ = ABCMeta 38 | 39 | @abstractmethod 40 | def headers(self) -> dict[str, str]: 41 | """Return headers.""" 42 | 43 | def tls_required(self) -> bool: # pylint: disable=no-self-use 44 | """Return TLS required to use this server-side encryption.""" 45 | return True 46 | 47 | def copy_headers(self) -> dict[str, str]: # pylint: disable=no-self-use 48 | """Return copy headers.""" 49 | return {} 50 | 51 | 52 | class SseCustomerKey(Sse): 53 | """ Server-side encryption - customer key type.""" 54 | 55 | def __init__(self, key: bytes): 56 | if len(key) != 32: 57 | raise ValueError( 58 | "SSE-C keys need to be 256 bit base64 encoded", 59 | ) 60 | b64key = base64.b64encode(key).decode() 61 | from .helpers import \ 62 | md5sum_hash # pylint: disable=import-outside-toplevel 63 | md5key = cast(str, md5sum_hash(key)) 64 | self._headers: dict[str, str] = { 65 | "X-Amz-Server-Side-Encryption-Customer-Algorithm": "AES256", 66 | "X-Amz-Server-Side-Encryption-Customer-Key": b64key, 67 | "X-Amz-Server-Side-Encryption-Customer-Key-MD5": md5key, 68 | } 69 | self._copy_headers: dict[str, str] = { 70 | "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Algorithm": 71 | "AES256", 72 | "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key": b64key, 73 | "X-Amz-Copy-Source-Server-Side-Encryption-Customer-Key-MD5": 74 | md5key, 75 | } 76 | 77 | def headers(self) -> dict[str, str]: 78 | return self._headers.copy() 79 | 80 | def copy_headers(self) -> dict[str, str]: 81 | return self._copy_headers.copy() 82 | 83 | 84 | class SseKMS(Sse): 85 | """Server-side encryption - KMS type.""" 86 | 87 | def __init__(self, key: str, context: dict[str, Any]): 88 | self._headers = { 89 | "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": key, 90 | "X-Amz-Server-Side-Encryption": "aws:kms" 91 | } 92 | if context: 93 | data = bytes(json.dumps(context), "utf-8") 94 | self._headers["X-Amz-Server-Side-Encryption-Context"] = ( 95 | base64.b64encode(data).decode() 96 | ) 97 | 98 | def headers(self) -> dict[str, str]: 99 | return self._headers.copy() 100 | 101 | 102 | class SseS3(Sse): 103 | """Server-side encryption - S3 type.""" 104 | 105 | def headers(self) -> dict[str, str]: 106 | return { 107 | "X-Amz-Server-Side-Encryption": "AES256" 108 | } 109 | 110 | def tls_required(self) -> bool: 111 | return False 112 | -------------------------------------------------------------------------------- /minio/sseconfig.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Request/response of PutBucketEncryption and GetBucketEncryption APIs.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | from abc import ABCMeta 22 | from typing import Type, TypeVar, cast 23 | from xml.etree import ElementTree as ET 24 | 25 | from .xml import Element, SubElement, find, findtext 26 | 27 | AES256 = "AES256" 28 | AWS_KMS = "aws:kms" 29 | 30 | A = TypeVar("A", bound="Rule") 31 | 32 | 33 | class Rule: 34 | """Server-side encryption rule. """ 35 | __metaclass__ = ABCMeta 36 | 37 | def __init__( 38 | self, 39 | sse_algorithm: str, 40 | kms_master_key_id: str | None = None, 41 | ): 42 | self._sse_algorithm = sse_algorithm 43 | self._kms_master_key_id = kms_master_key_id 44 | 45 | @property 46 | def sse_algorithm(self) -> str: 47 | """Get SSE algorithm.""" 48 | return self._sse_algorithm 49 | 50 | @property 51 | def kms_master_key_id(self) -> str | None: 52 | """Get KMS master key ID.""" 53 | return self._kms_master_key_id 54 | 55 | @classmethod 56 | def new_sse_s3_rule(cls: Type[A]) -> A: 57 | """Create SSE-S3 rule.""" 58 | return cls(AES256) 59 | 60 | @classmethod 61 | def new_sse_kms_rule( 62 | cls: Type[A], 63 | kms_master_key_id: str | None = None, 64 | ) -> A: 65 | """Create new SSE-KMS rule.""" 66 | return cls(AWS_KMS, kms_master_key_id) 67 | 68 | @classmethod 69 | def fromxml(cls: Type[A], element: ET.Element) -> A: 70 | """Create new object with values from XML element.""" 71 | element = cast( 72 | ET.Element, 73 | find(element, "ApplyServerSideEncryptionByDefault", True), 74 | ) 75 | return cls( 76 | cast(str, findtext(element, "SSEAlgorithm", True)), 77 | findtext(element, "KMSMasterKeyID"), 78 | ) 79 | 80 | def toxml(self, element: ET.Element | None) -> ET.Element: 81 | """Convert to XML.""" 82 | if element is None: 83 | raise ValueError("element must be provided") 84 | element = SubElement(element, "Rule") 85 | tag = SubElement(element, "ApplyServerSideEncryptionByDefault") 86 | SubElement(tag, "SSEAlgorithm", self._sse_algorithm) 87 | if self._kms_master_key_id is not None: 88 | SubElement(tag, "KMSMasterKeyID", self._kms_master_key_id) 89 | return element 90 | 91 | 92 | B = TypeVar("B", bound="SSEConfig") 93 | 94 | 95 | class SSEConfig: 96 | """server-side encryption configuration.""" 97 | 98 | def __init__(self, rule: Rule): 99 | if not rule: 100 | raise ValueError("rule must be provided") 101 | self._rule = rule 102 | 103 | @property 104 | def rule(self) -> Rule: 105 | """Get rule.""" 106 | return self._rule 107 | 108 | @classmethod 109 | def fromxml(cls: Type[B], element: ET.Element) -> B: 110 | """Create new object with values from XML element.""" 111 | element = cast(ET.Element, find(element, "Rule", True)) 112 | return cls(Rule.fromxml(element)) 113 | 114 | def toxml(self, element: ET.Element | None) -> ET.Element: 115 | """Convert to XML.""" 116 | element = Element("ServerSideEncryptionConfiguration") 117 | self._rule.toxml(element) 118 | return element 119 | -------------------------------------------------------------------------------- /minio/tagging.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Tagging for bucket and object.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | from typing import Type, TypeVar, cast 22 | from xml.etree import ElementTree as ET 23 | 24 | from .commonconfig import Tags 25 | from .xml import Element, SubElement, find 26 | 27 | A = TypeVar("A", bound="Tagging") 28 | 29 | 30 | class Tagging: 31 | """Tagging for buckets and objects.""" 32 | 33 | def __init__(self, tags: Tags | None): 34 | self._tags = tags 35 | 36 | @property 37 | def tags(self) -> Tags | None: 38 | """Get tags.""" 39 | return self._tags 40 | 41 | @classmethod 42 | def fromxml(cls: Type[A], element: ET.Element) -> A: 43 | """Create new object with values from XML element.""" 44 | element = cast(ET.Element, find(element, "TagSet", True)) 45 | tags = ( 46 | None if find(element, "Tag") is None 47 | else Tags.fromxml(element) 48 | ) 49 | return cls(tags) 50 | 51 | def toxml(self, element: ET.Element | None) -> ET.Element: 52 | """Convert to XML.""" 53 | element = Element("Tagging") 54 | if self._tags: 55 | self._tags.toxml(SubElement(element, "TagSet")) 56 | return element 57 | -------------------------------------------------------------------------------- /minio/time.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Time formatter for S3 APIs.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | import time as ctime 22 | from datetime import datetime, timezone 23 | 24 | try: 25 | from datetime import UTC # type: ignore[attr-defined] 26 | _UTC_IMPORTED = True 27 | except ImportError: 28 | _UTC_IMPORTED = False 29 | 30 | _WEEK_DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] 31 | _MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", 32 | "Nov", "Dec"] 33 | 34 | 35 | def _to_utc(value: datetime) -> datetime: 36 | """Convert to UTC time if value is not naive.""" 37 | return ( 38 | value.astimezone(timezone.utc).replace(tzinfo=None) 39 | if value.tzinfo else value 40 | ) 41 | 42 | 43 | def from_iso8601utc(value: str | None) -> datetime | None: 44 | """Parse UTC ISO-8601 formatted string to datetime.""" 45 | if value is None: 46 | return None 47 | 48 | try: 49 | time = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ") 50 | except ValueError: 51 | time = datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") 52 | return time.replace(tzinfo=timezone.utc) 53 | 54 | 55 | def to_iso8601utc(value: datetime | None) -> str | None: 56 | """Format datetime into UTC ISO-8601 formatted string.""" 57 | if value is None: 58 | return None 59 | 60 | value = _to_utc(value) 61 | return ( 62 | value.strftime("%Y-%m-%dT%H:%M:%S.") + value.strftime("%f")[:3] + "Z" 63 | ) 64 | 65 | 66 | def from_http_header(value: str) -> datetime: 67 | """Parse HTTP header date formatted string to datetime.""" 68 | if len(value) != 29: 69 | raise ValueError( 70 | f"time data {value} does not match HTTP header format") 71 | 72 | if value[0:3] not in _WEEK_DAYS or value[3] != ",": 73 | raise ValueError( 74 | f"time data {value} does not match HTTP header format") 75 | weekday = _WEEK_DAYS.index(value[0:3]) 76 | 77 | if value[4] != " " or value[7] != " ": 78 | raise ValueError( 79 | f"time data {value} does not match HTTP header format" 80 | ) 81 | day = int(value[5:7]) 82 | 83 | if value[8:11] not in _MONTHS: 84 | raise ValueError( 85 | f"time data {value} does not match HTTP header format") 86 | month = _MONTHS.index(value[8:11]) 87 | 88 | time = datetime.strptime(value[11:], " %Y %H:%M:%S GMT") 89 | time = time.replace(day=day, month=month+1, tzinfo=timezone.utc) 90 | 91 | if weekday != time.weekday(): 92 | raise ValueError( 93 | f"time data {value} does not match HTTP header format") 94 | 95 | return time 96 | 97 | 98 | def to_http_header(value: datetime) -> str: 99 | """Format datatime into HTTP header date formatted string.""" 100 | value = _to_utc(value) 101 | weekday = _WEEK_DAYS[value.weekday()] 102 | day = value.strftime(" %d ") 103 | month = _MONTHS[value.month - 1] 104 | suffix = value.strftime(" %Y %H:%M:%S GMT") 105 | return f"{weekday},{day}{month}{suffix}" 106 | 107 | 108 | def to_amz_date(value: datetime) -> str: 109 | """Format datetime into AMZ date formatted string.""" 110 | return _to_utc(value).strftime("%Y%m%dT%H%M%SZ") 111 | 112 | 113 | def utcnow() -> datetime: 114 | """Timezone-aware wrapper to datetime.utcnow().""" 115 | if _UTC_IMPORTED: 116 | return datetime.now(UTC).replace(tzinfo=timezone.utc) 117 | return datetime.utcnow().replace(tzinfo=timezone.utc) 118 | 119 | 120 | def to_signer_date(value: datetime) -> str: 121 | """Format datetime into SignatureV4 date formatted string.""" 122 | return _to_utc(value).strftime("%Y%m%d") 123 | 124 | 125 | def to_float(value: datetime) -> float: 126 | """Convert datetime into float value.""" 127 | return ctime.mktime(value.timetuple()) + value.microsecond * 1e-6 128 | -------------------------------------------------------------------------------- /minio/versioningconfig.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """Request/response of PutBucketVersioning and GetBucketVersioning APIs.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | from typing import List, Type, TypeVar, Union, cast 22 | from xml.etree import ElementTree as ET 23 | 24 | from .commonconfig import DISABLED, ENABLED 25 | from .xml import Element, SubElement, findall, findtext 26 | 27 | OFF = "Off" 28 | SUSPENDED = "Suspended" 29 | 30 | A = TypeVar("A", bound="VersioningConfig") 31 | 32 | 33 | class VersioningConfig: 34 | """Versioning configuration.""" 35 | 36 | def __init__( 37 | self, 38 | status: str | None = None, 39 | mfa_delete: str | None = None, 40 | excluded_prefixes: list[str] | None = None, 41 | exclude_folders: bool = False, 42 | ): 43 | if status is not None and status not in [ENABLED, SUSPENDED]: 44 | raise ValueError(f"status must be {ENABLED} or {SUSPENDED}") 45 | if mfa_delete is not None and mfa_delete not in [ENABLED, DISABLED]: 46 | raise ValueError(f"MFA delete must be {ENABLED} or {DISABLED}") 47 | self._status = status 48 | self._mfa_delete = mfa_delete 49 | self._excluded_prefixes = excluded_prefixes 50 | self._exclude_folders = exclude_folders 51 | 52 | @property 53 | def status(self) -> str: 54 | """Get status.""" 55 | return self._status or OFF 56 | 57 | @property 58 | def mfa_delete(self) -> str | None: 59 | """Get MFA delete.""" 60 | return self._mfa_delete 61 | 62 | @property 63 | def excluded_prefixes(self) -> list[str] | None: 64 | """Get excluded prefixes.""" 65 | return self._excluded_prefixes 66 | 67 | @property 68 | def exclude_folders(self) -> bool: 69 | """Get exclude folders.""" 70 | return self._exclude_folders 71 | 72 | @classmethod 73 | def fromxml(cls: Type[A], element: ET.Element) -> A: 74 | """Create new object with values from XML element.""" 75 | status = findtext(element, "Status") 76 | mfa_delete = findtext(element, "MFADelete") 77 | excluded_prefixes = [ 78 | prefix.text 79 | for prefix in findall( 80 | element, 81 | "ExcludedPrefixes/Prefix", 82 | ) 83 | ] 84 | exclude_folders = findtext(element, "ExcludeFolders") == "true" 85 | return cls( 86 | status, 87 | mfa_delete, 88 | cast(Union[List[str], None], excluded_prefixes), 89 | exclude_folders, 90 | ) 91 | 92 | def toxml(self, element: ET.Element | None) -> ET.Element: 93 | """Convert to XML.""" 94 | element = Element("VersioningConfiguration") 95 | if self._status: 96 | SubElement(element, "Status", self._status) 97 | if self._mfa_delete: 98 | SubElement(element, "MFADelete", self._mfa_delete) 99 | for prefix in self._excluded_prefixes or []: 100 | SubElement( 101 | SubElement(element, "ExcludedPrefixes"), 102 | "Prefix", 103 | prefix, 104 | ) 105 | if self._exclude_folders: 106 | SubElement(element, "ExcludeFolders", "true") 107 | return element 108 | -------------------------------------------------------------------------------- /minio/xml.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 3 | # 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | """XML utility module.""" 18 | 19 | from __future__ import absolute_import, annotations 20 | 21 | import io 22 | from typing import Type, TypeVar 23 | from xml.etree import ElementTree as ET 24 | 25 | from typing_extensions import Protocol 26 | 27 | _S3_NAMESPACE = "http://s3.amazonaws.com/doc/2006-03-01/" 28 | 29 | 30 | def Element( # pylint: disable=invalid-name 31 | tag: str, 32 | namespace: str = _S3_NAMESPACE, 33 | ) -> ET.Element: 34 | """Create ElementTree.Element with tag and namespace.""" 35 | return ET.Element(tag, {"xmlns": namespace} if namespace else {}) 36 | 37 | 38 | def SubElement( # pylint: disable=invalid-name 39 | parent: ET.Element, tag: str, text: str | None = None 40 | ) -> ET.Element: 41 | """Create ElementTree.SubElement on parent with tag and text.""" 42 | element = ET.SubElement(parent, tag) 43 | if text is not None: 44 | element.text = text 45 | return element 46 | 47 | 48 | def _get_namespace(element: ET.Element) -> str: 49 | """Exact namespace if found.""" 50 | start = element.tag.find("{") 51 | if start < 0: 52 | return "" 53 | start += 1 54 | end = element.tag.find("}") 55 | if end < 0: 56 | return "" 57 | return element.tag[start:end] 58 | 59 | 60 | def findall(element: ET.Element, name: str) -> list[ET.Element]: 61 | """Namespace aware ElementTree.Element.findall().""" 62 | namespace = _get_namespace(element) 63 | if namespace: 64 | name = "/".join(["ns:" + token for token in name.split("/")]) 65 | return element.findall(name, {"ns": namespace} if namespace else {}) 66 | 67 | 68 | def find( 69 | element: ET.Element, 70 | name: str, 71 | strict: bool = False, 72 | ) -> ET.Element | None: 73 | """Namespace aware ElementTree.Element.find().""" 74 | namespace = _get_namespace(element) 75 | elem = element.find( 76 | "ns:" + name if namespace else name, 77 | {"ns": namespace} if namespace else {}, 78 | ) 79 | if strict and elem is None: 80 | raise ValueError(f"XML element <{name}> not found") 81 | return elem 82 | 83 | 84 | def findtext( 85 | element: ET.Element, 86 | name: str, 87 | strict: bool = False, 88 | ) -> str | None: 89 | """ 90 | Namespace aware ElementTree.Element.findtext() with strict flag 91 | raises ValueError if element name not exist. 92 | """ 93 | elem = find(element, name, strict=strict) 94 | return None if elem is None else (elem.text or "") 95 | 96 | 97 | A = TypeVar("A") 98 | 99 | 100 | class FromXmlType(Protocol): 101 | """typing stub for class with `fromxml` method""" 102 | 103 | @classmethod 104 | def fromxml(cls: Type[A], element: ET.Element) -> A: 105 | """Create python object with values from XML element.""" 106 | 107 | 108 | B = TypeVar("B", bound=FromXmlType) 109 | 110 | 111 | def unmarshal(cls: Type[B], xmlstring: str) -> B: 112 | """Unmarshal given XML string to an object of passed class.""" 113 | return cls.fromxml(ET.fromstring(xmlstring)) 114 | 115 | 116 | def getbytes(element: ET.Element) -> bytes: 117 | """Convert ElementTree.Element to bytes.""" 118 | with io.BytesIO() as data: 119 | ET.ElementTree(element).write( 120 | data, 121 | encoding=None, 122 | xml_declaration=False, 123 | ) 124 | return data.getvalue() 125 | 126 | 127 | class ToXmlType(Protocol): 128 | """typing stub for class with `toxml` method""" 129 | 130 | def toxml(self, element: ET.Element | None) -> ET.Element: 131 | """Convert python object to ElementTree.Element.""" 132 | 133 | 134 | def marshal(obj: ToXmlType) -> bytes: 135 | """Get XML data as bytes of ElementTree.Element.""" 136 | return getbytes(obj.toxml(None)) 137 | -------------------------------------------------------------------------------- /run_functional_tests.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | 18 | function run_minio_server() { 19 | if [ ! -f tests/functional/minio ]; then 20 | wget --quiet --output-document tests/functional/minio https://dl.min.io/server/minio/release/linux-amd64/minio 21 | chmod +x tests/functional/minio 22 | fi 23 | 24 | export MINIO_KMS_KES_ENDPOINT=https://play.min.io:7373 25 | export MINIO_KMS_KES_KEY_FILE=tests/functional/play.min.io.kes.root.key 26 | export MINIO_KMS_KES_CERT_FILE=tests/functional/play.min.io.kes.root.cert 27 | export MINIO_KMS_KES_KEY_NAME=my-minio-key 28 | export MINIO_NOTIFY_WEBHOOK_ENABLE_miniopytest=on 29 | export MINIO_NOTIFY_WEBHOOK_ENDPOINT_miniopytest=http://example.org/ 30 | export SQS_ARN="arn:minio:sqs::miniopytest:webhook" 31 | export MINIO_CI_CD=1 32 | tests/functional/minio server --config-dir tests/functional/.cfg tests/functional/.d{1...4} >tests/functional/minio.log 2>&1 & 33 | } 34 | 35 | if [ -z ${SERVER_ENDPOINT+x} ]; then 36 | run_minio_server 37 | MINIO_PID=$! 38 | trap 'kill -9 ${MINIO_PID} 2>/dev/null' INT 39 | 40 | export MINT_MODE=full 41 | export SERVER_ENDPOINT=localhost:9000 42 | export ACCESS_KEY=minioadmin 43 | export SECRET_KEY=minioadmin 44 | export ENABLE_HTTPS=0 45 | fi 46 | 47 | PYTHONPATH=$PWD python tests/functional/tests.py 48 | if [ -n "$MINIO_PID" ]; then 49 | kill -9 "$MINIO_PID" 2>/dev/null 50 | fi 51 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 2 | # (C) 2015 MinIO, Inc. 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | import codecs 17 | import re 18 | import sys 19 | 20 | from setuptools import setup 21 | 22 | if sys.argv[-1] == "publish": 23 | sys.argv = sys.argv[:-1] + ["sdist", "upload"] 24 | 25 | with codecs.open("minio/__init__.py") as file: 26 | version = re.search( 27 | r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', 28 | file.read(), 29 | re.MULTILINE, 30 | ).group(1) 31 | 32 | with codecs.open("README.md", encoding="utf-8") as file: 33 | readme = file.read() 34 | 35 | setup( 36 | name="minio", 37 | description="MinIO Python SDK for Amazon S3 Compatible Cloud Storage", 38 | author="MinIO, Inc.", 39 | url="https://github.com/minio/minio-py", 40 | download_url="https://github.com/minio/minio-py/releases", 41 | author_email="dev@min.io", 42 | version=version, 43 | long_description_content_type="text/markdown", 44 | package_dir={"minio": "minio"}, 45 | packages=["minio", "minio.credentials"], 46 | python_requires=">=3.9", 47 | install_requires=["certifi", "urllib3", "argon2-cffi", 48 | "pycryptodome", "typing-extensions"], 49 | tests_require=[], 50 | license="Apache-2.0", 51 | classifiers=[ 52 | "Development Status :: 5 - Production/Stable", 53 | "Intended Audience :: Developers", 54 | "License :: OSI Approved :: Apache Software License", 55 | "Natural Language :: English", 56 | "Operating System :: OS Independent", 57 | "Programming Language :: Python", 58 | "Programming Language :: Python :: 3.9", 59 | "Programming Language :: Python :: 3.10", 60 | "Programming Language :: Python :: 3.11", 61 | "Programming Language :: Python :: 3.12", 62 | "Programming Language :: Python :: 3.13", 63 | "Topic :: Software Development :: Libraries :: Python Modules", 64 | ], 65 | long_description=readme, 66 | package_data={"": ["LICENSE", "README.md"]}, 67 | include_package_data=True, 68 | ) 69 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minio/minio-py/817235ba9ae9b204db073901411e92f5aeabc3bd/tests/__init__.py -------------------------------------------------------------------------------- /tests/certs/private.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg4xPXOZxw3CSdAENR 3 | GdHwbWoEGJz90Qj0i4sLYeDkDxyhRANCAAT7rsPVqHhjXdDs6vmWrc2PGEk2+YYe 4 | N0SYgtVXeyxJWU8pm+tRLxGEEQAwotF02n5zVgDoeCIE1Qw63x1UqbNb 5 | -----END PRIVATE KEY----- 6 | -------------------------------------------------------------------------------- /tests/certs/public.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIBzzCCAXWgAwIBAgIQB4m9LxyajXUukdwmZ1bAYjAKBggqhkjOPQQDAjAxMRww 3 | GgYDVQQKExNDZXJ0Z2VuIERldmVsb3BtZW50MREwDwYDVQQLDAhiYWxhQGY0MDAg 4 | Fw0yNDA2MjYxMTM1MjdaGA8yMTI0MDYwMjExMzUyN1owMTEcMBoGA1UEChMTQ2Vy 5 | dGdlbiBEZXZlbG9wbWVudDERMA8GA1UECwwIYmFsYUBmNDAwWTATBgcqhkjOPQIB 6 | BggqhkjOPQMBBwNCAAT7rsPVqHhjXdDs6vmWrc2PGEk2+YYeN0SYgtVXeyxJWU8p 7 | m+tRLxGEEQAwotF02n5zVgDoeCIE1Qw63x1UqbNbo20wazAOBgNVHQ8BAf8EBAMC 8 | AqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E 9 | FgQU+19mAIDUAmcrnLkQXK3wIALqOyMwFAYDVR0RBA0wC4IJbG9jYWxob3N0MAoG 10 | CCqGSM49BAMCA0gAMEUCIHTvNqhh7jne6xBHavVK8e7C/NX0Yn5Q8rAGdfAO3gOj 11 | AiEApng9Wygpnj8fIgn3itxjL/RZbic/gneL/nfVptBOnlY= 12 | -----END CERTIFICATE----- 13 | -------------------------------------------------------------------------------- /tests/functional/play.min.io.kes.root.cert: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIBKDCB26ADAgECAhB6vebGMUfKnmBKyqoApRSOMAUGAytlcDAbMRkwFwYDVQQD 3 | DBByb290QHBsYXkubWluLmlvMB4XDTIwMDQzMDE1MjIyNVoXDTI1MDQyOTE1MjIy 4 | NVowGzEZMBcGA1UEAwwQcm9vdEBwbGF5Lm1pbi5pbzAqMAUGAytlcAMhALzn735W 5 | fmSH/ghKs+4iPWziZMmWdiWr/sqvqeW+WwSxozUwMzAOBgNVHQ8BAf8EBAMCB4Aw 6 | EwYDVR0lBAwwCgYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAFBgMrZXADQQDZOrGK 7 | b2ATkDlu2pTcP3LyhSBDpYh7V4TvjRkBTRgjkacCzwFLm+mh+7US8V4dBpIDsJ4u 8 | uWoF0y6vbLVGIlkG 9 | -----END CERTIFICATE----- 10 | -------------------------------------------------------------------------------- /tests/functional/play.min.io.kes.root.key: -------------------------------------------------------------------------------- 1 | -----BEGIN PRIVATE KEY----- 2 | MC4CAQAwBQYDK2VwBCIEID9E7FSYWrMD+VjhI6q545cYT9YOyFxZb7UnjEepYDRc 3 | -----END PRIVATE KEY----- 4 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | -------------------------------------------------------------------------------- /tests/unit/bucket_exist_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | from minio.error import S3Error 23 | 24 | from .minio_mocks import MockConnection, MockResponse 25 | 26 | 27 | class BucketExists(TestCase): 28 | def test_bucket_is_string(self): 29 | client = Minio('localhost:9000') 30 | self.assertRaises(TypeError, client.bucket_exists, 1234) 31 | 32 | def test_bucket_is_not_empty_string(self): 33 | client = Minio('localhost:9000') 34 | self.assertRaises(ValueError, client.bucket_exists, ' \t \n ') 35 | 36 | def test_bucket_exists_invalid_name(self): 37 | client = Minio('localhost:9000') 38 | self.assertRaises(ValueError, client.bucket_exists, 'AB*CD') 39 | 40 | @mock.patch('urllib3.PoolManager') 41 | def test_bucket_exists_bad_request(self, mock_connection): 42 | mock_server = MockConnection() 43 | mock_connection.return_value = mock_server 44 | mock_server.mock_add_request( 45 | MockResponse('HEAD', 46 | 'https://localhost:9000/hello', 47 | {'User-Agent': _DEFAULT_USER_AGENT}, 48 | 400) 49 | ) 50 | client = Minio('localhost:9000') 51 | self.assertRaises(S3Error, client.bucket_exists, 'hello') 52 | 53 | @mock.patch('urllib3.PoolManager') 54 | def test_bucket_exists_works(self, mock_connection): 55 | mock_server = MockConnection() 56 | mock_connection.return_value = mock_server 57 | mock_server.mock_add_request( 58 | MockResponse('HEAD', 59 | 'https://localhost:9000/hello', 60 | {'User-Agent': _DEFAULT_USER_AGENT}, 61 | 200) 62 | ) 63 | client = Minio('localhost:9000') 64 | result = client.bucket_exists('hello') 65 | self.assertTrue(result) 66 | mock_server.mock_add_request( 67 | MockResponse('HEAD', 68 | 'https://localhost:9000/goodbye', 69 | {'User-Agent': _DEFAULT_USER_AGENT}, 70 | 404) 71 | ) 72 | false_result = client.bucket_exists('goodbye') 73 | self.assertFalse(false_result) 74 | -------------------------------------------------------------------------------- /tests/unit/config.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "version": "8", 3 | "hosts": { 4 | "play": { 5 | "url": "https://play.minio.io:9000", 6 | "accessKey": "Q3AM3UQ867SPQQA43P2F", 7 | "secretKey": "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", 8 | "api": "S3v2" 9 | }, 10 | "s3": { 11 | "url": "https://s3.amazonaws.com", 12 | "accessKey": "accessKey", 13 | "secretKey": "secret", 14 | "api": "S3v4" 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /tests/unit/copy_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015, 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import Minio 20 | from minio.commonconfig import CopySource 21 | 22 | 23 | class CopyObjectTest(TestCase): 24 | def test_valid_copy_source(self): 25 | client = Minio('localhost:9000') 26 | self.assertRaises( 27 | ValueError, 28 | client.copy_object, 'hello', '1', '/testbucket/object' 29 | ) 30 | 31 | def test_valid_match_etag(self): 32 | self.assertRaises( 33 | ValueError, CopySource, "src-bucket", "src-object", match_etag='') 34 | 35 | def test_not_match_etag(self): 36 | self.assertRaises( 37 | ValueError, 38 | CopySource, "src-bucket", "src-object", not_match_etag='' 39 | ) 40 | 41 | def test_valid_modified_since(self): 42 | self.assertRaises( 43 | ValueError, 44 | CopySource, "src-bucket", "src-object", modified_since='' 45 | ) 46 | 47 | def test_valid_unmodified_since(self): 48 | self.assertRaises( 49 | ValueError, 50 | CopySource, "src-bucket", "src-object", unmodified_since='' 51 | ) 52 | -------------------------------------------------------------------------------- /tests/unit/credentials.empty: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minio/minio-py/817235ba9ae9b204db073901411e92f5aeabc3bd/tests/unit/credentials.empty -------------------------------------------------------------------------------- /tests/unit/credentials.sample: -------------------------------------------------------------------------------- 1 | [default] 2 | aws_access_key_id = accessKey 3 | aws_secret_access_key = secret 4 | aws_session_token = token 5 | 6 | [no_token] 7 | aws_access_key_id = accessKey 8 | aws_secret_access_key = secret 9 | 10 | [with_colon] 11 | aws_access_key_id: accessKey 12 | aws_secret_access_key: secret -------------------------------------------------------------------------------- /tests/unit/crypto_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from io import BytesIO 18 | from unittest import TestCase 19 | 20 | from urllib3.response import HTTPResponse 21 | 22 | from minio.crypto import decrypt, encrypt 23 | 24 | 25 | class CryptoTest(TestCase): 26 | def test_correct(self): 27 | secret = "topsecret" 28 | plaintext = "Hello MinIO!" 29 | encrypted = encrypt(plaintext.encode(), secret) 30 | decrypted = decrypt( 31 | HTTPResponse(body=BytesIO(encrypted), preload_content=False), 32 | secret, 33 | ).decode() 34 | if hasattr(self, "assertEquals"): 35 | self.assertEquals(plaintext, decrypted) 36 | else: 37 | self.assertEqual(plaintext, decrypted) 38 | 39 | def test_wrong(self): 40 | secret = "topsecret" 41 | secret2 = "othersecret" 42 | plaintext = "Hello MinIO!" 43 | encrypted = encrypt(plaintext.encode(), secret) 44 | self.assertRaises( 45 | ValueError, 46 | decrypt, 47 | HTTPResponse(body=BytesIO(encrypted), preload_content=False), 48 | secret2, 49 | ) 50 | -------------------------------------------------------------------------------- /tests/unit/get_bucket_policy_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | import json 19 | import unittest.mock as mock 20 | from unittest import TestCase 21 | 22 | from minio import Minio 23 | from minio.api import _DEFAULT_USER_AGENT 24 | from minio.error import S3Error 25 | from tests.unit.minio_mocks import MockConnection, MockResponse 26 | 27 | 28 | class GetBucketPolicyTest(TestCase): 29 | @mock.patch('urllib3.PoolManager') 30 | def test_get_policy_for_non_existent_bucket(self, mock_connection): 31 | mock_server = MockConnection() 32 | mock_connection.return_value = mock_server 33 | bucket_name = 'non-existent-bucket' 34 | error = ("" 35 | "NoSuchBucket" 36 | "No such bucket1234" 37 | "/non-existent-bucket" 38 | "abcd" 39 | "non-existent-bucket" 40 | "") 41 | mock_server.mock_add_request( 42 | MockResponse( 43 | 'GET', 44 | 'https://localhost:9000/' + bucket_name + '?policy=', 45 | {'User-Agent': _DEFAULT_USER_AGENT}, 46 | 404, 47 | response_headers={"Content-Type": "application/xml"}, 48 | content=error.encode() 49 | ) 50 | ) 51 | client = Minio('localhost:9000') 52 | self.assertRaises(S3Error, client.get_bucket_policy, bucket_name) 53 | 54 | @mock.patch('urllib3.PoolManager') 55 | def test_get_policy_for_existent_bucket(self, mock_connection): 56 | mock_data = json.dumps({ 57 | "Version": "2012-10-17", 58 | "Statement": [ 59 | { 60 | "Sid": "", 61 | "Effect": "Allow", 62 | "Principal": {"AWS": "*"}, 63 | "Action": "s3:GetBucketLocation", 64 | "Resource": "arn:aws:s3:::test-bucket" 65 | }, 66 | { 67 | "Sid": "", 68 | "Effect": "Allow", 69 | "Principal": {"AWS": "*"}, 70 | "Action": "s3:ListBucket", 71 | "Resource": "arn:aws:s3:::test-bucket" 72 | }, 73 | { 74 | "Sid": "", 75 | "Effect": "Allow", 76 | "Principal": {"AWS": "*"}, 77 | "Action": "s3:GetObject", 78 | "Resource": "arn:aws:s3:::test-bucket/*" 79 | } 80 | ] 81 | }).encode() 82 | mock_server = MockConnection() 83 | mock_connection.return_value = mock_server 84 | bucket_name = 'test-bucket' 85 | mock_server.mock_add_request( 86 | MockResponse( 87 | 'GET', 88 | 'https://localhost:9000/' + bucket_name + '?policy=', 89 | {'User-Agent': _DEFAULT_USER_AGENT}, 90 | 200, 91 | content=mock_data 92 | ) 93 | ) 94 | client = Minio('localhost:9000') 95 | response = client.get_bucket_policy(bucket_name) 96 | self.assertEqual(response, mock_data.decode()) 97 | -------------------------------------------------------------------------------- /tests/unit/get_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | from minio.error import S3Error 23 | 24 | from .helpers import generate_error 25 | from .minio_mocks import MockConnection, MockResponse 26 | 27 | 28 | class GetObjectTest(TestCase): 29 | def test_object_is_string(self): 30 | client = Minio('localhost:9000') 31 | self.assertRaises(TypeError, client.get_object, 'hello', 1234) 32 | 33 | def test_object_is_not_empty_string(self): 34 | client = Minio('localhost:9000') 35 | self.assertRaises(ValueError, client.get_object, 'hello', ' \t \n ') 36 | 37 | @mock.patch('urllib3.PoolManager') 38 | def test_get_object_throws_fail(self, mock_connection): 39 | error_xml = generate_error('code', 'message', 'request_id', 40 | 'host_id', 'resource', 'bucket', 41 | 'object') 42 | mock_server = MockConnection() 43 | mock_connection.return_value = mock_server 44 | mock_server.mock_add_request( 45 | MockResponse('GET', 46 | 'https://localhost:9000/hello/key', 47 | {'User-Agent': _DEFAULT_USER_AGENT}, 48 | 404, 49 | response_headers={"Content-Type": "application/xml"}, 50 | content=error_xml.encode()) 51 | ) 52 | client = Minio('localhost:9000') 53 | self.assertRaises(S3Error, client.get_object, 'hello', 'key') 54 | -------------------------------------------------------------------------------- /tests/unit/legelhold_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.legalhold import LegalHold 21 | 22 | 23 | class LegalHoldTest(TestCase): 24 | def test_status(self): 25 | config = LegalHold(True) 26 | xml.marshal(config) 27 | 28 | config = xml.unmarshal( 29 | LegalHold, 30 | """ 31 | OFF 32 | """, 33 | ) 34 | xml.marshal(config) 35 | self.assertFalse(config.status) 36 | -------------------------------------------------------------------------------- /tests/unit/lifecycleconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015, 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.commonconfig import ENABLED, Filter 21 | from minio.lifecycleconfig import Expiration, LifecycleConfig, Rule, Transition 22 | 23 | 24 | class LifecycleConfigTest(TestCase): 25 | def test_config(self): 26 | config = LifecycleConfig( 27 | [ 28 | Rule( 29 | ENABLED, 30 | rule_filter=Filter(prefix="documents/"), 31 | rule_id="rule1", 32 | transition=Transition(days=30, storage_class="GLACIER"), 33 | ), 34 | Rule( 35 | ENABLED, 36 | rule_filter=Filter(prefix="logs/"), 37 | rule_id="rule2", 38 | expiration=Expiration(days=365), 39 | ), 40 | ], 41 | ) 42 | xml.marshal(config) 43 | 44 | config = LifecycleConfig( 45 | [ 46 | Rule( 47 | ENABLED, 48 | rule_filter=Filter(prefix=""), 49 | rule_id="rule", 50 | expiration=Expiration(days=365), 51 | ), 52 | ], 53 | ) 54 | xml.marshal(config) 55 | 56 | config = xml.unmarshal( 57 | LifecycleConfig, 58 | """ 59 | 60 | DeleteAfterBecomingNonCurrent 61 | 62 | logs/ 63 | 64 | Enabled 65 | 66 | 100 67 | 68 | 69 | 70 | TransitionAfterBecomingNonCurrent 71 | 72 | documents/ 73 | 74 | Enabled 75 | 76 | 30 77 | GLACIER 78 | 79 | 80 | """, 81 | ) 82 | xml.marshal(config) 83 | 84 | config = xml.unmarshal( 85 | LifecycleConfig, 86 | """ 87 | 88 | DeleteAfterBecomingNonCurrent 89 | 90 | 91 | 92 | Enabled 93 | 94 | 100 95 | 96 | 97 | """, 98 | ) 99 | xml.marshal(config) 100 | -------------------------------------------------------------------------------- /tests/unit/list_buckets_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from datetime import datetime, timezone 19 | from unittest import TestCase 20 | 21 | from minio import Minio 22 | from minio.api import _DEFAULT_USER_AGENT 23 | 24 | from .minio_mocks import MockConnection, MockResponse 25 | 26 | 27 | class ListBucketsTest(TestCase): 28 | @mock.patch('urllib3.PoolManager') 29 | def test_empty_list_buckets_works(self, mock_connection): 30 | mock_data = ('' 32 | 'minio' 33 | 'minio') 34 | mock_server = MockConnection() 35 | mock_connection.return_value = mock_server 36 | mock_server.mock_add_request( 37 | MockResponse('GET', 'https://localhost:9000/', 38 | {'User-Agent': _DEFAULT_USER_AGENT}, 39 | 200, content=mock_data.encode()) 40 | ) 41 | client = Minio('localhost:9000') 42 | buckets = client.list_buckets() 43 | count = 0 44 | for bucket in buckets: 45 | count += 1 46 | self.assertEqual(0, count) 47 | 48 | @mock.patch('urllib3.PoolManager') 49 | def test_list_buckets_works(self, mock_connection): 50 | mock_data = ('' 52 | 'hello' 53 | '2015-06-22T23:07:43.240Z' 54 | 'world' 55 | '2015-06-22T23:07:56.766Z' 56 | 'minio' 57 | 'minio' 58 | '') 59 | mock_server = MockConnection() 60 | mock_connection.return_value = mock_server 61 | mock_server.mock_add_request( 62 | MockResponse('GET', 'https://localhost:9000/', 63 | {'User-Agent': _DEFAULT_USER_AGENT}, 64 | 200, content=mock_data.encode()) 65 | ) 66 | client = Minio('localhost:9000') 67 | buckets = client.list_buckets() 68 | buckets_list = [] 69 | count = 0 70 | for bucket in buckets: 71 | count += 1 72 | buckets_list.append(bucket) 73 | self.assertEqual(2, count) 74 | self.assertEqual('hello', buckets_list[0].name) 75 | self.assertEqual( 76 | datetime(2015, 6, 22, 23, 7, 43, 240000, timezone.utc), 77 | buckets_list[0].creation_date, 78 | ) 79 | self.assertEqual('world', buckets_list[1].name) 80 | self.assertEqual( 81 | datetime(2015, 6, 22, 23, 7, 56, 766000, timezone.utc), 82 | buckets_list[1].creation_date, 83 | ) 84 | -------------------------------------------------------------------------------- /tests/unit/list_objects_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015-2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import time 18 | import unittest.mock as mock 19 | from unittest import TestCase 20 | 21 | from minio import Minio 22 | from minio.api import _DEFAULT_USER_AGENT 23 | 24 | from .minio_mocks import MockConnection, MockResponse 25 | 26 | 27 | class ListObjectsTest(TestCase): 28 | @mock.patch('urllib3.PoolManager') 29 | def test_empty_list_objects_works(self, mock_connection): 30 | mock_data = ''' 31 | 32 | bucket 33 | 34 | 0 35 | 1000 36 | 37 | false 38 | ''' 39 | mock_server = MockConnection() 40 | mock_connection.return_value = mock_server 41 | mock_server.mock_add_request( 42 | MockResponse( 43 | "GET", 44 | "https://localhost:9000/bucket?delimiter=&encoding-type=url" 45 | "&list-type=2&max-keys=1000&prefix=", 46 | {"User-Agent": _DEFAULT_USER_AGENT}, 47 | 200, 48 | content=mock_data.encode(), 49 | ), 50 | ) 51 | client = Minio('localhost:9000') 52 | object_iter = client.list_objects('bucket', recursive=True) 53 | objects = [] 54 | for obj in object_iter: 55 | objects.append(obj) 56 | self.assertEqual(0, len(objects)) 57 | 58 | @mock.patch('urllib3.PoolManager') 59 | def test_list_objects_works(self, mock_connection): 60 | start_time = time.time() 61 | mock_data = ''' 62 | 63 | bucket 64 | 65 | 2 66 | 1000 67 | false 68 | 69 | 6/f/9/6f9898076bb08572403f95dbb86c5b9c85e1e1b3 70 | 2016-11-27T07:55:53.000Z 71 | "5d5512301b6b6e247b8aec334b2cf7ea" 72 | 493 73 | REDUCED_REDUNDANCY 74 | 75 | 76 | b/d/7/bd7f6410cced55228902d881c2954ebc826d7464 77 | 2016-11-27T07:10:27.000Z 78 | "f00483d523ffc8b7f2883ae896769d85" 79 | 493 80 | REDUCED_REDUNDANCY 81 | 82 | ''' 83 | mock_server = MockConnection() 84 | mock_connection.return_value = mock_server 85 | mock_server.mock_add_request( 86 | MockResponse( 87 | "GET", 88 | "https://localhost:9000/bucket?delimiter=%2F&encoding-type=url" 89 | "&list-type=2&max-keys=1000&prefix=", 90 | {"User-Agent": _DEFAULT_USER_AGENT}, 91 | 200, 92 | content=mock_data.encode(), 93 | ), 94 | ) 95 | client = Minio('localhost:9000') 96 | objects_iter = client.list_objects('bucket') 97 | objects = [] 98 | for obj in objects_iter: 99 | objects.append(obj) 100 | 101 | self.assertEqual(2, len(objects)) 102 | end_time = time.time() 103 | self.assertLess(end_time-start_time, 1) 104 | -------------------------------------------------------------------------------- /tests/unit/make_bucket_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | from minio.error import S3Error 23 | 24 | from .helpers import generate_error 25 | from .minio_mocks import MockConnection, MockResponse 26 | 27 | 28 | class MakeBucket(TestCase): 29 | def test_bucket_is_string(self): 30 | client = Minio('localhost:9000') 31 | self.assertRaises(TypeError, client.make_bucket, 1234) 32 | 33 | def test_bucket_is_not_empty_string(self): 34 | client = Minio('localhost:9000') 35 | self.assertRaises(ValueError, client.make_bucket, ' \t \n ') 36 | 37 | @mock.patch('urllib3.PoolManager') 38 | def test_make_bucket_works(self, mock_connection): 39 | mock_server = MockConnection() 40 | mock_connection.return_value = mock_server 41 | mock_server.mock_add_request( 42 | MockResponse('PUT', 43 | 'https://localhost:9000/hello', 44 | {'User-Agent': _DEFAULT_USER_AGENT}, 45 | 200) 46 | ) 47 | Minio('localhost:9000') 48 | 49 | @mock.patch('urllib3.PoolManager') 50 | def test_make_bucket_throws_fail(self, mock_connection): 51 | error_xml = generate_error('code', 'message', 'request_id', 52 | 'host_id', 'resource', 'bucket', 53 | 'object') 54 | mock_server = MockConnection() 55 | mock_connection.return_value = mock_server 56 | mock_server.mock_add_request( 57 | MockResponse('PUT', 58 | 'https://localhost:9000/hello', 59 | {'User-Agent': _DEFAULT_USER_AGENT}, 60 | 409, 61 | response_headers={"Content-Type": "application/xml"}, 62 | content=error_xml.encode()) 63 | ) 64 | client = Minio('localhost:9000') 65 | self.assertRaises(S3Error, client.make_bucket, 'hello') 66 | -------------------------------------------------------------------------------- /tests/unit/minio_mocks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015-2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from http import client as httplib 18 | 19 | 20 | class MockResponse(object): 21 | def __init__(self, method, url, headers, status_code, 22 | response_headers=None, content=None): 23 | self.method = method 24 | self.url = url 25 | self.request_headers = { 26 | key.lower(): value for key, value in headers.items() 27 | } 28 | self.status = status_code 29 | self.headers = { 30 | key.lower(): value for key, value in ( 31 | response_headers or {}).items() 32 | } 33 | self.data = content 34 | if content is None: 35 | self.reason = httplib.responses[status_code] 36 | 37 | # noinspection PyUnusedLocal 38 | def read(self, *args, **kwargs): 39 | return self.data 40 | 41 | def mock_verify(self, method, url, headers): 42 | assert self.method == method 43 | assert self.url == url 44 | headers = { 45 | key.lower(): value for key, value in headers.items() 46 | } 47 | for header in self.request_headers: 48 | assert self.request_headers[header] == headers[header] 49 | 50 | # noinspection PyUnusedLocal 51 | def stream(self, chunk_size=1, decode_unicode=False): 52 | if self.data is not None: 53 | return iter(bytearray(self.data, 'utf-8')) 54 | return iter([]) 55 | 56 | # dummy release connection call. 57 | def release_conn(self): 58 | return 59 | 60 | def getheader(self, key, value=None): 61 | return self.headers.get(key, value) if self.headers else value 62 | 63 | def __getitem__(self, key): 64 | if key == "status": 65 | return self.status 66 | 67 | 68 | class MockConnection(object): 69 | def __init__(self): 70 | self.requests = [] 71 | 72 | def clear(self): 73 | pass 74 | 75 | def mock_add_request(self, request): 76 | self.requests.append(request) 77 | 78 | # noinspection PyUnusedLocal 79 | def request(self, method, url, headers, redirect=False): 80 | # only pop off matching requests 81 | return_request = self.requests[0] 82 | return_request.mock_verify(method, url, headers) 83 | return self.requests.pop(0) 84 | 85 | # noinspection PyRedeclaration,PyUnusedLocal,PyUnusedLocal 86 | 87 | def urlopen(self, method, url, headers={}, preload_content=False, 88 | body=None, redirect=False): 89 | return self.request(method, url, headers) 90 | -------------------------------------------------------------------------------- /tests/unit/notificationconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.notificationconfig import (NotificationConfig, PrefixFilterRule, 21 | QueueConfig) 22 | 23 | 24 | class NotificationConfigTest(TestCase): 25 | def test_config(self): 26 | config = NotificationConfig( 27 | queue_config_list=[ 28 | QueueConfig( 29 | "QUEUE-ARN-OF-THIS-BUCKET", 30 | ['s3:ObjectCreated:*'], 31 | config_id="1", 32 | prefix_filter_rule=PrefixFilterRule("abc"), 33 | ), 34 | ], 35 | ) 36 | xml.marshal(config) 37 | 38 | config = xml.unmarshal( 39 | NotificationConfig, 40 | """ 41 | 42 | ObjectCreatedEvents 43 | arn:aws:lambda:us-west-2:35667example:function:CreateThumbnail 44 | s3:ObjectCreated:* 45 | 46 | 47 | 1 48 | 49 | 50 | 51 | prefix 52 | images/ 53 | 54 | 55 | suffix 56 | .jpg 57 | 58 | 59 | 60 | arn:aws:sqs:us-west-2:444455556666:s3notificationqueue 61 | s3:ObjectCreated:Put 62 | 63 | """, 64 | ) 65 | xml.marshal(config) 66 | -------------------------------------------------------------------------------- /tests/unit/objectlockconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.commonconfig import COMPLIANCE, GOVERNANCE 21 | from minio.objectlockconfig import DAYS, YEARS, ObjectLockConfig 22 | 23 | 24 | class ObjectLockConfigTest(TestCase): 25 | def test_config(self): 26 | config = ObjectLockConfig(GOVERNANCE, 15, DAYS) 27 | xml.marshal(config) 28 | 29 | config = xml.unmarshal( 30 | ObjectLockConfig, 31 | """ 32 | Enabled 33 | 34 | 35 | COMPLIANCE 36 | 3 37 | 38 | 39 | """, 40 | ) 41 | xml.marshal(config) 42 | self.assertEqual(config.mode, COMPLIANCE) 43 | self.assertEqual(config.duration, (3, YEARS)) 44 | -------------------------------------------------------------------------------- /tests/unit/presigned_get_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from datetime import timedelta 19 | from unittest import TestCase 20 | 21 | from minio import Minio 22 | 23 | 24 | class PresignedGetObjectTest(TestCase): 25 | def test_object_is_string(self): 26 | client = Minio('localhost:9000') 27 | self.assertRaises( 28 | TypeError, client.presigned_get_object, 'hello', 1234) 29 | 30 | def test_object_is_not_empty_string(self): 31 | client = Minio('localhost:9000') 32 | self.assertRaises( 33 | ValueError, client.presigned_get_object, 'hello', ' \t \n ') 34 | 35 | def test_expiry_limit(self): 36 | client = Minio('localhost:9000') 37 | self.assertRaises( 38 | ValueError, 39 | client.presigned_get_object, 'hello', 'key', 40 | expires=timedelta(days=8) 41 | ) 42 | 43 | def test_can_include_response_headers(self): 44 | client = Minio('localhost:9000', 'my_access_key', 'my_secret_key', 45 | secure=True) 46 | client._get_region = mock.Mock(return_value='us-east-1') 47 | r = client.presigned_get_object( 48 | 'mybucket', 'myfile.pdf', 49 | response_headers={ 50 | 'Response-Content-Type': 'application/pdf', 51 | 'Response-Content-Disposition': 'inline; filename="test.pdf"' 52 | }) 53 | self.assertIn('inline', r) 54 | self.assertIn('test.pdf', r) 55 | self.assertIn('application%2Fpdf', r) 56 | -------------------------------------------------------------------------------- /tests/unit/presigned_put_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015, 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import timedelta 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | 22 | 23 | class PresignedPutObjectTest(TestCase): 24 | def test_object_is_string(self): 25 | client = Minio('localhost:9000') 26 | self.assertRaises( 27 | TypeError, client.presigned_put_object, 'hello', 1234) 28 | 29 | def test_object_is_not_empty_string(self): 30 | client = Minio('localhost:9000') 31 | self.assertRaises( 32 | ValueError, client.presigned_put_object, 'hello', ' \t \n ') 33 | 34 | def test_expiry_limit(self): 35 | client = Minio('localhost:9000') 36 | self.assertRaises( 37 | ValueError, 38 | client.presigned_put_object, 'hello', 'key', 39 | expires=timedelta(days=8) 40 | ) 41 | -------------------------------------------------------------------------------- /tests/unit/put_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import Minio 20 | 21 | 22 | class PutObjectTest(TestCase): 23 | def test_object_is_string(self): 24 | client = Minio('localhost:9000') 25 | self.assertRaises( 26 | TypeError, 27 | client.put_object, 'hello', 1234, 1, iter([1, 2, 3]) 28 | ) 29 | 30 | def test_object_is_not_empty_string(self): 31 | client = Minio('localhost:9000') 32 | self.assertRaises( 33 | ValueError, 34 | client.put_object, 'hello', ' \t \n ', 1, iter([1, 2, 3]) 35 | ) 36 | 37 | def test_length_is_string(self): 38 | client = Minio('localhost:9000') 39 | self.assertRaises( 40 | TypeError, 41 | client.put_object, 'hello', 1234, '1', iter([1, 2, 3]) 42 | ) 43 | 44 | def test_length_is_not_empty_string(self): 45 | client = Minio('localhost:9000') 46 | self.assertRaises( 47 | ValueError, 48 | client.put_object, 'hello', ' \t \n ', -1, iter([1, 2, 3]) 49 | ) 50 | -------------------------------------------------------------------------------- /tests/unit/remove_bucket_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | 23 | from .minio_mocks import MockConnection, MockResponse 24 | 25 | 26 | class RemoveBucket(TestCase): 27 | def test_bucket_is_string(self): 28 | client = Minio('localhost:9000') 29 | self.assertRaises(TypeError, client.remove_bucket, 1234) 30 | 31 | def test_bucket_is_not_empty_string(self): 32 | client = Minio('localhost:9000') 33 | self.assertRaises(ValueError, client.remove_bucket, ' \t \n ') 34 | 35 | def test_remove_bucket_invalid_name(self): 36 | client = Minio('localhost:9000') 37 | self.assertRaises(ValueError, client.remove_bucket, 'AB*CD') 38 | 39 | @mock.patch('urllib3.PoolManager') 40 | def test_remove_bucket_works(self, mock_connection): 41 | mock_server = MockConnection() 42 | mock_connection.return_value = mock_server 43 | mock_server.mock_add_request( 44 | MockResponse('DELETE', 45 | 'https://localhost:9000/hello', 46 | {'User-Agent': _DEFAULT_USER_AGENT}, 204) 47 | ) 48 | client = Minio('localhost:9000') 49 | client.remove_bucket('hello') 50 | -------------------------------------------------------------------------------- /tests/unit/remove_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the 'License'); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an 'AS IS' BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | 23 | from .minio_mocks import MockConnection, MockResponse 24 | 25 | 26 | class StatObject(TestCase): 27 | def test_object_is_string(self): 28 | client = Minio('localhost:9000') 29 | self.assertRaises(TypeError, client.remove_object, 'hello', 1234) 30 | 31 | def test_object_is_not_empty_string(self): 32 | client = Minio('localhost:9000') 33 | self.assertRaises(ValueError, client.remove_object, 34 | 'hello', ' \t \n ') 35 | 36 | def test_remove_bucket_invalid_name(self): 37 | client = Minio('localhost:9000') 38 | self.assertRaises(ValueError, client.remove_object, 'AB*CD', 'world') 39 | 40 | @mock.patch('urllib3.PoolManager') 41 | def test_remove_object_works(self, mock_connection): 42 | mock_server = MockConnection() 43 | mock_connection.return_value = mock_server 44 | mock_server.mock_add_request( 45 | MockResponse('DELETE', 46 | 'https://localhost:9000/hello/world', 47 | {'User-Agent': _DEFAULT_USER_AGENT}, 204) 48 | ) 49 | client = Minio('localhost:9000') 50 | client.remove_object('hello', 'world') 51 | -------------------------------------------------------------------------------- /tests/unit/remove_objects_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the 'License'); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an 'AS IS' BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import itertools 18 | import unittest.mock as mock 19 | from unittest import TestCase 20 | 21 | from minio import Minio 22 | from minio.api import _DEFAULT_USER_AGENT 23 | from minio.deleteobjects import DeleteObject 24 | 25 | from .minio_mocks import MockConnection, MockResponse 26 | 27 | 28 | class RemoveObjectsTest(TestCase): 29 | @mock.patch('urllib3.PoolManager') 30 | def test_object_is_list(self, mock_connection): 31 | mock_server = MockConnection() 32 | mock_connection.return_value = mock_server 33 | mock_server.mock_add_request( 34 | MockResponse('POST', 35 | 'https://localhost:9000/hello?delete=', 36 | {'User-Agent': _DEFAULT_USER_AGENT, 37 | 'Content-Md5': u'Te1kmIjQRNNz70DJjsrD8A=='}, 200, 38 | content=b'') 39 | ) 40 | client = Minio('localhost:9000') 41 | for err in client.remove_objects( 42 | "hello", 43 | [DeleteObject("Ab"), DeleteObject("c")], 44 | ): 45 | print(err) 46 | 47 | @mock.patch('urllib3.PoolManager') 48 | def test_object_is_tuple(self, mock_connection): 49 | mock_server = MockConnection() 50 | mock_connection.return_value = mock_server 51 | mock_server.mock_add_request( 52 | MockResponse('POST', 53 | 'https://localhost:9000/hello?delete=', 54 | {'User-Agent': _DEFAULT_USER_AGENT, 55 | 'Content-Md5': u'Te1kmIjQRNNz70DJjsrD8A=='}, 200, 56 | content=b'') 57 | ) 58 | client = Minio('localhost:9000') 59 | for err in client.remove_objects( 60 | "hello", 61 | (DeleteObject("Ab"), DeleteObject("c")), 62 | ): 63 | print(err) 64 | 65 | @mock.patch('urllib3.PoolManager') 66 | def test_object_is_iterator(self, mock_connection): 67 | mock_server = MockConnection() 68 | mock_connection.return_value = mock_server 69 | mock_server.mock_add_request( 70 | MockResponse('POST', 71 | 'https://localhost:9000/hello?delete=', 72 | {'User-Agent': _DEFAULT_USER_AGENT, 73 | 'Content-Md5': u'Te1kmIjQRNNz70DJjsrD8A=='}, 200, 74 | content=b'') 75 | ) 76 | client = Minio('localhost:9000') 77 | it = itertools.chain((DeleteObject("Ab"), DeleteObject("c"))) 78 | for err in client.remove_objects('hello', it): 79 | print(err) 80 | -------------------------------------------------------------------------------- /tests/unit/replicationconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.commonconfig import DISABLED, ENABLED, AndOperator, Filter, Tags 21 | from minio.replicationconfig import (DeleteMarkerReplication, Destination, 22 | ReplicationConfig, Rule) 23 | 24 | 25 | class ReplicationConfigTest(TestCase): 26 | def test_config(self): 27 | tags = Tags() 28 | tags.update({"key1": "value1", "key2": "value2"}) 29 | config = ReplicationConfig( 30 | "REPLACE-WITH-ACTUAL-ROLE", 31 | [ 32 | Rule( 33 | Destination( 34 | "REPLACE-WITH-ACTUAL-DESTINATION-BUCKET-ARN", 35 | ), 36 | ENABLED, 37 | delete_marker_replication=DeleteMarkerReplication( 38 | DISABLED, 39 | ), 40 | rule_filter=Filter(AndOperator("TaxDocs", tags)), 41 | rule_id="rule1", 42 | priority=1, 43 | ), 44 | ], 45 | ) 46 | xml.marshal(config) 47 | 48 | config = xml.unmarshal( 49 | ReplicationConfig, 50 | """ 51 | arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3 52 | 53 | rule1 54 | Enabled 55 | 1 56 | 57 | Disabled 58 | 59 | 60 | 61 | TaxDocs 62 | 63 | key1 64 | value1 65 | 66 | 67 | key1 68 | value1 69 | 70 | 71 | 72 | 73 | arn:aws:s3:::exampletargetbucket 74 | 75 | 76 | """, 77 | ) 78 | xml.marshal(config) 79 | -------------------------------------------------------------------------------- /tests/unit/retention_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from datetime import datetime, timedelta, timezone 18 | from unittest import TestCase 19 | 20 | from minio import xml 21 | from minio.commonconfig import COMPLIANCE, GOVERNANCE 22 | from minio.retention import Retention 23 | from minio.time import utcnow 24 | 25 | 26 | class RetentionTest(TestCase): 27 | def test_config(self): 28 | config = Retention(GOVERNANCE, utcnow() + timedelta(days=10)) 29 | xml.marshal(config) 30 | 31 | config = xml.unmarshal( 32 | Retention, 33 | """ 34 | COMPLIANCE 35 | 2020-10-02T00:00:00Z 36 | """, 37 | ) 38 | xml.marshal(config) 39 | self.assertEqual(config.mode, COMPLIANCE) 40 | self.assertEqual( 41 | config.retain_until_date, 42 | datetime(2020, 10, 2, 0, 0, 0, 0, timezone.utc), 43 | ) 44 | -------------------------------------------------------------------------------- /tests/unit/sseconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.sseconfig import AWS_KMS, Rule, SSEConfig 21 | 22 | 23 | class ReplicationConfigTest(TestCase): 24 | def test_config(self): 25 | config = SSEConfig(Rule.new_sse_s3_rule()) 26 | xml.marshal(config) 27 | 28 | config = xml.unmarshal( 29 | SSEConfig, 30 | """ 31 | 32 | 33 | aws:kms 34 | arn:aws:kms:us-east-1:1234/5678example 35 | 36 | 37 | 38 | """, 39 | ) 40 | xml.marshal(config) 41 | self.assertEqual(config.rule.sse_algorithm, AWS_KMS) 42 | self.assertEqual( 43 | config.rule.kms_master_key_id, 44 | "arn:aws:kms:us-east-1:1234/5678example", 45 | ) 46 | -------------------------------------------------------------------------------- /tests/unit/stat_object_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the 'License'); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an 'AS IS' BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import unittest.mock as mock 18 | from unittest import TestCase 19 | 20 | from minio import Minio 21 | from minio.api import _DEFAULT_USER_AGENT 22 | 23 | from .minio_mocks import MockConnection, MockResponse 24 | 25 | 26 | class StatObject(TestCase): 27 | def test_object_is_string(self): 28 | client = Minio('localhost:9000') 29 | self.assertRaises(TypeError, client.stat_object, 'hello', 1234) 30 | 31 | def test_object_is_not_empty_string(self): 32 | client = Minio('localhost:9000') 33 | self.assertRaises(ValueError, client.stat_object, 'hello', ' \t \n ') 34 | 35 | def test_stat_object_invalid_name(self): 36 | client = Minio('localhost:9000') 37 | self.assertRaises(ValueError, client.stat_object, 'AB#CD', 'world') 38 | 39 | @mock.patch('urllib3.PoolManager') 40 | def test_stat_object_works(self, mock_connection): 41 | mock_headers = { 42 | 'content-type': 'application/octet-stream', 43 | 'last-modified': 'Fri, 26 Jun 2015 19:05:37 GMT', 44 | 'content-length': 11, 45 | 'etag': '5eb63bbbe01eeed093cb22bb8f5acdc3' 46 | } 47 | mock_server = MockConnection() 48 | mock_connection.return_value = mock_server 49 | mock_server.mock_add_request( 50 | MockResponse('HEAD', 51 | 'https://localhost:9000/hello/world', 52 | {'User-Agent': _DEFAULT_USER_AGENT}, 200, 53 | response_headers=mock_headers) 54 | ) 55 | client = Minio('localhost:9000') 56 | client.stat_object('hello', 'world') 57 | -------------------------------------------------------------------------------- /tests/unit/tagging_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.commonconfig import Tags 21 | from minio.tagging import Tagging 22 | 23 | 24 | class TaggingTest(TestCase): 25 | def test_tagging(self): 26 | tags = Tags() 27 | tags["Project"] = "Project One" 28 | tags["User"] = "jsmith" 29 | tagging = Tagging(tags) 30 | xml.marshal(tagging) 31 | 32 | config = xml.unmarshal( 33 | Tagging, 34 | """ 35 | 36 | 37 | key1 38 | value1 39 | 40 | 41 | key2 42 | value2 43 | 44 | 45 | """, 46 | ) 47 | xml.marshal(config) 48 | -------------------------------------------------------------------------------- /tests/unit/time_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2024 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | import locale 18 | import threading 19 | import unittest 20 | from contextlib import contextmanager 21 | from datetime import datetime, timezone 22 | from typing import Any, Generator 23 | 24 | from minio.time import from_http_header, to_http_header 25 | 26 | LOCALE_LOCK = threading.Lock() 27 | LAST_MODIFIED_STR = "Mon, 02 Mar 2015 07:28:00 GMT" 28 | LAST_MODIFIED_DATE = datetime( 29 | year=2015, 30 | month=3, 31 | day=2, 32 | hour=7, 33 | minute=28, 34 | second=0, 35 | tzinfo=timezone.utc, 36 | ) 37 | 38 | 39 | @contextmanager 40 | def setlocale(name) -> Generator[str, Any, None]: 41 | with LOCALE_LOCK: 42 | saved = locale.setlocale(locale.LC_ALL) 43 | try: 44 | yield locale.setlocale(locale.LC_ALL, name) 45 | finally: 46 | locale.setlocale(locale.LC_ALL, saved) 47 | 48 | 49 | class TimeutilsTest(unittest.TestCase): 50 | def test_from_http_header_valid_headers(self) -> None: 51 | for case in [ 52 | ( 53 | "Wed, 30 Oct 2024 09:35:00 GMT", 54 | datetime( 55 | year=2024, 56 | month=10, 57 | day=30, 58 | hour=9, 59 | minute=35, 60 | second=0, 61 | tzinfo=timezone.utc, 62 | ), 63 | ), 64 | ( 65 | "Tue, 29 Oct 2024 00:35:00 GMT", 66 | datetime( 67 | year=2024, 68 | month=10, 69 | day=29, 70 | hour=0, 71 | minute=35, 72 | second=0, 73 | tzinfo=timezone.utc, 74 | ), 75 | ), 76 | ( 77 | "Tue, 01 Oct 2024 22:35:22 GMT", 78 | datetime( 79 | year=2024, 80 | month=10, 81 | day=1, 82 | hour=22, 83 | minute=35, 84 | second=22, 85 | tzinfo=timezone.utc, 86 | ), 87 | ), 88 | ( 89 | "Mon, 30 Sep 2024 22:35:55 GMT", 90 | datetime( 91 | year=2024, 92 | month=9, 93 | day=30, 94 | hour=22, 95 | minute=35, 96 | second=55, 97 | tzinfo=timezone.utc, 98 | ), 99 | ), 100 | ]: 101 | with self.subTest(case=case): 102 | self.assertEqual(from_http_header(case[0]), case[1]) 103 | 104 | def test_from_http_header_invalid_headers(self) -> None: 105 | for case in [ 106 | ("Wed, 30 Oct 2024 09:35:00 GMT ", "invalid length"), 107 | ("Wet, 30 Oct 2024 09:35:00 GMT", "invalid weekday"), 108 | ("Wed 30 Oct 2024 09:35:00 GMT", "no comma after weekday"), 109 | ("Wed,30 Sep 2024 09:35:00 GMT ", "no space after weekday"), 110 | ("Wed, 30Sep 2024 09:35:00 GMT ", "no space before month"), 111 | ("Wed, 00 Sep 2024 09:35:00 GMT", "invalid day"), 112 | ("Wed, 32 Sep 2024 09:35:00 GMT", "invalid day 2"), 113 | ("Wed, ab Sep 2024 09:35:00 GMT", "invalid day 3"), 114 | ("Wed, 30 Set 2024 09:35:00 GMT", "invalid month"), 115 | ("Tue, 30 Set 2024 09:35:00 GMT", "name of day doesn't match"), 116 | ]: 117 | with self.subTest(case=case): 118 | self.assertRaises(ValueError, from_http_header, case[0]) 119 | 120 | def test_from_http_header_default_locale(self) -> None: 121 | result_datetime = from_http_header(LAST_MODIFIED_STR) 122 | 123 | self.assertEqual( 124 | result_datetime, 125 | LAST_MODIFIED_DATE, 126 | ) 127 | 128 | def test_from_http_header_polish_locale(self) -> None: 129 | try: 130 | with setlocale("pl_PL.utf8"): 131 | result_datetime = from_http_header(LAST_MODIFIED_STR) 132 | 133 | self.assertEqual( 134 | result_datetime, 135 | LAST_MODIFIED_DATE, 136 | ) 137 | except locale.Error: 138 | self.skipTest("pl_PL.utf8 locale is not supported on this machine") 139 | 140 | def test_to_http_header_default_locale(self) -> None: 141 | self.assertEqual( 142 | to_http_header(LAST_MODIFIED_DATE), 143 | LAST_MODIFIED_STR, 144 | ) 145 | 146 | def test_to_http_header_polish_locale(self) -> None: 147 | try: 148 | with setlocale("pl_PL.utf8"): 149 | self.assertEqual( 150 | to_http_header(LAST_MODIFIED_DATE), 151 | LAST_MODIFIED_STR, 152 | ) 153 | except locale.Error: 154 | self.skipTest("pl_PL.utf8 locale is not supported on this machine") 155 | -------------------------------------------------------------------------------- /tests/unit/trace_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2015, 2016 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import Minio 20 | 21 | 22 | class TraceTest(TestCase): 23 | def test_bucket_is_string(self): 24 | client = Minio('localhost:9000') 25 | self.assertRaises(ValueError, client.trace_on, None) 26 | -------------------------------------------------------------------------------- /tests/unit/versioningconfig_test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # MinIO Python Library for Amazon S3 Compatible Cloud Storage, 3 | # (C) 2020 MinIO, Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | from unittest import TestCase 18 | 19 | from minio import xml 20 | from minio.commonconfig import DISABLED, ENABLED 21 | from minio.versioningconfig import OFF, SUSPENDED, VersioningConfig 22 | 23 | 24 | class VersioningConfigTest(TestCase): 25 | def test_config(self): 26 | config = VersioningConfig(ENABLED) 27 | xml.marshal(config) 28 | 29 | config = xml.unmarshal( 30 | VersioningConfig, 31 | """ 32 | """, 33 | ) 34 | xml.marshal(config) 35 | self.assertEqual(config.status, OFF) 36 | 37 | config = xml.unmarshal( 38 | VersioningConfig, 39 | """ 40 | Enabled 41 | """, 42 | ) 43 | xml.marshal(config) 44 | self.assertEqual(config.status, ENABLED) 45 | 46 | config = xml.unmarshal( 47 | VersioningConfig, 48 | """ 49 | Suspended 50 | Disabled 51 | """, 52 | ) 53 | xml.marshal(config) 54 | self.assertEqual(config.status, SUSPENDED) 55 | self.assertEqual(config.mfa_delete, DISABLED) 56 | --------------------------------------------------------------------------------