├── .editorconfig ├── .github └── workflows │ ├── release.yml │ └── tox.yml ├── .gitignore ├── .readthedocs.yaml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── LICENSE-APACHE ├── README.md ├── dev-requirements.txt ├── docker-compose.yml ├── docs-requirements.txt ├── docs ├── contributing.md ├── development.md ├── index.md ├── licences.md └── usage.md ├── minio_storage ├── __init__.py ├── apps.py ├── errors.py ├── files.py ├── management │ ├── __init__.py │ └── commands │ │ ├── __init__.py │ │ └── minio.py ├── policy.py ├── py.typed └── storage.py ├── mkdocs.yml ├── pyproject.toml ├── pyrightconfig.json ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── django_minio_storage_tests │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py ├── test_app │ ├── __init__.py │ └── tests │ │ ├── __init__.py │ │ ├── bucket_tests.py │ │ ├── custom_storage_class_tests.py │ │ ├── delete_tests.py │ │ ├── managementcommand_tests.py │ │ ├── package_tests.py │ │ ├── retrieve_tests.py │ │ ├── settings_tests.py │ │ ├── upload_tests.py │ │ └── utils.py └── watermelon-cat.jpg └── tox.ini /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | charset = utf-8 9 | 10 | [*.py] 11 | indent_size = 4 12 | max_line_length = 88 13 | 14 | [{*.yml,*.yaml}] 15 | indent_size = 2 16 | 17 | [*.json] 18 | indent_size = 2 19 | max_line_length = 88 20 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - v0.** 7 | - v1.** 8 | 9 | jobs: 10 | pypi-publish: 11 | name: Upload release to PyPI 12 | runs-on: ubuntu-latest 13 | permissions: 14 | id-token: write 15 | environment: release 16 | steps: 17 | - uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | - name: Set up Python 21 | uses: actions/setup-python@v5 22 | with: 23 | python-version: "3.x" 24 | - name: Install pypa/build 25 | run: >- 26 | python -m 27 | pip install 28 | build 29 | --user 30 | - name: Build a binary wheel and a source tarball 31 | run: >- 32 | python -m 33 | build 34 | --sdist 35 | --wheel 36 | --outdir dist/ 37 | . 38 | - name: Publish package 39 | uses: pypa/gh-action-pypi-publish@release/v1 40 | -------------------------------------------------------------------------------- /.github/workflows/tox.yml: -------------------------------------------------------------------------------- 1 | name: tox 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: ['3.9', '3.10', '3.11', '3.12', '3.13'] 15 | 16 | env: 17 | MINIO_STORAGE_ENDPOINT: 127.0.0.1:9000 18 | MINIO_STORAGE_ACCESS_KEY: minioadmin 19 | MINIO_STORAGE_SECRET_KEY: minioadmin 20 | 21 | services: 22 | minio: 23 | # This image does not require any command arguments (which GitHub Actions don't support) 24 | image: bitnami/minio:latest 25 | env: 26 | MINIO_ROOT_USER: minioadmin 27 | MINIO_ROOT_PASSWORD: minioadmin 28 | ports: 29 | - 9000:9000 30 | 31 | steps: 32 | - uses: actions/checkout@v4 33 | with: 34 | fetch-depth: 0 35 | - name: Set up Python ${{ matrix.python-version }} 36 | uses: actions/setup-python@v5 37 | with: 38 | python-version: ${{ matrix.python-version }} 39 | - name: Install dependencies 40 | run: | 41 | python -m pip install --upgrade pip 42 | python -m pip install tox tox-gh-actions 43 | - name: Test with tox 44 | run: tox 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /minio_storage/version.py 2 | 3 | # Created by https://www.toptal.com/developers/gitignore/api/django 4 | # Edit at https://www.toptal.com/developers/gitignore?templates=django 5 | 6 | ### Django ### 7 | *.log 8 | *.pot 9 | *.pyc 10 | __pycache__/ 11 | local_settings.py 12 | db.sqlite3 13 | db.sqlite3-journal 14 | media 15 | 16 | # If your build process includes running collectstatic, then you probably don't need or want to include staticfiles/ 17 | # in your Git repository. Update and uncomment the following line accordingly. 18 | # /staticfiles/ 19 | 20 | ### Django.Python Stack ### 21 | # Byte-compiled / optimized / DLL files 22 | *.py[cod] 23 | *$py.class 24 | 25 | # C extensions 26 | *.so 27 | 28 | # Distribution / packaging 29 | .Python 30 | build/ 31 | develop-eggs/ 32 | dist/ 33 | downloads/ 34 | eggs/ 35 | .eggs/ 36 | lib/ 37 | lib64/ 38 | parts/ 39 | sdist/ 40 | var/ 41 | wheels/ 42 | share/python-wheels/ 43 | *.egg-info/ 44 | .installed.cfg 45 | *.egg 46 | MANIFEST 47 | 48 | # PyInstaller 49 | # Usually these files are written by a python script from a template 50 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 51 | *.manifest 52 | *.spec 53 | 54 | # Installer logs 55 | pip-log.txt 56 | pip-delete-this-directory.txt 57 | 58 | # Unit test / coverage reports 59 | htmlcov/ 60 | .tox/ 61 | .nox/ 62 | .coverage 63 | .coverage.* 64 | .cache 65 | nosetests.xml 66 | coverage.xml 67 | *.cover 68 | *.py,cover 69 | .hypothesis/ 70 | .pytest_cache/ 71 | cover/ 72 | 73 | # Translations 74 | *.mo 75 | 76 | # Django stuff: 77 | 78 | # Flask stuff: 79 | instance/ 80 | .webassets-cache 81 | 82 | # Scrapy stuff: 83 | .scrapy 84 | 85 | # Sphinx documentation 86 | docs/_build/ 87 | 88 | # PyBuilder 89 | .pybuilder/ 90 | target/ 91 | 92 | # Jupyter Notebook 93 | .ipynb_checkpoints 94 | 95 | # IPython 96 | profile_default/ 97 | ipython_config.py 98 | 99 | # pyenv 100 | # For a library or package, you might want to ignore these files since the code is 101 | # intended to run in multiple environments; otherwise, check them in: 102 | # .python-version 103 | 104 | # pipenv 105 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 106 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 107 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 108 | # install all needed dependencies. 109 | #Pipfile.lock 110 | 111 | # poetry 112 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 113 | # This is especially recommended for binary packages to ensure reproducibility, and is more 114 | # commonly ignored for libraries. 115 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 116 | #poetry.lock 117 | 118 | # pdm 119 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 120 | #pdm.lock 121 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 122 | # in version control. 123 | # https://pdm.fming.dev/#use-with-ide 124 | .pdm.toml 125 | 126 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 127 | __pypackages__/ 128 | 129 | # Celery stuff 130 | celerybeat-schedule 131 | celerybeat.pid 132 | 133 | # SageMath parsed files 134 | *.sage.py 135 | 136 | # Environments 137 | .env 138 | .venv 139 | env/ 140 | venv/ 141 | ENV/ 142 | env.bak/ 143 | venv.bak/ 144 | 145 | # Spyder project settings 146 | .spyderproject 147 | .spyproject 148 | 149 | # Rope project settings 150 | .ropeproject 151 | 152 | # mkdocs documentation 153 | /site 154 | 155 | # mypy 156 | .mypy_cache/ 157 | .dmypy.json 158 | dmypy.json 159 | 160 | # Pyre type checker 161 | .pyre/ 162 | 163 | # pytype static type analyzer 164 | .pytype/ 165 | 166 | # Cython debug symbols 167 | cython_debug/ 168 | 169 | # PyCharm 170 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 171 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 172 | # and can be added to the global gitignore or merged into this file. For a more nuclear 173 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 174 | #.idea/ 175 | 176 | # End of https://www.toptal.com/developers/gitignore/api/django 177 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | # Read the Docs configuration file 3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 4 | 5 | # Required 6 | version: 2 7 | 8 | # Set the version of Python and other tools you might need 9 | build: 10 | os: ubuntu-22.04 11 | tools: 12 | python: "3.11" 13 | 14 | mkdocs: 15 | configuration: mkdocs.yml 16 | 17 | python: 18 | install: 19 | - requirements: docs-requirements.txt 20 | 21 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 0.5.3 2 | 3 | Migrate package meta data to pyproject.toml 4 | 5 | ## 0.5.2 6 | 7 | Add/fix more type hints. 8 | 9 | ## 0.5.1 10 | 11 | Fix type hints 12 | 13 | ## 0.5.0 14 | 15 | Switched the minio-py client library version from `<7` to `>=7`. 16 | 17 | Minimum Django version is now 3.2 18 | 19 | Minimum Python version is now 3.8 20 | 21 | ## 0.3.9 22 | 23 | The minio client is now deconstructable by Django, fixes migrations. 24 | 25 | ## 0.3.8 26 | 27 | Improved presigned urls with non standard base urls 28 | 29 | ## 0.3.7 30 | 31 | Removed accidentally left over debug print from previous release 32 | 33 | ## 0.3.6 34 | 35 | ### support adding default meta data 36 | 37 | Also new settings: MINIO_STORAGE_MEDIA_OBJECT_METADATA and 38 | MINIO_STORAGE_STATIC_OBJECT_METADATA 39 | 40 | example: 41 | 42 | ```py 43 | MINIO_STORAGE_MEDIA_OBJECT_METADATA = {"Cache-Control": "max-age=1000"} 44 | ``` 45 | 46 | ### fix issue with directory listing names 47 | 48 | Minio has changed in the last months to be more picky about path names so we 49 | now enure that we don't create path prefixes with a // suffix. 50 | 51 | 52 | ## 0.3.5 53 | 54 | #### Add support for skipping bucket existst/policy check on start up 55 | https://github.com/py-pa/django-minio-storage/commit/7086f125ed74b157240bae10c589ce785ca93bbf 56 | 57 | Added settings MINIO_STORAGE_ASSUME_MEDIA_BUCKET_EXISTS and 58 | MINIO_STORAGE_ASSUME_STATIC_BUCKET_EXISTS 59 | 60 | ## 0.3.4 61 | 62 | #### • fixed resource leak where one extra file was opened per file and never closed 63 | https://github.com/py-pa/django-minio-storage/commit/1532e34c7dcecbc2cf3ca0805d6fbf42b57c25ba 64 | 65 | There leaked file descriptors were only freed by the gargabe collector before 66 | this fix so if you have farily tight loop that does something to a lot of files 67 | while not generating a lot of garbage to trigger the gc. 68 | 69 | 70 | ## 0.3.3 71 | 72 | #### • reworked management commands and added tests. 73 | 74 | ``` 75 | $ python manage.py minio 76 | usage: minio [-h] [--class CLASS] [--bucket BUCKET] [--version] 77 | [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] 78 | [--traceback] [--no-color] [--force-color] 79 | {check,create,delete,ls,policy} ... 80 | ... 81 | minio: 82 | --class CLASS Storage class to modify (media/static are short names 83 | for default classes) 84 | --bucket BUCKET bucket name (default: storage defined bucket if not 85 | set) 86 | 87 | subcommands: 88 | valid subcommands 89 | 90 | {check,create,delete,ls,policy} 91 | check check bucket 92 | create make bucket 93 | delete remove an empty bucket 94 | ls list bucket objects or buckets 95 | policy get or set bucket policy 96 | ``` 97 | 98 | 99 | ## 0.3.2 100 | 101 | #### • GET_ONLY is now the default bucket policy 102 | 103 | 104 | ## 0.3.1 105 | 106 | ### Changes 107 | 108 | #### • dropped python 2 support, 3.6+ is now required 109 | 110 | #### • dropped support for django earlier than 1.11 111 | 112 | #### • policy settings default values changed 113 | 114 | - MINIO_STORAGE_AUTO_CREATE_..._POLICY now has more options (see Policy enum) 115 | - MINIO_STORAGE_AUTO_CREATE_..._POLICY now defaults to GET_ONLY 116 | 117 | ### New feautures 118 | 119 | #### • new django management commands 120 | 121 | - minio_bucket 122 | - minio_bucket_policy 123 | #### • implement Storage.listdir(): 124 | 125 | https://github.com/py-pa/django-minio-storage/commit/9300d3d0b819672dbae788155258ff499788691c 126 | 127 | #### • add max_age to Storage.url() 128 | 129 | https://github.com/py-pa/django-minio-storage/commit/5084b954ad0ba0afad340a8d1010ccd2e491a30c 130 | 131 | ### Fixes 132 | 133 | #### • urlquote object name when using BASE_URL setting 134 | 135 | https://github.com/py-pa/django-minio-storage/commit/960961932bcef8c17fbb774f0ef5fa3022af15a2 136 | 137 | 138 | ## 0.2.2 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | see [docs/contributing](docs/contributing) 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 The django-minio-storage developers 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 The django-minio-storage developers 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PyPI version](https://badge.fury.io/py/django-minio-storage.svg)](https://badge.fury.io/py/django-minio-storage) 2 | [![PyPI - Downloads](https://img.shields.io/pypi/dm/django-minio-storage)](https://pypistats.org/packages/django-minio-storage) 3 | [![Documentation Status](http://readthedocs.org/projects/django-minio-storage/badge/?version=latest)](http://django-minio-storage.readthedocs.io/en/latest/?badge=latest) 4 | 5 | 6 | # django-minio-storage 7 | 8 | Use [minio](https://minio.io) for django static and media file storage. 9 | 10 | Minio is accessed through the Amazon S3 API, so existing django file storage 11 | adapters for S3 should work, but in practice they are hard to configure. This 12 | project uses the minio python client instead. Inspiration has been drawn from 13 | `django-s3-storage` and `django-storages`. 14 | 15 | # Documentation 16 | 17 | See 18 | [http://django-minio-storage.readthedocs.io/en/latest/](http://django-minio-storage.readthedocs.io/en/latest/) for 19 | documentation and usage guides. 20 | -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | freezegun 3 | 4 | # PyTest for running the tests. 5 | pytest==8.3.5 6 | pytest-django==4.11.1 7 | pytest-cov==6.1.1 8 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | minio: 3 | image: minio/minio:latest 4 | tty: true 5 | command: ["server", "/export"] 6 | environment: 7 | MINIO_ROOT_USER: weak_access_key 8 | MINIO_ROOT_PASSWORD: weak_secret_key 9 | ports: 10 | - 9153:9000 11 | -------------------------------------------------------------------------------- /docs-requirements.txt: -------------------------------------------------------------------------------- 1 | mkdocs==1.6.* 2 | -------------------------------------------------------------------------------- /docs/contributing.md: -------------------------------------------------------------------------------- 1 | ## Licencing 2 | Unless you explicitly state otherwise, any contribution intentionally submitted 3 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall be 4 | dual licensed as above, without any additional terms or conditions. 5 | 6 | 7 | -------------------------------------------------------------------------------- /docs/development.md: -------------------------------------------------------------------------------- 1 | ## Testing strategy 2 | 3 | Test coverage is and should remain near 100%. 4 | 5 | This package is very small and a minio server can be very easily brought up 6 | with docker so there is typically no reason to use mocking at all. The tests 7 | should run directly against a real minio server instance. 8 | 9 | ## Running tests 10 | 11 | To run the tests you need to have minio running locally with some specific 12 | settings, you can start it using docker-compose: 13 | 14 | ```sh 15 | docker-compose up -d 16 | ``` 17 | 18 | Use tox to run the tests for all environments in `tox.ini`: 19 | 20 | ```sh 21 | tox 22 | ``` 23 | 24 | Or just run tests for some of them 25 | 26 | ```sh 27 | # list all environment 28 | tox -l 29 | # run one or more of them 30 | tox -e py35-django110,py35-django111 31 | ``` 32 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # About 2 | 3 | **django-minio-storage** enables using [minio](https://minio.io) as django 4 | static and media file storages. 5 | 6 | Minio is accessed through the Amazon S3 API, so existing django file storage 7 | adapters for S3 should work, but in practice they are hard to configure. This 8 | project uses the minio python client instead. Inspiration has been drawn from 9 | `django-s3-storage` and `django-storages`. 10 | 11 | The project source code and issue tracking is hosted at 12 | [github.com/py-pa/django-minio-storage](https://github.com/py-pa/django-minio-storage). 13 | 14 | # Compatibility 15 | 16 | CI is currenlty executed on Python 3.8+ and Django 3.2+. 17 | 18 | The goal is to have a thoroughly tested, small code base that delegates as much 19 | as possible to the minio client. 20 | 21 | - Release versioning is semver compliant. 22 | -------------------------------------------------------------------------------- /docs/licences.md: -------------------------------------------------------------------------------- 1 | `django-minio-storage` is Licensed under either of: 2 | 3 | - Apache License, Version 2.0, (http://www.apache.org/licenses/LICENSE-2.0) 4 | 5 | - MIT license (http://opensource.org/licenses/MIT) at your option. 6 | 7 | 8 | ## MIT 9 | 10 | ```text 11 | The MIT License (MIT) 12 | 13 | Copyright (c) 2016 The django-minio-storage developers 14 | 15 | Permission is hereby granted, free of charge, to any person obtaining a copy of 16 | this software and associated documentation files (the "Software"), to deal in 17 | the Software without restriction, including without limitation the rights to 18 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 19 | the Software, and to permit persons to whom the Software is furnished to do so, 20 | subject to the following conditions: 21 | 22 | The above copyright notice and this permission notice shall be included in all 23 | copies or substantial portions of the Software. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 27 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 28 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 29 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 30 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 31 | ``` 32 | 33 | ## Apache 34 | 35 | ```text 36 | Apache License 37 | Version 2.0, January 2004 38 | http://www.apache.org/licenses/ 39 | 40 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 41 | 42 | 1. Definitions. 43 | 44 | "License" shall mean the terms and conditions for use, reproduction, 45 | and distribution as defined by Sections 1 through 9 of this document. 46 | 47 | "Licensor" shall mean the copyright owner or entity authorized by 48 | the copyright owner that is granting the License. 49 | 50 | "Legal Entity" shall mean the union of the acting entity and all 51 | other entities that control, are controlled by, or are under common 52 | control with that entity. For the purposes of this definition, 53 | "control" means (i) the power, direct or indirect, to cause the 54 | direction or management of such entity, whether by contract or 55 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 56 | outstanding shares, or (iii) beneficial ownership of such entity. 57 | 58 | "You" (or "Your") shall mean an individual or Legal Entity 59 | exercising permissions granted by this License. 60 | 61 | "Source" form shall mean the preferred form for making modifications, 62 | including but not limited to software source code, documentation 63 | source, and configuration files. 64 | 65 | "Object" form shall mean any form resulting from mechanical 66 | transformation or translation of a Source form, including but 67 | not limited to compiled object code, generated documentation, 68 | and conversions to other media types. 69 | 70 | "Work" shall mean the work of authorship, whether in Source or 71 | Object form, made available under the License, as indicated by a 72 | copyright notice that is included in or attached to the work 73 | (an example is provided in the Appendix below). 74 | 75 | "Derivative Works" shall mean any work, whether in Source or Object 76 | form, that is based on (or derived from) the Work and for which the 77 | editorial revisions, annotations, elaborations, or other modifications 78 | represent, as a whole, an original work of authorship. For the purposes 79 | of this License, Derivative Works shall not include works that remain 80 | separable from, or merely link (or bind by name) to the interfaces of, 81 | the Work and Derivative Works thereof. 82 | 83 | "Contribution" shall mean any work of authorship, including 84 | the original version of the Work and any modifications or additions 85 | to that Work or Derivative Works thereof, that is intentionally 86 | submitted to Licensor for inclusion in the Work by the copyright owner 87 | or by an individual or Legal Entity authorized to submit on behalf of 88 | the copyright owner. For the purposes of this definition, "submitted" 89 | means any form of electronic, verbal, or written communication sent 90 | to the Licensor or its representatives, including but not limited to 91 | communication on electronic mailing lists, source code control systems, 92 | and issue tracking systems that are managed by, or on behalf of, the 93 | Licensor for the purpose of discussing and improving the Work, but 94 | excluding communication that is conspicuously marked or otherwise 95 | designated in writing by the copyright owner as "Not a Contribution." 96 | 97 | "Contributor" shall mean Licensor and any individual or Legal Entity 98 | on behalf of whom a Contribution has been received by Licensor and 99 | subsequently incorporated within the Work. 100 | 101 | 2. Grant of Copyright License. Subject to the terms and conditions of 102 | this License, each Contributor hereby grants to You a perpetual, 103 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 104 | copyright license to reproduce, prepare Derivative Works of, 105 | publicly display, publicly perform, sublicense, and distribute the 106 | Work and such Derivative Works in Source or Object form. 107 | 108 | 3. Grant of Patent License. Subject to the terms and conditions of 109 | this License, each Contributor hereby grants to You a perpetual, 110 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 111 | (except as stated in this section) patent license to make, have made, 112 | use, offer to sell, sell, import, and otherwise transfer the Work, 113 | where such license applies only to those patent claims licensable 114 | by such Contributor that are necessarily infringed by their 115 | Contribution(s) alone or by combination of their Contribution(s) 116 | with the Work to which such Contribution(s) was submitted. If You 117 | institute patent litigation against any entity (including a 118 | cross-claim or counterclaim in a lawsuit) alleging that the Work 119 | or a Contribution incorporated within the Work constitutes direct 120 | or contributory patent infringement, then any patent licenses 121 | granted to You under this License for that Work shall terminate 122 | as of the date such litigation is filed. 123 | 124 | 4. Redistribution. You may reproduce and distribute copies of the 125 | Work or Derivative Works thereof in any medium, with or without 126 | modifications, and in Source or Object form, provided that You 127 | meet the following conditions: 128 | 129 | (a) You must give any other recipients of the Work or 130 | Derivative Works a copy of this License; and 131 | 132 | (b) You must cause any modified files to carry prominent notices 133 | stating that You changed the files; and 134 | 135 | (c) You must retain, in the Source form of any Derivative Works 136 | that You distribute, all copyright, patent, trademark, and 137 | attribution notices from the Source form of the Work, 138 | excluding those notices that do not pertain to any part of 139 | the Derivative Works; and 140 | 141 | (d) If the Work includes a "NOTICE" text file as part of its 142 | distribution, then any Derivative Works that You distribute must 143 | include a readable copy of the attribution notices contained 144 | within such NOTICE file, excluding those notices that do not 145 | pertain to any part of the Derivative Works, in at least one 146 | of the following places: within a NOTICE text file distributed 147 | as part of the Derivative Works; within the Source form or 148 | documentation, if provided along with the Derivative Works; or, 149 | within a display generated by the Derivative Works, if and 150 | wherever such third-party notices normally appear. The contents 151 | of the NOTICE file are for informational purposes only and 152 | do not modify the License. You may add Your own attribution 153 | notices within Derivative Works that You distribute, alongside 154 | or as an addendum to the NOTICE text from the Work, provided 155 | that such additional attribution notices cannot be construed 156 | as modifying the License. 157 | 158 | You may add Your own copyright statement to Your modifications and 159 | may provide additional or different license terms and conditions 160 | for use, reproduction, or distribution of Your modifications, or 161 | for any such Derivative Works as a whole, provided Your use, 162 | reproduction, and distribution of the Work otherwise complies with 163 | the conditions stated in this License. 164 | 165 | 5. Submission of Contributions. Unless You explicitly state otherwise, 166 | any Contribution intentionally submitted for inclusion in the Work 167 | by You to the Licensor shall be under the terms and conditions of 168 | this License, without any additional terms or conditions. 169 | Notwithstanding the above, nothing herein shall supersede or modify 170 | the terms of any separate license agreement you may have executed 171 | with Licensor regarding such Contributions. 172 | 173 | 6. Trademarks. This License does not grant permission to use the trade 174 | names, trademarks, service marks, or product names of the Licensor, 175 | except as required for reasonable and customary use in describing the 176 | origin of the Work and reproducing the content of the NOTICE file. 177 | 178 | 7. Disclaimer of Warranty. Unless required by applicable law or 179 | agreed to in writing, Licensor provides the Work (and each 180 | Contributor provides its Contributions) on an "AS IS" BASIS, 181 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 182 | implied, including, without limitation, any warranties or conditions 183 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 184 | PARTICULAR PURPOSE. You are solely responsible for determining the 185 | appropriateness of using or redistributing the Work and assume any 186 | risks associated with Your exercise of permissions under this License. 187 | 188 | 8. Limitation of Liability. In no event and under no legal theory, 189 | whether in tort (including negligence), contract, or otherwise, 190 | unless required by applicable law (such as deliberate and grossly 191 | negligent acts) or agreed to in writing, shall any Contributor be 192 | liable to You for damages, including any direct, indirect, special, 193 | incidental, or consequential damages of any character arising as a 194 | result of this License or out of the use or inability to use the 195 | Work (including but not limited to damages for loss of goodwill, 196 | work stoppage, computer failure or malfunction, or any and all 197 | other commercial damages or losses), even if such Contributor 198 | has been advised of the possibility of such damages. 199 | 200 | 9. Accepting Warranty or Additional Liability. While redistributing 201 | the Work or Derivative Works thereof, You may choose to offer, 202 | and charge a fee for, acceptance of support, warranty, indemnity, 203 | or other liability obligations and/or rights consistent with this 204 | License. However, in accepting such obligations, You may act only 205 | on Your own behalf and on Your sole responsibility, not on behalf 206 | of any other Contributor, and only if You agree to indemnify, 207 | defend, and hold each Contributor harmless for any liability 208 | incurred by, or claims asserted against, such Contributor by reason 209 | of your accepting any such warranty or additional liability. 210 | 211 | END OF TERMS AND CONDITIONS 212 | 213 | APPENDIX: How to apply the Apache License to your work. 214 | 215 | To apply the Apache License to your work, attach the following 216 | boilerplate notice, with the fields enclosed by brackets "{}" 217 | replaced with your own identifying information. (Don't include 218 | the brackets!) The text should be enclosed in the appropriate 219 | comment syntax for the file format. We also recommend that a 220 | file or class name and description of purpose be included on the 221 | same "printed page" as the copyright notice for easier 222 | identification within third-party archives. 223 | 224 | Copyright 2016 The django-minio-storage developers 225 | 226 | Licensed under the Apache License, Version 2.0 (the "License"); 227 | you may not use this file except in compliance with the License. 228 | You may obtain a copy of the License at 229 | 230 | http://www.apache.org/licenses/LICENSE-2.0 231 | 232 | Unless required by applicable law or agreed to in writing, software 233 | distributed under the License is distributed on an "AS IS" BASIS, 234 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 235 | See the License for the specific language governing permissions and 236 | limitations under the License. 237 | ``` 238 | -------------------------------------------------------------------------------- /docs/usage.md: -------------------------------------------------------------------------------- 1 | ## Installation 2 | 3 | ```sh 4 | pip install django-minio-storage 5 | ``` 6 | 7 | Add `minio_storage` to `INSTALLED_APPS` in your project settings. 8 | 9 | The last step is setting `STORAGES['default']['BACKEND']` to 10 | `'minio_storage.MinioMediaStorage'`, and `STORAGES['staticfiles']['BACKEND']` to 11 | `'minio_storage.MinioStaticStorage'`. 12 | 13 | ## Django settings Configuration 14 | 15 | The following settings are available: 16 | 17 | - `MINIO_STORAGE_ENDPOINT`: the access URL for the service (for example 18 | `minio.example.org:9000` (note that there is no scheme)). 19 | 20 | - `MINIO_STORAGE_ACCESS_KEY` and `MINIO_STORAGE_SECRET_KEY` (mandatory) 21 | 22 | - `MINIO_STORAGE_REGION`: Allows you to specify the region. By setting this 23 | configuration option, an additional HTTP request to Minio for region checking 24 | can be prevented, resulting in improved performance and reduced latency for 25 | generating presigned URLs. 26 | 27 | - `MINIO_STORAGE_USE_HTTPS`: whether to use TLS or not (default: `True`). This 28 | affect both how how Django internally communicates with the Minio server AND 29 | controls if the generated the storage object URLs uses `http://` or 30 | `https://` schemes. 31 | 32 | - `MINIO_STORAGE_MEDIA_BUCKET_NAME`: the bucket that will act as `MEDIA` folder 33 | 34 | - `MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET`: whether to create the bucket if it 35 | does not already exist (default: `False`) 36 | 37 | - `MINIO_STORAGE_ASSUME_MEDIA_BUCKET_EXISTS`: whether to ignore media bucket 38 | creation and policy. 39 | (default: `False`) 40 | 41 | - `MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY`: sets the buckets public policy 42 | right after it's been created by `MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET`. 43 | Valid values are: `GET_ONLY`, `READ_ONLY`, `WRITE_ONLY`, `READ_WRITE` and 44 | `NONE`. (default: `GET_ONLY`) 45 | 46 | - `MINIO_STORAGE_MEDIA_OBJECT_METADATA`: set default additional metadata for 47 | every object persisted during save operations. The value is a dict with 48 | string keys and values, example: `{'Cache-Control': 'max-age=1000'}`. 49 | (default: `None`) 50 | 51 | - `MINIO_STORAGE_STATIC_BUCKET_NAME`: the bucket that will act as `STATIC` 52 | folder 53 | 54 | - `MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET`: whether to create the bucket if it 55 | does not already exist (default: `False`) 56 | 57 | 58 | - `MINIO_STORAGE_ASSUME_STATIC_BUCKET_EXISTS`: whether to ignore the static bucket 59 | creation and policy. 60 | (default: `False`) 61 | 62 | - `MINIO_STORAGE_AUTO_CREATE_STATIC_POLICY`: sets the buckets public policy 63 | right after it's been created by `MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET`. 64 | Valid values are: `GET_ONLY`, `READ_ONLY`, `WRITE_ONLY`, `READ_WRITE` and 65 | `NONE`. (default: `GET_ONLY`) 66 | 67 | - `MINIO_STORAGE_STATIC_OBJECT_METADATA`: set default additional metadata for 68 | every object persisted during save operations. The value is a dict with 69 | string keys and values, example: `{'Cache-Control': 'max-age=1000'}`. 70 | (default: `None`) 71 | 72 | - `MINIO_STORAGE_MEDIA_URL`: the base URL for generating urls to objects from 73 | `MinioMediaStorage`. When not specified or set to `None` it's value will be 74 | combined from `MINIO_STORAGE_ENDPOINT` and `MINIO_STORAGE_MEDIA_BUCKET_NAME`. 75 | `MINIO_STORAGE_MEDIA_URL` should contain the full base url including the 76 | bucket name without a trailing slash. Normally, this should not have to be 77 | set, but may be useful when the storage and end user must access the server 78 | from different endpoints. 79 | 80 | - `MINIO_STORAGE_STATIC_URL`: the base URL for generating URLs to objects from 81 | `MinioStaticStorage`. When not specified or set to `None` it's value will be 82 | combined from `MINIO_STORAGE_ENDPOINT` and 83 | `MINIO_STORAGE_STATIC_BUCKET_NAME`. `MINIO_STORAGE_STATIC_URL` should contain 84 | the full base url including the bucket name without a trailing slash. 85 | Normally, this should not have to be set, but may be useful when the storage 86 | and end user must access the server from different endpoints. 87 | 88 | - `MINIO_STORAGE_MEDIA_BACKUP_BUCKET`: Bucket to be used to store deleted files. 89 | The bucket **has to exists**, the storage will not try to create it. 90 | Required if `MINIO_STORAGE_MEDIA_BACKUP_FORMAT` is set. 91 | 92 | - `MINIO_STORAGE_MEDIA_BACKUP_FORMAT`: Path to be used to store deleted files, 93 | the path can contain Python's `strftime` substitutes, such as `%H`, `%c` and 94 | others. The object name will be appended to the resulting path, without 95 | actually forcing another `/` at the end, so if you set this setting to 96 | `backup-%Y-%m_` then the resulting object name will be (e.g.) 97 | `backup-2018-07_my_object.data`. If you want to store the objects inside 98 | folders, make sure to finish this setting with a forward slash. 99 | Required if `MINIO_STORAGE_MEDIA_BACKUP_BUCKET` is set. 100 | 101 | - `MINIO_STORAGE_MEDIA_USE_PRESIGNED`: Determines if the media file URLs should 102 | be pre-signed (default: `False`) 103 | 104 | - `MINIO_STORAGE_STATIC_USE_PRESIGNED`: Determines if the static file URLs 105 | should be pre-signed (default: `False`) By default set to False. 106 | 107 | ## Short Example 108 | 109 | ```py 110 | STATIC_URL = '/static/' 111 | STATIC_ROOT = './static_files/' 112 | 113 | STORAGES = { 114 | 'default': { 115 | 'BACKEND': 'minio_storage.MinioMediaStorage', 116 | }, 117 | 'staticfiles': { 118 | 'BACKEND': 'minio_storage.MinioStaticStorage', 119 | }, 120 | } 121 | MINIO_STORAGE_ENDPOINT = 'minio:9000' 122 | MINIO_STORAGE_ACCESS_KEY = 'KBP6WXGPS387090EZMG8' 123 | MINIO_STORAGE_SECRET_KEY = 'DRjFXylyfMqn2zilAr33xORhaYz5r9e8r37XPz3A' 124 | MINIO_STORAGE_USE_HTTPS = False 125 | MINIO_STORAGE_MEDIA_OBJECT_METADATA = {'Cache-Control': 'max-age=1000'} 126 | MINIO_STORAGE_MEDIA_BUCKET_NAME = 'local-media' 127 | MINIO_STORAGE_MEDIA_BACKUP_BUCKET = 'Recycle Bin' 128 | MINIO_STORAGE_MEDIA_BACKUP_FORMAT = '%c/' 129 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET = True 130 | MINIO_STORAGE_STATIC_BUCKET_NAME = 'local-static' 131 | MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET = True 132 | 133 | # These settings should generally not be used: 134 | # MINIO_STORAGE_MEDIA_URL = 'http://localhost:9000/local-media' 135 | # MINIO_STORAGE_STATIC_URL = 'http://localhost:9000/local-static' 136 | ``` 137 | 138 | ## Logging 139 | 140 | The library defines a logger with the name `minio_storage` that you can add to 141 | your Django logging configuration. 142 | -------------------------------------------------------------------------------- /minio_storage/__init__.py: -------------------------------------------------------------------------------- 1 | from minio_storage.storage import MinioMediaStorage, MinioStaticStorage, MinioStorage 2 | 3 | __all__ = [ 4 | "MinioMediaStorage", 5 | "MinioStaticStorage", 6 | "MinioStorage", 7 | ] 8 | -------------------------------------------------------------------------------- /minio_storage/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class DjangoStoragesConfig(AppConfig): 5 | name = "minio_storage" 6 | -------------------------------------------------------------------------------- /minio_storage/errors.py: -------------------------------------------------------------------------------- 1 | import minio.error as merr 2 | 3 | 4 | class MinIOError(OSError): 5 | def __init__(self, msg, cause): 6 | super().__init__(msg) 7 | self.cause = cause 8 | 9 | 10 | reraise = {} 11 | for v in ( 12 | merr.MinioException, 13 | merr.InvalidResponseError, 14 | merr.ServerError, 15 | merr.S3Error, 16 | ): 17 | reraise[v] = {"err": v} 18 | 19 | 20 | def minio_error(msg, e): 21 | if e.__class__ in reraise: 22 | return e 23 | return MinIOError(msg, e) 24 | -------------------------------------------------------------------------------- /minio_storage/files.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import typing as T 3 | from logging import getLogger 4 | 5 | from django.core.files.base import File 6 | from minio import error as merr 7 | 8 | from minio_storage.errors import minio_error 9 | 10 | if T.TYPE_CHECKING: 11 | from minio_storage.storage import MinioStorage 12 | 13 | logger = getLogger("minio_storage") 14 | 15 | 16 | class ReadOnlyMixin: 17 | """File class mixin which disallows .write() calls""" 18 | 19 | def writable(self) -> bool: 20 | return False 21 | 22 | def write(*args, **kwargs): 23 | raise NotImplementedError("this is a read only file") 24 | 25 | 26 | class NonSeekableMixin: 27 | """File class mixin which disallows .seek() calls""" 28 | 29 | def seekable(self) -> bool: 30 | return False 31 | 32 | def seek(self, *args, **kwargs) -> bool: 33 | # TODO: maybe exception is better 34 | # raise NotImplementedError('seek is not supported') 35 | return False 36 | 37 | 38 | class MinioStorageFile(File): 39 | def __init__(self, name: str, mode: str, storage: "MinioStorage", **kwargs): 40 | self._storage: MinioStorage = storage 41 | self.name: str = name # type: ignore[override] 42 | self._mode: str = mode 43 | self._file = None 44 | 45 | def read(self, *args, **kwargs): 46 | if "b" in self._mode: 47 | return super().read(*args, **kwargs) 48 | else: 49 | return super().read(*args, **kwargs).decode() 50 | 51 | def readline(self, *args, **kwargs): 52 | if "b" in self._mode: 53 | return super().readline(*args, **kwargs) 54 | else: 55 | return super().readline(*args, **kwargs).decode() 56 | 57 | def readlines(self, *args, **kwargs): 58 | return list(self) 59 | 60 | 61 | class ReadOnlyMinioObjectFile(MinioStorageFile, ReadOnlyMixin, NonSeekableMixin): 62 | """A django File class which directly exposes the underlying minio object. This 63 | means the the instance doesnt support functions like .seek() and is required to 64 | be closed to be able to reuse minio connections.""" 65 | 66 | def __init__( 67 | self, 68 | name: str, 69 | mode: str, 70 | storage: "MinioStorage", 71 | max_memory_size: T.Optional[int] = None, 72 | **kwargs, 73 | ): 74 | if mode.find("w") > -1: 75 | raise NotImplementedError( 76 | "ReadOnlyMinioObjectFile storage only support read modes" 77 | ) 78 | if max_memory_size is not None: 79 | self.max_memory_size = max_memory_size 80 | super().__init__(name, mode, storage) 81 | 82 | @property 83 | def file(self): 84 | obj = None 85 | if self._file is None: 86 | try: 87 | obj = self._storage.client.get_object( 88 | self._storage.bucket_name, self.name 89 | ) 90 | self._file = obj 91 | return self._file 92 | except merr.InvalidResponseError as error: 93 | logger.warn(error) 94 | raise OSError(f"File {self.name} does not exist") from error 95 | finally: 96 | try: 97 | if obj: 98 | obj.release_conn() 99 | except Exception as e: 100 | logger.error(str(e)) 101 | return self._file 102 | 103 | @file.setter 104 | def file(self, value): # type: ignore[override] 105 | self._file = value 106 | 107 | def close(self): 108 | try: 109 | self.file.close() 110 | finally: 111 | self.file.release_conn() 112 | 113 | 114 | class ReadOnlySpooledTemporaryFile(MinioStorageFile, ReadOnlyMixin): 115 | """A django File class which buffers the minio object into a local 116 | SpooledTemporaryFile.""" 117 | 118 | max_memory_size: int = 10 * 1024 * 1024 119 | 120 | def __init__( 121 | self, 122 | name: str, 123 | mode: str, 124 | storage: "MinioStorage", 125 | max_memory_size: T.Optional[int] = None, 126 | **kwargs, 127 | ): 128 | if mode.find("w") > -1: 129 | raise NotImplementedError( 130 | "ReadOnlySpooledTemporaryFile storage only support read modes" 131 | ) 132 | if max_memory_size is not None: 133 | self.max_memory_size = max_memory_size 134 | super().__init__(name, mode, storage) 135 | 136 | @property 137 | def file(self): 138 | if self._file is None: 139 | obj = None 140 | try: 141 | obj = self._storage.client.get_object( 142 | self._storage.bucket_name, self.name 143 | ) 144 | self._file = tempfile.SpooledTemporaryFile( 145 | max_size=self.max_memory_size 146 | ) 147 | for d in obj.stream(amt=1024 * 1024): 148 | self._file.write(d) 149 | self._file.seek(0) 150 | return self._file 151 | except merr.InvalidResponseError as error: 152 | raise minio_error(f"File {self.name} does not exist", error) from error 153 | finally: 154 | try: 155 | if obj: 156 | obj.release_conn() 157 | except Exception as e: 158 | logger.error(str(e)) 159 | return self._file 160 | 161 | @file.setter 162 | def file(self, value): # type: ignore[override] 163 | self._file = value 164 | 165 | def close(self): 166 | if self._file is not None: 167 | self._file.close() 168 | self._file = None 169 | -------------------------------------------------------------------------------- /minio_storage/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/minio_storage/management/__init__.py -------------------------------------------------------------------------------- /minio_storage/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/minio_storage/management/commands/__init__.py -------------------------------------------------------------------------------- /minio_storage/management/commands/minio.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | import typing as T 4 | from string import Template 5 | from unittest.mock import patch 6 | 7 | import minio.error 8 | from django.core.management.base import BaseCommand, CommandError 9 | from django.utils.module_loading import import_string 10 | 11 | from minio_storage.policy import Policy 12 | from minio_storage.storage import MinioStorage 13 | 14 | 15 | class Command(BaseCommand): 16 | help = "verify, list, create and delete minio buckets" 17 | 18 | CHECK = "check" 19 | CREATE = "create" 20 | DELETE = "delete" 21 | LIST = "ls" 22 | POLICY = "policy" 23 | 24 | FULL_FORMAT = "$name $size $modified $url $etag" 25 | 26 | def add_arguments(self, parser): 27 | group = parser.add_argument_group("minio") 28 | group.add_argument( 29 | "--class", 30 | type=str, 31 | default="minio_storage.MinioMediaStorage", 32 | help="Storage class to modify " 33 | "(media/static are short names for default classes)", 34 | ) 35 | group.add_argument( 36 | "--bucket", 37 | type=str, 38 | default=None, 39 | help="bucket name (default: storage defined bucket if not set)", 40 | ) 41 | 42 | cmds = parser.add_subparsers( 43 | dest="command", 44 | title="subcommands", 45 | description="valid subcommands", 46 | # required=True, 47 | ) 48 | cmds.add_parser(self.CHECK, help="check bucket") 49 | cmds.add_parser(self.CREATE, help="make bucket") 50 | cmds.add_parser(self.DELETE, help="remove an empty bucket") 51 | 52 | ls = cmds.add_parser(self.LIST, help="list bucket objects or buckets") 53 | ls.add_argument("--dirs", action="store_true", help="include directories") 54 | ls.add_argument("--files", action="store_true", help="include files") 55 | ls.add_argument( 56 | "-r", "--recursive", action="store_true", help="find files recursive" 57 | ) 58 | ls.add_argument("-p", "--prefix", type=str, default="", help="path prefix") 59 | ls.add_argument( 60 | "--buckets", action="store_true", help="list buckets instead of files" 61 | ) 62 | ls.add_argument( 63 | "-f", 64 | "--format", 65 | type=str, 66 | default="$name", 67 | help="list format. ( $name $size $modified $url $etag )", 68 | ) 69 | 70 | policy = cmds.add_parser(self.POLICY, help="get or set bucket policy") 71 | policy.add_argument( 72 | "--set", 73 | type=str, 74 | default=None, 75 | choices=[p.value for p in Policy], 76 | help="set bucket policy", 77 | ) 78 | 79 | super().add_arguments(parser) 80 | 81 | def handle(self, *args, **options): 82 | storage = self.storage(options) 83 | bucket_name = options["bucket"] or storage.bucket_name 84 | command = options["command"] or "" 85 | if command == self.CHECK: 86 | return self.bucket_exists(storage, bucket_name) 87 | if command == self.CREATE: 88 | return self.bucket_create(storage, bucket_name) 89 | elif command == self.DELETE: 90 | return self.bucket_delete(storage, bucket_name) 91 | elif command == self.LIST: 92 | if options["buckets"]: 93 | return self.list_buckets(storage) 94 | 95 | list_dirs = True 96 | list_files = True 97 | summary = True 98 | if options["dirs"] or options["files"]: 99 | list_dirs = options["dirs"] 100 | list_files = options["files"] 101 | summary = False 102 | 103 | return self.bucket_list( 104 | storage, 105 | bucket_name, 106 | prefix=options["prefix"], 107 | list_dirs=list_dirs, 108 | list_files=list_files, 109 | recursive=options["recursive"], 110 | format=options["format"], 111 | summary=summary, 112 | ) 113 | elif command == self.POLICY: 114 | if options["set"] is not None: 115 | return self.policy_set( 116 | storage, bucket_name, policy=Policy(options["set"]) 117 | ) 118 | return self.policy_get(storage, bucket_name) 119 | self.print_help("minio", "") 120 | if command != "": 121 | raise CommandError(f"don't know how to handle command: {command}") 122 | raise CommandError("command name required") 123 | 124 | def storage(self, options): 125 | class_name: str = options["class"] 126 | if class_name == "media": 127 | class_name = "minio_storage.MinioMediaStorage" 128 | elif class_name == "static": 129 | class_name = "minio_storage.MinioStaticStorage" 130 | 131 | try: 132 | storage_class = import_string(class_name) 133 | except ImportError as err: 134 | raise CommandError(f"could not find storage class: {class_name}") from err 135 | if not issubclass(storage_class, MinioStorage): 136 | raise CommandError(f"{class_name} is not an sub class of MinioStorage.") 137 | 138 | # TODO: maybe another way 139 | with patch.object(storage_class, "_init_check", return_value=None): 140 | # TODO: This constructor can be missing arguments 141 | storage = storage_class() # pyright: ignore[reportCallIssue] 142 | return storage 143 | 144 | def bucket_exists(self, storage, bucket_name): 145 | exists = storage.client.bucket_exists(bucket_name) 146 | if not exists: 147 | raise CommandError(f"bucket {bucket_name} does not exist") 148 | 149 | def list_buckets(self, storage): 150 | objs = storage.client.list_buckets() 151 | for o in objs: 152 | self.stdout.write(f"{o.name}") 153 | 154 | def bucket_list( 155 | self, 156 | storage, 157 | bucket_name: str, 158 | *, 159 | prefix: str, 160 | list_dirs: bool, 161 | list_files: bool, 162 | recursive: bool, 163 | format: T.Optional[str] = None, 164 | summary: bool = True, 165 | ): 166 | try: 167 | objs = storage.client.list_objects( 168 | bucket_name, prefix=prefix, recursive=recursive 169 | ) 170 | 171 | template = None 172 | if format is not None and format != "$name": 173 | template = Template(format) 174 | 175 | def fmt(o): 176 | if template is None: 177 | return o.object_name 178 | return template.substitute( 179 | name=o.object_name, 180 | size=o.size, 181 | modified=o.last_modified, 182 | etag=o.etag, 183 | url=storage.url(o.object_name), 184 | ) 185 | 186 | n_files = 0 187 | n_dirs = 0 188 | for o in objs: 189 | if o.is_dir: 190 | n_dirs += 1 191 | if list_dirs: 192 | self.stdout.write(fmt(o)) 193 | else: 194 | n_files += 1 195 | if list_files: 196 | self.stdout.write(fmt(o)) 197 | 198 | if summary: 199 | print(f"{n_files} files and {n_dirs} directories", file=sys.stderr) 200 | except minio.error.S3Error as e: 201 | raise CommandError(f"error reading bucket {bucket_name}") from e 202 | 203 | def bucket_create(self, storage, bucket_name): 204 | try: 205 | storage.client.make_bucket(bucket_name) 206 | print(f"created bucket: {bucket_name}", file=sys.stderr) 207 | except minio.error.S3Error as e: 208 | raise CommandError(f"error creating {bucket_name}") from e 209 | return 210 | 211 | def bucket_delete(self, storage, bucket_name): 212 | try: 213 | storage.client.remove_bucket(bucket_name) 214 | except minio.error.S3Error as err: 215 | if err.code == "BucketNotEmpty": 216 | raise CommandError(f"bucket {bucket_name} is not empty") from err 217 | elif err.code == "NoSuchBucket": 218 | raise CommandError(f"bucket {bucket_name} does not exist") from err 219 | 220 | def policy_get(self, storage, bucket_name): 221 | try: 222 | policy = storage.client.get_bucket_policy(bucket_name) 223 | policy = json.loads(policy) 224 | policy = json.dumps(policy, ensure_ascii=False, indent=2) 225 | return policy 226 | except minio.error.S3Error as err: 227 | if err.code == "NoSuchBucket": 228 | raise CommandError(f"bucket {bucket_name} does not exist") from err 229 | elif err.code == "NoSuchBucketPolicy": 230 | raise CommandError(f"bucket {bucket_name} has no policy") from err 231 | 232 | def policy_set(self, storage, bucket_name, policy: Policy): 233 | try: 234 | policy = Policy(policy) 235 | storage.client.set_bucket_policy(bucket_name, policy.bucket(bucket_name)) 236 | except minio.error.S3Error as e: 237 | raise CommandError(e.message) from e 238 | -------------------------------------------------------------------------------- /minio_storage/policy.py: -------------------------------------------------------------------------------- 1 | import enum 2 | import json 3 | import typing as T 4 | 5 | 6 | class Policy(enum.Enum): 7 | none = "NONE" 8 | get = "GET_ONLY" 9 | read = "READ_ONLY" 10 | write = "WRITE_ONLY" 11 | read_write = "READ_WRITE" 12 | 13 | @T.overload 14 | def bucket( 15 | self, bucket_name: str, *, json_encode: T.Literal[True] = ... 16 | ) -> str: ... 17 | 18 | @T.overload 19 | def bucket( 20 | self, bucket_name: str, *, json_encode: T.Literal[False] 21 | ) -> dict[str, T.Any]: ... 22 | 23 | def bucket( 24 | self, bucket_name: str, *, json_encode: bool = True 25 | ) -> T.Union[str, dict[str, T.Any]]: 26 | policies = { 27 | Policy.get: _get, 28 | Policy.read: _read, 29 | Policy.write: _write, 30 | Policy.read_write: _read_write, 31 | Policy.none: _none, 32 | } 33 | pol = policies[self](bucket_name) 34 | if json_encode: 35 | return json.dumps(pol) 36 | return pol 37 | 38 | 39 | def _none(bucket_name: str) -> dict[str, T.Any]: 40 | return {"Version": "2012-10-17", "Statement": []} 41 | 42 | 43 | def _get(bucket_name: str) -> dict[str, T.Any]: 44 | return { 45 | "Version": "2012-10-17", 46 | "Statement": [ 47 | { 48 | "Effect": "Allow", 49 | "Principal": {"AWS": ["*"]}, 50 | "Action": ["s3:GetObject"], 51 | "Resource": [f"arn:aws:s3:::{bucket_name}/*"], 52 | } 53 | ], 54 | } 55 | 56 | 57 | def _read(bucket_name: str) -> dict[str, T.Any]: 58 | return { 59 | "Version": "2012-10-17", 60 | "Statement": [ 61 | { 62 | "Effect": "Allow", 63 | "Principal": {"AWS": ["*"]}, 64 | "Action": ["s3:GetBucketLocation"], 65 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 66 | }, 67 | { 68 | "Effect": "Allow", 69 | "Principal": {"AWS": ["*"]}, 70 | "Action": ["s3:ListBucket"], 71 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 72 | }, 73 | { 74 | "Effect": "Allow", 75 | "Principal": {"AWS": ["*"]}, 76 | "Action": ["s3:GetObject"], 77 | "Resource": [f"arn:aws:s3:::{bucket_name}/*"], 78 | }, 79 | ], 80 | } 81 | 82 | 83 | def _write(bucket_name: str) -> dict[str, T.Any]: 84 | return { 85 | "Version": "2012-10-17", 86 | "Statement": [ 87 | { 88 | "Effect": "Allow", 89 | "Principal": {"AWS": ["*"]}, 90 | "Action": ["s3:GetBucketLocation"], 91 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 92 | }, 93 | { 94 | "Effect": "Allow", 95 | "Principal": {"AWS": ["*"]}, 96 | "Action": ["s3:ListBucketMultipartUploads"], 97 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 98 | }, 99 | { 100 | "Effect": "Allow", 101 | "Principal": {"AWS": ["*"]}, 102 | "Action": [ 103 | "s3:ListMultipartUploadParts", 104 | "s3:AbortMultipartUpload", 105 | "s3:DeleteObject", 106 | "s3:PutObject", 107 | ], 108 | "Resource": [f"arn:aws:s3:::{bucket_name}/*"], 109 | }, 110 | ], 111 | } 112 | 113 | 114 | def _read_write(bucket_name: str) -> dict[str, T.Any]: 115 | return { 116 | "Version": "2012-10-17", 117 | "Statement": [ 118 | { 119 | "Effect": "Allow", 120 | "Principal": {"AWS": ["*"]}, 121 | "Action": ["s3:GetBucketLocation"], 122 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 123 | }, 124 | { 125 | "Effect": "Allow", 126 | "Principal": {"AWS": ["*"]}, 127 | "Action": ["s3:ListBucket"], 128 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 129 | }, 130 | { 131 | "Effect": "Allow", 132 | "Principal": {"AWS": ["*"]}, 133 | "Action": ["s3:ListBucketMultipartUploads"], 134 | "Resource": [f"arn:aws:s3:::{bucket_name}"], 135 | }, 136 | { 137 | "Effect": "Allow", 138 | "Principal": {"AWS": ["*"]}, 139 | "Action": [ 140 | "s3:AbortMultipartUpload", 141 | "s3:DeleteObject", 142 | "s3:GetObject", 143 | "s3:ListMultipartUploadParts", 144 | "s3:PutObject", 145 | ], 146 | "Resource": [f"arn:aws:s3:::{bucket_name}/*"], 147 | }, 148 | ], 149 | } 150 | -------------------------------------------------------------------------------- /minio_storage/py.typed: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /minio_storage/storage.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import mimetypes 3 | import posixpath 4 | import typing as T 5 | from logging import getLogger 6 | from urllib.parse import quote, urlsplit, urlunsplit 7 | 8 | import minio 9 | import minio.error as merr 10 | from django.conf import settings 11 | from django.core.exceptions import ImproperlyConfigured 12 | from django.core.files.storage import Storage 13 | from django.utils import timezone 14 | from django.utils.deconstruct import deconstructible 15 | from minio.datatypes import Object 16 | 17 | from minio_storage.errors import minio_error 18 | from minio_storage.files import MinioStorageFile, ReadOnlySpooledTemporaryFile 19 | from minio_storage.policy import Policy 20 | 21 | logger = getLogger("minio_storage") 22 | 23 | ObjectMetadataType = T.Mapping[str, T.Union[str, list[str], tuple[str]]] 24 | 25 | 26 | @deconstructible 27 | class MinioStorage(Storage): 28 | """An implementation of Django's file storage using the minio client. 29 | 30 | The implementation should comply with 31 | https://docs.djangoproject.com/en/dev/ref/files/storage/. 32 | 33 | """ 34 | 35 | file_class = ReadOnlySpooledTemporaryFile 36 | 37 | def __init__( 38 | self, 39 | minio_client: minio.Minio, 40 | bucket_name: str, 41 | *, 42 | base_url: T.Optional[str] = None, 43 | file_class: T.Optional[type[MinioStorageFile]] = None, 44 | auto_create_bucket: bool = False, 45 | presign_urls: bool = False, 46 | auto_create_policy: bool = False, 47 | policy_type: T.Optional[Policy] = None, 48 | object_metadata: T.Optional[ObjectMetadataType] = None, 49 | backup_format: T.Optional[str] = None, 50 | backup_bucket: T.Optional[str] = None, 51 | assume_bucket_exists: bool = False, 52 | **kwargs, 53 | ): 54 | self.client = minio_client 55 | self.bucket_name = bucket_name 56 | self.base_url = base_url 57 | 58 | self.backup_format = backup_format 59 | self.backup_bucket = backup_bucket 60 | if bool(self.backup_format) != bool(self.backup_bucket): 61 | raise ImproperlyConfigured( 62 | "To enable backups, make sure to set both backup format " 63 | "and backup format" 64 | ) 65 | 66 | if file_class is not None: 67 | self.file_class = file_class 68 | self.auto_create_bucket = auto_create_bucket 69 | self.auto_create_policy = auto_create_policy 70 | self.assume_bucket_exists = assume_bucket_exists 71 | self.policy_type = policy_type 72 | self.presign_urls = presign_urls 73 | self.object_metadata = object_metadata 74 | 75 | self._init_check() 76 | 77 | # A base_url_client is only necessary when using presign_urls 78 | if self.presign_urls and self.base_url: 79 | # Do this after _init_check, so client's bucket region cache will 80 | # already be populated 81 | self.base_url_client = self._create_base_url_client( 82 | self.client, self.bucket_name, self.base_url 83 | ) 84 | 85 | super().__init__() 86 | 87 | def _init_check(self): 88 | if not self.assume_bucket_exists: 89 | if self.auto_create_bucket and not self.client.bucket_exists( 90 | self.bucket_name 91 | ): 92 | self.client.make_bucket(self.bucket_name) 93 | if self.auto_create_policy: 94 | policy_type = self.policy_type 95 | if policy_type is None: 96 | policy_type = Policy.get 97 | self.client.set_bucket_policy( 98 | self.bucket_name, policy_type.bucket(self.bucket_name) 99 | ) 100 | 101 | elif not self.client.bucket_exists(self.bucket_name): 102 | raise OSError(f"The bucket {self.bucket_name} does not exist") 103 | 104 | @staticmethod 105 | def _create_base_url_client(client: minio.Minio, bucket_name: str, base_url: str): 106 | """ 107 | Clone a Minio client, using a different endpoint from `base_url`. 108 | """ 109 | base_url_parts = urlsplit(base_url) 110 | 111 | # Clone from the normal client, but with base_url as the endpoint 112 | base_url_client = minio.Minio( 113 | base_url_parts.netloc, 114 | credentials=client._provider, 115 | secure=base_url_parts.scheme == "https", 116 | # The bucket region may be auto-detected by client (via an HTTP 117 | # request), so don't just use client._region 118 | region=client._get_region(bucket_name), 119 | http_client=client._http, 120 | ) 121 | 122 | return base_url_client 123 | 124 | def _sanitize_path(self, name): 125 | v = posixpath.normpath(name).replace("\\", "/") 126 | if v == ".": 127 | v = "" 128 | if name.endswith("/") and not v.endswith("/"): 129 | v += "/" 130 | return v 131 | 132 | def _examine_file(self, name, content): 133 | """Examines a file and produces information necessary for upload. 134 | 135 | Returns a tuple of the form (content_size, content_type, 136 | sanitized_name) 137 | 138 | """ 139 | content_size = content.size 140 | content_type = mimetypes.guess_type(name, strict=False) 141 | content_type = content_type[0] or "application/octet-stream" 142 | sane_name = self._sanitize_path(name) 143 | return (content_size, content_type, sane_name) 144 | 145 | def _open(self, name: str, mode: str = "rb") -> MinioStorageFile: 146 | try: 147 | f = self.file_class(self._sanitize_path(name), mode, self) 148 | except merr.MinioException as e: 149 | raise minio_error(f"File {name} could not be saved: {e!s}", e) from e 150 | return f 151 | 152 | def _save(self, name: str, content: T.BinaryIO) -> str: 153 | try: 154 | if hasattr(content, "seek") and callable(content.seek): 155 | content.seek(0) 156 | content_size, content_type, sane_name = self._examine_file(name, content) 157 | self.client.put_object( 158 | self.bucket_name, 159 | sane_name, 160 | content, 161 | content_size, 162 | content_type, 163 | # Minio is annotated to expect a Dict, rather than a Mapping; we 164 | # annotate this type as Mapping, since only Mapping is covariant, which 165 | # is more friendly to users. 166 | metadata=self.object_metadata, # type: ignore[arg-type] 167 | ) 168 | return sane_name 169 | except merr.InvalidResponseError as error: 170 | raise minio_error(f"File {name} could not be saved", error) from error 171 | 172 | def delete(self, name: str) -> None: 173 | if self.backup_format and self.backup_bucket: 174 | try: 175 | obj = self.client.get_object(self.bucket_name, name) 176 | except merr.InvalidResponseError as error: 177 | raise minio_error( 178 | f"Could not obtain file {name} to make a copy of it", 179 | error, 180 | ) from error 181 | 182 | try: 183 | content_length = int(obj.headers.get("Content-Length", "")) 184 | except ValueError as error: 185 | raise minio_error( 186 | f"Could not backup removed file {name}", error 187 | ) from error 188 | 189 | # Creates the backup filename 190 | target_name = f"{timezone.now().strftime(self.backup_format)}{name}" 191 | try: 192 | self.client.put_object( 193 | self.backup_bucket, 194 | target_name, 195 | # This is expected to be a BinaryIO, but the actual 196 | # BaseHTTPResponse "obj" still provides ".read() -> bytes". 197 | obj, # type: ignore[arg-type] 198 | content_length, 199 | ) 200 | except merr.InvalidResponseError as error: 201 | raise minio_error( 202 | f"Could not make a copy of file {name} before removing it", 203 | error, 204 | ) from error 205 | 206 | try: 207 | self.client.remove_object(self.bucket_name, name) 208 | except merr.InvalidResponseError as error: 209 | raise minio_error(f"Could not remove file {name}", error) from error 210 | 211 | def exists(self, name: str) -> bool: 212 | try: 213 | self.client.stat_object(self.bucket_name, self._sanitize_path(name)) 214 | return True 215 | except merr.InvalidResponseError as error: 216 | # TODO - deprecate 217 | if error._code == "NoSuchKey": 218 | return False 219 | else: 220 | raise minio_error(f"Could not stat file {name}", error) from error 221 | except merr.S3Error: 222 | return False 223 | except Exception as error: 224 | logger.error(error) 225 | return False 226 | 227 | def listdir(self, path: str) -> tuple[list, list]: 228 | # [None, "", "."] is supported to mean the configured root among various 229 | # implementations of Storage implementations so we copy that behaviour even if 230 | # maybe None should raise an exception instead. 231 | # 232 | # If the path prefix does not match anything full prefix that does exist this 233 | # function will just return empty results, this is different from 234 | # FileSystemStorage where an invalid directory would raise an OSError. 235 | 236 | if path in [None, "", ".", "/"]: 237 | path = "" 238 | else: 239 | if not path.endswith("/"): 240 | path += "/" 241 | 242 | dirs: list[str] = [] 243 | files: list[str] = [] 244 | try: 245 | objects = self.client.list_objects(self.bucket_name, prefix=path) 246 | for o in objects: 247 | assert o.object_name is not None 248 | p = posixpath.relpath(o.object_name, path) 249 | if o.is_dir: 250 | dirs.append(p) 251 | else: 252 | files.append(p) 253 | return dirs, files 254 | except merr.S3Error: 255 | raise 256 | except merr.InvalidResponseError as error: 257 | raise minio_error(f"Could not list directory {path}", error) from error 258 | 259 | def size(self, name: str) -> int: 260 | try: 261 | info: Object = self.client.stat_object(self.bucket_name, name) 262 | except merr.InvalidResponseError as error: 263 | raise minio_error( 264 | f"Could not access file size for {name}", error 265 | ) from error 266 | assert info.size is not None 267 | return info.size 268 | 269 | def _presigned_url( 270 | self, name: str, max_age: T.Optional[datetime.timedelta] = None 271 | ) -> T.Optional[str]: 272 | kwargs = {} 273 | if max_age is not None: 274 | kwargs["expires"] = max_age 275 | 276 | client = self.client if self.base_url is None else self.base_url_client 277 | url = client.presigned_get_object(self.bucket_name, name, **kwargs) 278 | 279 | if self.base_url is not None: 280 | url_parts = urlsplit(url) 281 | base_url_parts = urlsplit(self.base_url) 282 | 283 | # It's assumed that self.base_url will contain bucket information, 284 | # which could be different, so remove the bucket_name component (with 1 285 | # extra character for the leading "/") from the generated URL 286 | url_key_path = url_parts.path[len(self.bucket_name) + 1 :] # noqa: E203 287 | 288 | # Prefix the URL with any path content from base_url 289 | new_url_path = base_url_parts.path + url_key_path 290 | 291 | # Reconstruct the URL with an updated path 292 | url = urlunsplit( 293 | ( 294 | url_parts.scheme, 295 | url_parts.netloc, 296 | new_url_path, 297 | url_parts.query, 298 | url_parts.fragment, 299 | ) 300 | ) 301 | if url: 302 | return str(url) 303 | return None 304 | 305 | # Django allows "name" to be None, but types should indicate that this is disallowed 306 | @T.overload 307 | def url( 308 | self, name: None, *, max_age: T.Optional[datetime.timedelta] = ... 309 | ) -> T.NoReturn: ... 310 | 311 | @T.overload 312 | def url( 313 | self, name: str, *, max_age: T.Optional[datetime.timedelta] = ... 314 | ) -> str: ... 315 | 316 | def url( 317 | self, name: T.Optional[str], *, max_age: T.Optional[datetime.timedelta] = None 318 | ) -> str: 319 | if name is None: 320 | raise ValueError("name may not be None") 321 | url = "" 322 | if self.presign_urls: 323 | url = self._presigned_url(name, max_age=max_age) 324 | else: 325 | 326 | def strip_beg(path): 327 | while path.startswith("/"): 328 | path = path[1:] 329 | return path 330 | 331 | def strip_end(path): 332 | while path.endswith("/"): 333 | path = path[:-1] 334 | return path 335 | 336 | if self.base_url is not None: 337 | url = f"{strip_end(self.base_url)}/{quote(strip_beg(name))}" 338 | else: 339 | url = ( 340 | f"{strip_end(self.endpoint_url)}/{self.bucket_name}/" 341 | f"{quote(strip_beg(name))}" 342 | ) 343 | if url: 344 | return url 345 | raise OSError(f"could not produce URL for {name}") 346 | 347 | @property 348 | def endpoint_url(self): 349 | return self.client._base_url._url.geturl() 350 | 351 | def accessed_time(self, name: str) -> datetime.datetime: 352 | """ 353 | Not available via the S3 API 354 | """ 355 | return self.modified_time(name) 356 | 357 | def created_time(self, name: str) -> datetime.datetime: 358 | """ 359 | Not available via the S3 API 360 | """ 361 | return self.modified_time(name) 362 | 363 | def modified_time(self, name: str) -> datetime.datetime: 364 | try: 365 | info: Object = self.client.stat_object(self.bucket_name, name) 366 | except merr.InvalidResponseError as error: 367 | raise minio_error( 368 | f"Could not access modification time for file {name}", error 369 | ) from error 370 | if info.last_modified is None: 371 | raise OSError(f"Could not access modification time for file {name}") 372 | return info.last_modified 373 | 374 | 375 | _NoValue = object() 376 | 377 | 378 | def get_setting(name: str, default=_NoValue) -> T.Any: 379 | result = getattr(settings, name, default) 380 | if result is _NoValue: 381 | # print("Attr {} : {}".format(name, getattr(settings, name, default))) 382 | raise ImproperlyConfigured 383 | else: 384 | return result 385 | 386 | 387 | def create_minio_client_from_settings(*, minio_kwargs=None): 388 | endpoint = get_setting("MINIO_STORAGE_ENDPOINT") 389 | kwargs = { 390 | "access_key": get_setting("MINIO_STORAGE_ACCESS_KEY"), 391 | "secret_key": get_setting("MINIO_STORAGE_SECRET_KEY"), 392 | "secure": get_setting("MINIO_STORAGE_USE_HTTPS", True), 393 | } 394 | region = get_setting("MINIO_STORAGE_REGION", None) 395 | if region: 396 | kwargs["region"] = region 397 | 398 | if minio_kwargs: 399 | kwargs.update(minio_kwargs) 400 | 401 | # Making this client deconstructible allows it to be passed directly as 402 | # an argument to MinioStorage, since Django needs to be able to 403 | # deconstruct all Storage constructor arguments for Storages referenced in 404 | # migrations (e.g. when using a custom storage on a FileField). 405 | client = deconstructible(minio.Minio)( 406 | endpoint, 407 | **kwargs, 408 | ) 409 | return client 410 | 411 | 412 | @deconstructible 413 | class MinioMediaStorage(MinioStorage): 414 | def __init__( # noqa: C901 415 | self, 416 | *, 417 | minio_client: T.Optional[minio.Minio] = None, 418 | bucket_name: T.Optional[str] = None, 419 | base_url: T.Optional[str] = None, 420 | file_class: T.Optional[type[MinioStorageFile]] = None, 421 | auto_create_bucket: T.Optional[bool] = None, 422 | presign_urls: T.Optional[bool] = None, 423 | auto_create_policy: T.Optional[bool] = None, 424 | policy_type: T.Optional[Policy] = None, 425 | object_metadata: T.Optional[ObjectMetadataType] = None, 426 | backup_format: T.Optional[str] = None, 427 | backup_bucket: T.Optional[str] = None, 428 | assume_bucket_exists: T.Optional[bool] = None, 429 | ): 430 | if minio_client is None: 431 | minio_client = create_minio_client_from_settings() 432 | if bucket_name is None: 433 | bucket_name = get_setting("MINIO_STORAGE_MEDIA_BUCKET_NAME") 434 | assert bucket_name is not None 435 | if base_url is None: 436 | base_url = get_setting("MINIO_STORAGE_MEDIA_URL", None) 437 | if auto_create_bucket is None: 438 | auto_create_bucket = get_setting( 439 | "MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET", False 440 | ) 441 | assert auto_create_bucket is not None 442 | if presign_urls is None: 443 | presign_urls = get_setting("MINIO_STORAGE_MEDIA_USE_PRESIGNED", False) 444 | assert presign_urls is not None 445 | auto_create_policy_setting = get_setting( 446 | "MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY", "GET_ONLY" 447 | ) 448 | if auto_create_policy is None: 449 | auto_create_policy = ( 450 | True 451 | if isinstance(auto_create_policy_setting, str) 452 | else auto_create_policy_setting 453 | ) 454 | assert auto_create_policy is not None 455 | if policy_type is None: 456 | policy_type = ( 457 | Policy(auto_create_policy_setting) 458 | if isinstance(auto_create_policy_setting, str) 459 | else Policy.get 460 | ) 461 | assert policy_type is not None 462 | if object_metadata is None: 463 | object_metadata = get_setting("MINIO_STORAGE_MEDIA_OBJECT_METADATA", None) 464 | if backup_format is None: 465 | backup_format = get_setting("MINIO_STORAGE_MEDIA_BACKUP_FORMAT", None) 466 | if backup_bucket is None: 467 | backup_bucket = get_setting("MINIO_STORAGE_MEDIA_BACKUP_BUCKET", None) 468 | if assume_bucket_exists is None: 469 | assume_bucket_exists = get_setting( 470 | "MINIO_STORAGE_ASSUME_MEDIA_BUCKET_EXISTS", False 471 | ) 472 | assert assume_bucket_exists is not None 473 | 474 | super().__init__( 475 | minio_client, 476 | bucket_name, 477 | base_url=base_url, 478 | file_class=file_class, 479 | auto_create_bucket=auto_create_bucket, 480 | presign_urls=presign_urls, 481 | auto_create_policy=auto_create_policy, 482 | policy_type=policy_type, 483 | object_metadata=object_metadata, 484 | backup_format=backup_format, 485 | backup_bucket=backup_bucket, 486 | assume_bucket_exists=assume_bucket_exists, 487 | ) 488 | 489 | 490 | @deconstructible 491 | class MinioStaticStorage(MinioStorage): 492 | def __init__( 493 | self, 494 | *, 495 | minio_client: T.Optional[minio.Minio] = None, 496 | bucket_name: T.Optional[str] = None, 497 | base_url: T.Optional[str] = None, 498 | file_class: T.Optional[type[MinioStorageFile]] = None, 499 | auto_create_bucket: T.Optional[bool] = None, 500 | presign_urls: T.Optional[bool] = None, 501 | auto_create_policy: T.Optional[bool] = None, 502 | policy_type: T.Optional[Policy] = None, 503 | object_metadata: T.Optional[ObjectMetadataType] = None, 504 | assume_bucket_exists: T.Optional[bool] = None, 505 | ): 506 | if minio_client is None: 507 | minio_client = create_minio_client_from_settings() 508 | if bucket_name is None: 509 | bucket_name = get_setting("MINIO_STORAGE_STATIC_BUCKET_NAME") 510 | assert bucket_name is not None 511 | if base_url is None: 512 | base_url = get_setting("MINIO_STORAGE_STATIC_URL", None) 513 | if auto_create_bucket is None: 514 | auto_create_bucket = get_setting( 515 | "MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET", False 516 | ) 517 | assert auto_create_bucket is not None 518 | if presign_urls is None: 519 | presign_urls = get_setting("MINIO_STORAGE_STATIC_USE_PRESIGNED", False) 520 | assert presign_urls is not None 521 | auto_create_policy_setting = get_setting( 522 | "MINIO_STORAGE_AUTO_CREATE_STATIC_POLICY", "GET_ONLY" 523 | ) 524 | if auto_create_policy is None: 525 | auto_create_policy = ( 526 | True 527 | if isinstance(auto_create_policy_setting, str) 528 | else auto_create_policy_setting 529 | ) 530 | assert auto_create_policy is not None 531 | if policy_type is None: 532 | policy_type = ( 533 | Policy(auto_create_policy_setting) 534 | if isinstance(auto_create_policy_setting, str) 535 | else Policy.get 536 | ) 537 | assert policy_type is not None 538 | if object_metadata is None: 539 | object_metadata = get_setting("MINIO_STORAGE_STATIC_OBJECT_METADATA", None) 540 | if assume_bucket_exists is None: 541 | assume_bucket_exists = get_setting( 542 | "MINIO_STORAGE_ASSUME_STATIC_BUCKET_EXISTS", False 543 | ) 544 | assert assume_bucket_exists is not None 545 | 546 | super().__init__( 547 | minio_client, 548 | bucket_name, 549 | base_url=base_url, 550 | file_class=file_class, 551 | auto_create_bucket=auto_create_bucket, 552 | presign_urls=presign_urls, 553 | auto_create_policy=auto_create_policy, 554 | policy_type=policy_type, 555 | object_metadata=object_metadata, 556 | # backup_format and backup_bucket are not valid for static storage 557 | assume_bucket_exists=assume_bucket_exists, 558 | ) 559 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: django-minio-storage 2 | theme: readthedocs 3 | nav: 4 | - Home: index.md 5 | - Usage: usage.md 6 | - Development: development.md 7 | - Contributing: contributing.md 8 | - Licences: licences.md 9 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "django-minio-storage" 3 | description = "Django file storage using the minio python client" 4 | license = "MIT OR Apache-2.0" 5 | license-files = ["LICENSE", "LICENSE-APACHE"] 6 | requires-python = ">=3.9" 7 | dependencies = [ 8 | "django>=4.2", 9 | "minio>=7.1.16", 10 | ] 11 | classifiers=[ 12 | "Development Status :: 4 - Beta", 13 | "Environment :: Web Environment", 14 | "Intended Audience :: Developers", 15 | "Operating System :: OS Independent", 16 | "Programming Language :: Python", 17 | "Programming Language :: Python :: 3", 18 | "Framework :: Django", 19 | ] 20 | authors = [ 21 | {name = "Thomas Frössman", email = "thomasf@jossystem.se"}, 22 | {name = "Tom Houlé", email = "tom@kafunsho.be"}, 23 | ] 24 | maintainers = [ 25 | {name = "Thomas Frössman", email = "thomasf@jossystem.se"}, 26 | ] 27 | readme = "README.md" 28 | dynamic = ["version"] 29 | 30 | [build-system] 31 | requires = ["setuptools>=77.0.3", "setuptools_scm[toml]>=6.2"] 32 | 33 | [project.urls] 34 | Homepage = "https://github.com/py-pa/django-minio-storage" 35 | Repository = "https://github.com/py-pa/django-minio-storage" 36 | Documentation = "https://django-minio-storage.readthedocs.io/" 37 | 38 | [tool.setuptools_scm] 39 | write_to = "minio_storage/version.py" 40 | write_to_template = '__version__ = "{version}"' 41 | tag_regex = "^v(?Pv)?(?P[^\\+]+)(?P.*)?$" 42 | 43 | [tool.ruff] 44 | target-version = "py39" 45 | line-length = 88 46 | 47 | [tool.ruff.lint] 48 | select = [ 49 | "B", 50 | "C4", 51 | "C9", 52 | "DJ", 53 | "E", 54 | "F", 55 | "I", 56 | "ISC", 57 | "NPY", 58 | "PLC", 59 | "PLE", 60 | "PLW", 61 | "RUF010", 62 | "RUF013", 63 | "S5", 64 | "S6", 65 | "UP", 66 | "W", 67 | ] 68 | ignore = ["E203"] 69 | 70 | [tool.pytest.ini_options] 71 | pythonpath = [".", "tests"] 72 | addopts = ["--tb=short"] 73 | python_files = ["tests.py", "test_*.py", "*_tests.py"] 74 | django_find_project = false 75 | DJANGO_SETTINGS_MODULE = "django_minio_storage_tests.settings" 76 | -------------------------------------------------------------------------------- /pyrightconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": [ 3 | "minio_storage", 4 | "tests" 5 | ], 6 | "exclude": [ 7 | "**/migrations" 8 | ], 9 | "reportMissingImports": true, 10 | "reportMissingTypeStubs": false, 11 | "strictParameterNoneValue": true, 12 | "reportInvalidStringEscapeSequence": "error", 13 | "reportUnboundVariable": "error", 14 | "reportOptionalMemberAccess": "error", 15 | "reportOptionalIterable": "error", 16 | "pythonVersion": "3.9", 17 | "pythonPlatform": "Linux" 18 | } 19 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [options] 2 | packages = find: 3 | 4 | 5 | [options.packages.find] 6 | include = 7 | minio_storage 8 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() 4 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/tests/__init__.py -------------------------------------------------------------------------------- /tests/django_minio_storage_tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/tests/django_minio_storage_tests/__init__.py -------------------------------------------------------------------------------- /tests/django_minio_storage_tests/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_minio_storage_tests project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.9.7. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.9/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | from tests.test_app.tests.utils import bucket_name 16 | 17 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 18 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = "fbkujk%qi0!g$xcz#jah-@#(m%yen^z0dpdatz7hw*=k+&ezgj" 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = True 29 | 30 | ALLOWED_HOSTS = [] 31 | 32 | STORAGES = { 33 | "default": { 34 | "BACKEND": "minio_storage.MinioMediaStorage", 35 | }, 36 | "staticfiles": { 37 | "BACKEND": "minio_storage.MinioStaticStorage", 38 | }, 39 | } 40 | 41 | MINIO_STORAGE_ENDPOINT = os.getenv("MINIO_STORAGE_ENDPOINT", "minio:9000") 42 | MINIO_STORAGE_ACCESS_KEY = os.environ["MINIO_STORAGE_ACCESS_KEY"] 43 | MINIO_STORAGE_SECRET_KEY = os.environ["MINIO_STORAGE_SECRET_KEY"] 44 | MINIO_STORAGE_MEDIA_BUCKET_NAME = bucket_name("tests-media") 45 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET = True 46 | MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET = True 47 | MINIO_STORAGE_STATIC_BUCKET_NAME = bucket_name("tests-static") 48 | MINIO_STORAGE_USE_HTTPS = False 49 | 50 | MINIO_STORAGE_MEDIA_URL = "http://{}/{}".format( 51 | MINIO_STORAGE_ENDPOINT, bucket_name("tests-media") 52 | ) 53 | # MINIO_STATIC_URL = 'http://localhost:9000/{}'.format( 54 | # bucket_name("tests-static")) 55 | 56 | # MINIO_STORAGE_MEDIA_USE_PRESIGNED = True 57 | # MINIO_STORAGE_STATIC_USE_PRESIGNED = True 58 | 59 | # Application definition 60 | 61 | INSTALLED_APPS = [ 62 | "django.contrib.admin", 63 | "django.contrib.auth", 64 | "django.contrib.contenttypes", 65 | "django.contrib.sessions", 66 | "django.contrib.messages", 67 | "django.contrib.staticfiles", 68 | "minio_storage", 69 | "test_app", 70 | ] 71 | 72 | MIDDLEWARE_CLASSES = [ 73 | "django.middleware.security.SecurityMiddleware", 74 | "django.contrib.sessions.middleware.SessionMiddleware", 75 | "django.middleware.common.CommonMiddleware", 76 | "django.middleware.csrf.CsrfViewMiddleware", 77 | "django.contrib.auth.middleware.AuthenticationMiddleware", 78 | "django.contrib.auth.middleware.SessionAuthenticationMiddleware", 79 | "django.contrib.messages.middleware.MessageMiddleware", 80 | "django.middleware.clickjacking.XFrameOptionsMiddleware", 81 | ] 82 | 83 | ROOT_URLCONF = "django_minio_storage_tests.urls" 84 | 85 | TEMPLATES = [ 86 | { 87 | "BACKEND": "django.template.backends.django.DjangoTemplates", 88 | "DIRS": [], 89 | "APP_DIRS": True, 90 | "OPTIONS": { 91 | "context_processors": [ 92 | "django.template.context_processors.debug", 93 | "django.template.context_processors.request", 94 | "django.contrib.auth.context_processors.auth", 95 | "django.contrib.messages.context_processors.messages", 96 | ] 97 | }, 98 | } 99 | ] 100 | 101 | WSGI_APPLICATION = "django_minio_storage_tests.wsgi.application" 102 | 103 | 104 | # Database 105 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 106 | 107 | DATABASES = { 108 | "default": { 109 | "ENGINE": "django.db.backends.sqlite3", 110 | "NAME": os.path.join(BASE_DIR, "db.sqlite3"), 111 | } 112 | } 113 | 114 | 115 | # Password validation 116 | # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators 117 | 118 | AUTH_PASSWORD_VALIDATORS = [ 119 | { 120 | "NAME": "django.contrib.auth.password_validation" 121 | ".UserAttributeSimilarityValidator" 122 | }, 123 | {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"}, 124 | {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"}, 125 | {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, 126 | ] 127 | 128 | 129 | # Internationalization 130 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 131 | 132 | LANGUAGE_CODE = "en-us" 133 | 134 | TIME_ZONE = "UTC" 135 | 136 | USE_I18N = True 137 | 138 | USE_TZ = True 139 | 140 | 141 | # Static files (CSS, JavaScript, Images) 142 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 143 | 144 | STATIC_URL = "/static/" 145 | -------------------------------------------------------------------------------- /tests/django_minio_storage_tests/urls.py: -------------------------------------------------------------------------------- 1 | """django_minio_storage_tests URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.9/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | 17 | from django.contrib import admin 18 | from django.urls import path 19 | 20 | urlpatterns = [path("admin/", admin.site.urls)] 21 | -------------------------------------------------------------------------------- /tests/django_minio_storage_tests/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_minio_storage_tests project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_minio_storage_tests.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /tests/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault( 7 | "DJANGO_SETTINGS_MODULE", "django_minio_storage_tests.settings" 8 | ) 9 | 10 | from django.core.management import execute_from_command_line 11 | 12 | execute_from_command_line(sys.argv) 13 | -------------------------------------------------------------------------------- /tests/test_app/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/tests/test_app/__init__.py -------------------------------------------------------------------------------- /tests/test_app/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/tests/test_app/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_app/tests/bucket_tests.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | import minio 4 | import requests 5 | from django.core.exceptions import ImproperlyConfigured 6 | from django.core.files.base import ContentFile 7 | from django.test import TestCase, override_settings 8 | 9 | from minio_storage.policy import Policy 10 | from minio_storage.storage import MinioMediaStorage, MinioStaticStorage, get_setting 11 | 12 | from .utils import BaseTestMixin 13 | 14 | 15 | class BucketTests(BaseTestMixin, TestCase): 16 | @override_settings( 17 | MINIO_STORAGE_MEDIA_BUCKET_NAME="inexistent", 18 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=False, 19 | ) 20 | def test_media_storage_cannot_be_initialized_without_bucket(self): 21 | with self.assertRaises(OSError): 22 | MinioMediaStorage() 23 | 24 | @override_settings( 25 | MINIO_STORAGE_STATIC_BUCKET_NAME="inexistent", 26 | MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET=False, 27 | ) 28 | def test_static_storage_cannot_be_initialized_without_bucket(self): 29 | with self.assertRaises(OSError): 30 | MinioStaticStorage() 31 | 32 | def test_get_setting_raises_exception(self): 33 | with self.assertRaises(ImproperlyConfigured): 34 | get_setting("INEXISTENT_SETTING") 35 | 36 | @override_settings( 37 | MINIO_STORAGE_MEDIA_BUCKET_NAME="inexistent", 38 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=False, 39 | MINIO_STORAGE_ASSUME_MEDIA_BUCKET_EXISTS=True, 40 | ) 41 | def test_media_storage_ignore_bucket_check(self): 42 | MinioMediaStorage() 43 | 44 | @override_settings( 45 | MINIO_STORAGE_STATIC_BUCKET_NAME="inexistent", 46 | MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET=False, 47 | MINIO_STORAGE_ASSUME_STATIC_BUCKET_EXISTS=True, 48 | ) 49 | def test_static_storage_ignore_bucket_check(self): 50 | MinioStaticStorage() 51 | 52 | 53 | class BucketPolicyTests(BaseTestMixin, TestCase): 54 | def setUp(self): 55 | pass 56 | 57 | def tearDown(self): 58 | self.obliterate_bucket(self.bucket_name("tests-media")) 59 | 60 | def assertPolicyEqual(self, first, second): 61 | """A stupid method to compare policies which is enough for this test""" 62 | 63 | def comparable(v): 64 | return sorted(json.dumps(v)) 65 | 66 | def pretty(v): 67 | return json.dumps(v, sort_keys=True, indent=2) 68 | 69 | if comparable(first) != comparable(second): 70 | raise ValueError( 71 | f"not equal:\n\n ------{pretty(first)}\n\n ------{pretty(second)}" 72 | ) 73 | 74 | @override_settings( 75 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 76 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY=False, 77 | ) 78 | def test_auto_create_no_policy(self): 79 | ms = MinioMediaStorage() 80 | with self.assertRaises(minio.error.S3Error): 81 | ms.client.get_bucket_policy(ms.bucket_name) 82 | 83 | @override_settings( 84 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY=True, 85 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 86 | ) 87 | def test_media_policy_auto_true(self): 88 | ms = MinioMediaStorage() 89 | self.maxDiff = 50000 90 | self.assertPolicyEqual( 91 | Policy.get.bucket(ms.bucket_name, json_encode=False), 92 | json.loads(ms.client.get_bucket_policy(ms.bucket_name)), 93 | ) 94 | fn = ms.save("somefile", ContentFile(b"test")) 95 | self.assertEqual(ms.open(fn).read(), b"test") 96 | url = ms.url(fn) 97 | self.assertEqual(requests.get(url).status_code, 200) 98 | self.assertEqual( 99 | requests.get(f"{ms.endpoint_url}/{ms.bucket_name}").status_code, 403 100 | ) 101 | 102 | @override_settings( 103 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY="GET_ONLY", 104 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 105 | ) 106 | def test_media_policy_get(self): 107 | ms = MinioMediaStorage() 108 | self.maxDiff = 50000 109 | self.assertPolicyEqual( 110 | Policy.get.bucket(ms.bucket_name, json_encode=False), 111 | json.loads(ms.client.get_bucket_policy(ms.bucket_name)), 112 | ) 113 | fn = ms.save("somefile", ContentFile(b"test")) 114 | self.assertEqual(ms.open(fn).read(), b"test") 115 | self.assertEqual(requests.get(ms.url(fn)).status_code, 200) 116 | self.assertEqual( 117 | requests.get(f"{ms.endpoint_url}/{ms.bucket_name}").status_code, 403 118 | ) 119 | 120 | @override_settings( 121 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY="WRITE_ONLY", 122 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 123 | ) 124 | def test_media_policy_write(self): 125 | ms = MinioMediaStorage() 126 | self.maxDiff = 50000 127 | self.assertPolicyEqual( 128 | Policy.write.bucket(ms.bucket_name, json_encode=False), 129 | json.loads(ms.client.get_bucket_policy(ms.bucket_name)), 130 | ) 131 | fn = ms.save("somefile", ContentFile(b"test")) 132 | self.assertEqual(ms.open(fn).read(), b"test") 133 | self.assertEqual(requests.get(ms.url(fn)).status_code, 403) 134 | self.assertEqual( 135 | requests.get(f"{ms.endpoint_url}/{ms.bucket_name}").status_code, 403 136 | ) 137 | 138 | @override_settings( 139 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY="READ_WRITE", 140 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 141 | ) 142 | def test_media_policy_rw(self): 143 | ms = MinioMediaStorage() 144 | self.maxDiff = 50000 145 | self.assertPolicyEqual( 146 | Policy.read_write.bucket(ms.bucket_name, json_encode=False), 147 | json.loads(ms.client.get_bucket_policy(ms.bucket_name)), 148 | ) 149 | 150 | @override_settings( 151 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY=True, 152 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=True, 153 | MINIO_STORAGE_AUTO_CREATE_STATIC_POLICY=True, 154 | MINIO_STORAGE_AUTO_CREATE_STATIC_BUCKET=True, 155 | ) 156 | def test_public_url_generation(self): 157 | media_storage = MinioMediaStorage() 158 | media_test_file_name = media_storage.save( 159 | "weird & ÜRΛ", ContentFile(b"irrelevant") 160 | ) 161 | url = media_storage.url(media_test_file_name) 162 | res = requests.get(url) 163 | self.assertEqual(res.content, b"irrelevant") 164 | 165 | static_storage = MinioStaticStorage() 166 | static_test_file_name = static_storage.save( 167 | "weird & ÜRΛ", ContentFile(b"irrelevant") 168 | ) 169 | url = static_storage.url(static_test_file_name) 170 | res = requests.get(url) 171 | self.assertEqual(res.content, b"irrelevant") 172 | -------------------------------------------------------------------------------- /tests/test_app/tests/custom_storage_class_tests.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | import shutil 4 | import tempfile 5 | 6 | from django.core.files.base import ContentFile 7 | from django.test import TestCase, override_settings 8 | from django.utils.deconstruct import deconstructible 9 | 10 | from minio_storage.files import ReadOnlyMinioObjectFile 11 | from minio_storage.storage import ( 12 | MinioStorage, 13 | create_minio_client_from_settings, 14 | get_setting, 15 | ) 16 | 17 | from .utils import BaseTestMixin 18 | from .utils import bucket_name as create_test_bucket_name 19 | 20 | 21 | @deconstructible 22 | class PrivateStorage(MinioStorage): 23 | """The PrivateStorage MinioStorage subclass can be used directly, as a storage in 24 | settings.STORAGES or after instantiated used individually on any django 25 | FileField: 26 | 27 | from django.db import models 28 | 29 | private_storage = PrivateStorage(bucket_name='invoices') 30 | 31 | class Invoice(models.Model): 32 | ... 33 | pdf = models.FileField(storage=private_storage) 34 | 35 | """ 36 | 37 | # We can set a new default File class implementation that will be used here because 38 | # we want to stream the data directly from minio. Imagine that we need to process 39 | # large files where we don't want to waste time/ram/disk space on writing the file 40 | # to disk two times before processing it. 41 | # 42 | file_class = ReadOnlyMinioObjectFile 43 | 44 | def __init__(self, bucket_name=None): 45 | # we can create the minio client ourselves or use 46 | # create_minio_client_from_settings convinience function while providing it with 47 | # extra args. 48 | # 49 | client = create_minio_client_from_settings(minio_kwargs={"region": "us-east-1"}) 50 | 51 | # or use our own Django setting 52 | # 53 | if bucket_name is None: 54 | bucket_name = get_setting("PRIVATE_BUCKET_NAME") 55 | 56 | # Run the super constructor and make a choice to only use presigned urls with 57 | # this bucket so that we can keep files more private here than how media files 58 | # usually are public readable. 59 | # 60 | super().__init__( 61 | client, 62 | bucket_name, 63 | auto_create_bucket=True, 64 | auto_create_policy=False, 65 | presign_urls=True, 66 | ) 67 | 68 | 69 | class CustomStorageTests(BaseTestMixin, TestCase): 70 | @override_settings(PRIVATE_BUCKET_NAME=create_test_bucket_name("my-private-bucket")) 71 | def test_custom_storage(self): 72 | # Instansiate a storage class and put a file in it so that we have something to 73 | # work with. 74 | # 75 | storage = PrivateStorage() 76 | storage_filename = storage.save("secret.txt", ContentFile(b"abcd")) 77 | 78 | # Create a temporary workspace directory. 79 | # 80 | # It's importat that this directory is deleted after we are done so we use the 81 | # with statement here. 82 | # 83 | with tempfile.TemporaryDirectory() as workspace: 84 | # A filename to use for the file inside the working directory. 85 | # 86 | filename = os.path.join(workspace, "secret.txt") 87 | 88 | # Open a stream with the minio file objenct and the temporary file. 89 | # 90 | # We might be processing a lot of files in a loop here so we are going top 91 | # use the with statement to ensure that both the input stream and output 92 | # files are closed after the copying is done. 93 | # 94 | with ( 95 | open(filename, "wb") as out_file, 96 | storage.open(storage_filename) as storage_file, 97 | ): 98 | # Copy the stream from the http stream to the out_file 99 | # 100 | assert storage_file.file 101 | shutil.copyfileobj(storage_file.file, out_file) 102 | 103 | # 104 | # We are not using the ReadOnlyMinioObjectFile type so we can't seek in 105 | # it. 106 | # 107 | with self.assertRaises(io.UnsupportedOperation): 108 | if storage_file.file: 109 | storage_file.file.seek(0) 110 | 111 | workspace_files = os.listdir(workspace) 112 | print(workspace_files) # prints: ['secret.txt'] 113 | 114 | # 115 | # Process the file with external tools or something.... 116 | # 117 | # For the purpouse of the example test we just check that the contents of 118 | # the file is what we wrote in the beginning of the test. 119 | # 120 | with open(filename, "rb") as f: 121 | self.assertEqual(f.read(), b"abcd") 122 | 123 | # 124 | # Clean up after the test 125 | # 126 | storage.delete(storage_filename) 127 | 128 | # 129 | # use the minio client directly to also remove bucket 130 | # 131 | storage.client.remove_bucket(storage.bucket_name) 132 | -------------------------------------------------------------------------------- /tests/test_app/tests/delete_tests.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.core.files.base import ContentFile 3 | from django.test import TestCase, override_settings 4 | from django.utils import timezone 5 | 6 | from .utils import BaseTestMixin 7 | 8 | 9 | class DeleteTests(BaseTestMixin, TestCase): 10 | def test_file_removal_success(self): 11 | test_file = self.media_storage.save( 12 | "should_be_removed.txt", ContentFile(b"meh") 13 | ) 14 | self.media_storage.delete(test_file) 15 | self.assertFalse(self.media_storage.exists(test_file)) 16 | 17 | 18 | @override_settings( 19 | MINIO_STORAGE_MEDIA_BACKUP_BUCKET=settings.MINIO_STORAGE_MEDIA_BUCKET_NAME 20 | ) 21 | @override_settings(MINIO_STORAGE_MEDIA_BACKUP_FORMAT="Recycle Bin/%Y-%m-%d/") 22 | class BackupOnDeleteTests(BaseTestMixin, TestCase): 23 | def test_backup_on_file_removal(self): 24 | test_file = self.media_storage.save( 25 | "should_be_removed.txt", ContentFile(b"meh") 26 | ) 27 | self.media_storage.delete(test_file) 28 | now = timezone.now() 29 | removed_filename = now.strftime("Recycle Bin/%Y-%m-%d/should_be_removed.txt") 30 | self.assertTrue(self.media_storage.exists(removed_filename)) 31 | self.assertFalse(self.media_storage.exists(test_file)) 32 | 33 | def test_no_backups_for_static_files_by_default(self): 34 | test_file = self.static_storage.save( 35 | "should_be_removed.txt", ContentFile(b"meh") 36 | ) 37 | self.static_storage.delete(test_file) 38 | now = timezone.now() 39 | removed_filename = now.strftime("Recycle Bin/%Y-%m-%d/should_be_removed.txt") 40 | self.assertFalse(self.static_storage.exists(removed_filename)) 41 | self.assertFalse(self.static_storage.exists(test_file)) 42 | -------------------------------------------------------------------------------- /tests/test_app/tests/managementcommand_tests.py: -------------------------------------------------------------------------------- 1 | from io import StringIO 2 | 3 | import minio 4 | from django.core.files.base import ContentFile 5 | from django.core.management import call_command 6 | from django.core.management.base import CommandError 7 | from django.test import TestCase, override_settings 8 | 9 | from minio_storage.policy import Policy 10 | 11 | from .utils import BaseTestMixin, bucket_name 12 | 13 | 14 | @override_settings( 15 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, MINIO_STORAGE_STATIC_USE_PRESIGNED=False 16 | ) 17 | class CommandsTests(BaseTestMixin, TestCase): 18 | @override_settings( 19 | MINIO_STORAGE_AUTO_CREATE_MEDIA_BUCKET=False, 20 | MINIO_STORAGE_AUTO_CREATE_MEDIA_POLICY=False, 21 | ) 22 | def test_management_command(self): 23 | storage = self.media_storage 24 | bucket = self.media_storage.bucket_name 25 | 26 | call_command("minio", "check") 27 | 28 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} is not empty"): 29 | call_command("minio", "delete") 30 | 31 | try: 32 | self.obliterate_bucket(self.media_storage.bucket_name) 33 | except minio.error.S3Error: 34 | pass 35 | 36 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} does not exist"): 37 | call_command("minio", "check") 38 | 39 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} does not exist"): 40 | call_command("minio", "policy") 41 | 42 | with self.assertRaisesRegex(CommandError, f"error reading bucket {bucket}"): 43 | call_command("minio", "ls") 44 | 45 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} does not exist"): 46 | call_command("minio", "delete") 47 | 48 | call_command("minio", "create") 49 | 50 | call_command("minio", "check") 51 | 52 | with self.assertRaisesRegex(CommandError, f"error creating {bucket}"): 53 | call_command("minio", "create") 54 | 55 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} has no policy"): 56 | call_command("minio", "policy") 57 | 58 | for p in [p.value for p in Policy]: 59 | call_command("minio", "policy", "--set", p) 60 | 61 | call_command("minio", "policy", "--set", "GET_ONLY") 62 | 63 | call_command("minio", "policy") 64 | 65 | call_command("minio", "delete") 66 | 67 | with self.assertRaisesRegex(CommandError, f"bucket {bucket} does not exist"): 68 | call_command("minio", "check") 69 | 70 | call_command("minio", "create") 71 | 72 | files = [ 73 | "animals/cats/cat1.txt", 74 | "animals/cats/cat2.txt", 75 | "animals/dogs/dog1.txt", 76 | "animals/dogs/dog2.txt", 77 | "what.txt", 78 | ] 79 | for p in files: 80 | self.assertEqual(p, storage.save(p, ContentFile(b"abc"))) 81 | 82 | def ls_test(*args, expected): 83 | out = StringIO() 84 | call_command("minio", "ls", *args, stdout=out) 85 | out.seek(0) 86 | lines = out.read().splitlines() 87 | self.assertEqual(sorted(lines), sorted(expected)) 88 | 89 | test_data: list[tuple[list[str], list[str]]] = [ 90 | ( 91 | ["-r"], 92 | # 93 | [ 94 | "animals/dogs/dog1.txt", 95 | "animals/dogs/dog2.txt", 96 | "animals/cats/cat1.txt", 97 | "animals/cats/cat2.txt", 98 | "what.txt", 99 | ], 100 | ), 101 | ( 102 | ["--files"], 103 | # 104 | ["what.txt"], 105 | ), 106 | ( 107 | ["--dirs"], 108 | # 109 | ["animals/"], 110 | ), 111 | ( 112 | [], 113 | # 114 | ["animals/", "what.txt"], 115 | ), 116 | ( 117 | ["--prefix", "animals/"], 118 | # 119 | ["animals/dogs/", "animals/cats/"], 120 | ), 121 | ( 122 | ["--prefix", "animals/", "--dirs"], 123 | # 124 | ["animals/dogs/", "animals/cats/"], 125 | ), 126 | ( 127 | ["--prefix", "animals/", "--files"], 128 | # 129 | [], 130 | ), 131 | ( 132 | ["-r", "-p", "animals/do"], 133 | # 134 | ["animals/dogs/dog1.txt", "animals/dogs/dog2.txt"], 135 | ), 136 | ( 137 | ["-r", "-p", "animals/do", "--dirs"], 138 | # 139 | [], 140 | ), 141 | ] 142 | 143 | for test in test_data: 144 | (args, expected) = test 145 | ls_test(*args, expected=expected) 146 | 147 | def test_check(self): 148 | out = StringIO() 149 | call_command("minio", "check", stdout=out) 150 | self.assertIn("", out.getvalue()) 151 | 152 | def test_check_not_exists(self): 153 | name = bucket_name("new") 154 | out = StringIO() 155 | err = StringIO() 156 | with self.assertRaises(CommandError): 157 | call_command("minio", "--bucket", name, "check", stdout=out, stderr=err) 158 | self.assertEqual("", out.getvalue()) 159 | self.assertEqual("", err.getvalue()) 160 | 161 | def test_list_files(self): 162 | out = StringIO() 163 | call_command("minio", "ls", stdout=out) 164 | out.seek(0) 165 | lines = sorted(out.readlines()) 166 | expected = sorted([f"{self.new_file}\n", f"{self.second_file}\n"]) 167 | self.assertEqual(lines, expected) 168 | 169 | def test_list_buckets(self): 170 | out = StringIO() 171 | call_command("minio", "ls", "--buckets", stdout=out) 172 | out.seek(0) 173 | lines = sorted(out.readlines()) 174 | self.assertIn(f"{self.media_storage.bucket_name}\n", lines) 175 | -------------------------------------------------------------------------------- /tests/test_app/tests/package_tests.py: -------------------------------------------------------------------------------- 1 | from importlib.metadata import version as package_version 2 | 3 | from packaging.version import parse as parse_version 4 | 5 | # Any version less than this is a bug, but versions greater are fine 6 | MIN_VERSION = parse_version("0.5.7") 7 | 8 | 9 | def test_package_version_file(): 10 | from minio_storage.version import __version__ 11 | 12 | version = parse_version(__version__) 13 | assert version >= MIN_VERSION 14 | 15 | 16 | def test_package_version_metadata(): 17 | version = parse_version(package_version("django_minio_storage")) 18 | assert version >= MIN_VERSION 19 | -------------------------------------------------------------------------------- /tests/test_app/tests/retrieve_tests.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import io 3 | import os 4 | 5 | import requests 6 | from django.core.files.base import ContentFile 7 | from django.test import TestCase, override_settings 8 | from freezegun import freeze_time 9 | from minio.error import S3Error 10 | 11 | from minio_storage.storage import MinioMediaStorage 12 | 13 | from .utils import BaseTestMixin 14 | 15 | 16 | @override_settings( 17 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, MINIO_STORAGE_STATIC_USE_PRESIGNED=True 18 | ) 19 | class RetrieveTestsWithRestrictedBucket(BaseTestMixin, TestCase): 20 | def test_presigned_url_generation(self): 21 | media_test_file_name = self.media_storage.save( 22 | "weird & ÜRΛ", ContentFile(b"irrelevant") 23 | ) 24 | url = self.media_storage.url(media_test_file_name) 25 | res = requests.get(url) 26 | self.assertEqual(res.content, b"irrelevant") 27 | 28 | static_test_file_name = self.static_storage.save( 29 | "weird & ÜRΛ", ContentFile(b"irrelevant") 30 | ) 31 | url = self.static_storage.url(static_test_file_name) 32 | res = requests.get(url) 33 | self.assertEqual(res.content, b"irrelevant") 34 | 35 | def test_url_of_non_existent_object(self): 36 | self.media_storage.url("this does not exist") 37 | 38 | def test_file_size(self): 39 | test_file = self.media_storage.save("sizetest.txt", ContentFile(b"1234")) 40 | self.assertEqual(4, self.media_storage.size(test_file)) 41 | 42 | def test_size_of_non_existent_raises_exception(self): 43 | test_file = self.media_storage.save("sizetest.txt", ContentFile(b"1234")) 44 | self.media_storage.delete(test_file) 45 | with self.assertRaises(S3Error): 46 | self.media_storage.size(test_file) 47 | 48 | def test_modified_time(self): 49 | self.assertIsInstance( 50 | self.media_storage.modified_time(self.new_file), datetime.datetime 51 | ) 52 | 53 | def test_accessed_time(self): 54 | self.assertIsInstance( 55 | self.media_storage.accessed_time(self.new_file), datetime.datetime 56 | ) 57 | 58 | def test_created_time(self): 59 | self.assertIsInstance( 60 | self.media_storage.created_time(self.new_file), datetime.datetime 61 | ) 62 | 63 | def test_modified_time_of_non_existent_raises_exception(self): 64 | with self.assertRaises(S3Error): 65 | self.media_storage.modified_time("nonexistent.jpg") 66 | 67 | def _listdir_root(self, root): 68 | self.media_storage.save("dir1/file2.txt", ContentFile(b"meh")) 69 | test_dir = self.media_storage.listdir(root) 70 | (dirs, files) = test_dir 71 | self.assertEqual(dirs, ["dir1"]) 72 | self.assertEqual(files, sorted([self.new_file, self.second_file])) 73 | self.assertEqual(len(files), 2) 74 | self.assertEqual(len(test_dir), 2) 75 | 76 | def test_listdir_emptystr(self): 77 | self._listdir_root("") 78 | 79 | def test_listdir_dot(self): 80 | self._listdir_root(".") 81 | 82 | def test_listdir_none(self): 83 | self._listdir_root(None) 84 | 85 | def test_listdir_slash(self): 86 | self._listdir_root("/") 87 | 88 | def _listdir_sub(self, path): 89 | self.media_storage.save("dir/file.txt", ContentFile(b"meh")) 90 | self.media_storage.save("dir/file2.txt", ContentFile(b"meh")) 91 | self.media_storage.save("dir/dir3/file3.txt", ContentFile(b"meh")) 92 | dirs, files = self.media_storage.listdir("dir/") 93 | self.assertEqual((dirs, files), (["dir3"], ["file.txt", "file2.txt"])) 94 | 95 | def test_listdir_subdir_slash(self): 96 | self._listdir_sub("dir/") 97 | 98 | def test_listdir_subdir_noslash(self): 99 | self._listdir_sub("dir") 100 | 101 | def test_list_nonexist(self): 102 | test_dir = self.media_storage.listdir("nonexist") 103 | self.assertEqual(test_dir, ([], [])) 104 | 105 | def test_list_prefix(self): 106 | self.media_storage.save("dir/file.txt", ContentFile(b"meh")) 107 | test_dir = self.media_storage.listdir("di") 108 | self.assertEqual(test_dir, ([], [])) 109 | 110 | def test_file_exists(self): 111 | existent = self.media_storage.save("existent.txt", ContentFile(b"meh")) 112 | self.assertTrue(self.media_storage.exists(existent)) 113 | 114 | def test_file_exists_failure(self): 115 | self.assertFalse(self.media_storage.exists("nonexistent.txt")) 116 | 117 | def test_reading_non_existing_file_raises_exception(self): 118 | with self.assertRaises(S3Error): 119 | f = self.media_storage.open("this does not exist") 120 | f.read() 121 | 122 | def test_reading_respects_binary_mode_flag(self): 123 | self.media_storage.save("test.txt", io.BytesIO(b"stuff")) 124 | f = self.media_storage.open("test.txt", "rb") 125 | self.assertEqual(f.read(), b"stuff") 126 | 127 | def test_reading_respects_text_mode_flag(self): 128 | self.media_storage.save("test.txt", io.BytesIO(b"stuff")) 129 | f = self.media_storage.open("test.txt", "r") 130 | self.assertEqual(f.read(), "stuff") 131 | 132 | def test_file_names_are_properly_sanitized(self): 133 | self.media_storage.save("./meh22222.txt", io.BytesIO(b"stuff")) 134 | 135 | def test_url_max_age(self): 136 | url = self.media_storage.url( 137 | "test-file", max_age=datetime.timedelta(seconds=10) 138 | ) 139 | self.assertEqual(requests.get(url).status_code, 200) 140 | 141 | def test_max_age_too_old(self): 142 | with freeze_time(-datetime.timedelta(seconds=10)): 143 | url = self.media_storage.url( 144 | "test-file", max_age=datetime.timedelta(seconds=10) 145 | ) 146 | self.assertEqual(requests.get(url).status_code, 403) 147 | 148 | def test_no_file(self): 149 | url = self.media_storage.url("no-file", max_age=datetime.timedelta(seconds=10)) 150 | self.assertEqual(requests.get(url).status_code, 404) 151 | 152 | def test_max_age_no_file(self): 153 | with freeze_time(-datetime.timedelta(seconds=10)): 154 | url = self.media_storage.url( 155 | "no-file", max_age=datetime.timedelta(seconds=10) 156 | ) 157 | self.assertEqual(requests.get(url).status_code, 403) 158 | 159 | 160 | class URLTests(TestCase): 161 | @override_settings( 162 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 163 | MINIO_STORAGE_MEDIA_URL=None, 164 | MINIO_STORAGE_MEDIA_BUCKET_NAME="foo", 165 | ) 166 | def test_no_base_url(self): 167 | endpoint = os.getenv("MINIO_STORAGE_ENDPOINT", "minio:9000") 168 | assert endpoint != "" 169 | media_storage = MinioMediaStorage() 170 | url = media_storage.url("22") 171 | self.assertEqual(url, f"http://{endpoint}/foo/22") 172 | 173 | @override_settings( 174 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 175 | MINIO_STORAGE_MEDIA_URL=None, 176 | MINIO_STORAGE_MEDIA_BUCKET_NAME="foo", 177 | ) 178 | def test_no_base_url_subpath(self): 179 | endpoint = os.getenv("MINIO_STORAGE_ENDPOINT", "minio:9000") 180 | assert endpoint != "" 181 | media_storage = MinioMediaStorage() 182 | name = "23/23/aaa/bbb/22" 183 | url = media_storage.url(name) 184 | self.assertEqual(url, f"http://{endpoint}/foo/23/23/aaa/bbb/22") 185 | 186 | @override_settings( 187 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, 188 | MINIO_STORAGE_MEDIA_URL=None, 189 | MINIO_STORAGE_MEDIA_BUCKET_NAME="foo", 190 | ) 191 | def test_presigned_no_base_url(self): 192 | endpoint = os.getenv("MINIO_STORAGE_ENDPOINT", "minio:9000") 193 | assert endpoint != "" 194 | media_storage = MinioMediaStorage() 195 | url = media_storage.url("22") 196 | self.assertRegex(url, rf"^http://{endpoint}/foo/22\?") 197 | 198 | @override_settings( 199 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 200 | MINIO_STORAGE_MEDIA_URL="https://example23.com/foo", 201 | MINIO_STORAGE_MEDIA_BUCKET_NAME="bar", 202 | ) 203 | def test_base_url(self): 204 | media_storage = MinioMediaStorage() 205 | url = media_storage.url("1") 206 | self.assertEqual(url, "https://example23.com/foo/1") 207 | 208 | @override_settings( 209 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 210 | MINIO_STORAGE_MEDIA_URL="https://example23.com/foo", 211 | MINIO_STORAGE_MEDIA_BUCKET_NAME="bar", 212 | ) 213 | def test_base_url_subpath(self): 214 | media_storage = MinioMediaStorage() 215 | url = media_storage.url("1/2/3/4") 216 | self.assertEqual(url, "https://example23.com/foo/1/2/3/4") 217 | 218 | @override_settings( 219 | MINIO_STORAGE_MEDIA_URL="http://example11.com/foo", 220 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, 221 | MINIO_STORAGE_MEDIA_BUCKET_NAME="bar", 222 | ) 223 | def test_presigned_base_url(self): 224 | media_storage = MinioMediaStorage() 225 | url = media_storage.url("1") 226 | self.assertIn("X-Amz-Signature", url) 227 | self.assertRegex(url, r"^http://example11.com/foo/1\?") 228 | 229 | @override_settings( 230 | MINIO_STORAGE_MEDIA_URL="http://example11.com/foo", 231 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, 232 | MINIO_STORAGE_MEDIA_BUCKET_NAME="bar", 233 | ) 234 | def test_presigned_base_url_subpath(self): 235 | media_storage = MinioMediaStorage() 236 | url = media_storage.url("1/555/666/777") 237 | self.assertIn("X-Amz-Signature", url) 238 | self.assertRegex(url, r"^http://example11.com/foo/1/555/666/777\?") 239 | 240 | BASE = "http://base/url" 241 | NAME = "Bö/ &öl@:/E" 242 | ENCODED = "B%C3%B6/%20%26%C3%B6l%40%3A/E" 243 | 244 | @override_settings( 245 | MINIO_STORAGE_MEDIA_URL=None, 246 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 247 | MINIO_STORAGE_MEDIA_BUCKET_NAME="encoding", 248 | ) 249 | def test_quote_url(self): 250 | media_storage = MinioMediaStorage() 251 | url = media_storage.url(self.NAME) 252 | self.assertTrue(url.endswith(self.ENCODED)) 253 | self.assertTrue(len(url) > len(self.ENCODED)) 254 | 255 | @override_settings( 256 | MINIO_STORAGE_MEDIA_URL=BASE, 257 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=False, 258 | MINIO_STORAGE_MEDIA_BUCKET_NAME="encoding", 259 | ) 260 | def test_quote_base_url(self): 261 | media_storage = MinioMediaStorage() 262 | url = media_storage.url(self.NAME) 263 | self.assertEqual(url, f"{self.BASE}/{self.ENCODED}") 264 | 265 | @override_settings( 266 | MINIO_STORAGE_MEDIA_URL=BASE, 267 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, 268 | MINIO_STORAGE_MEDIA_BUCKET_NAME="encoding", 269 | ) 270 | def test_quote_base_url_presigned(self): 271 | media_storage = MinioMediaStorage() 272 | url = media_storage.url(self.NAME) 273 | prefix = f"{self.BASE}/{self.ENCODED}" 274 | self.assertTrue(url.startswith(prefix)) 275 | self.assertTrue(len(url) > len(prefix)) 276 | -------------------------------------------------------------------------------- /tests/test_app/tests/settings_tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase, override_settings 2 | 3 | from minio_storage.storage import MinioMediaStorage 4 | from tests.test_app.tests.utils import BaseTestMixin 5 | 6 | 7 | class SettingsTests(BaseTestMixin, TestCase): 8 | @override_settings( 9 | MINIO_STORAGE_REGION="eu-central-666", 10 | ) 11 | def test_settings_with_region(self): 12 | ms = MinioMediaStorage() 13 | region = ms.client._get_region(self.bucket_name("tests-media")) 14 | self.assertEqual(region, "eu-central-666") 15 | 16 | def test_settings_without_region(self): 17 | ms = MinioMediaStorage() 18 | region = ms.client._get_region(self.bucket_name("tests-media")) 19 | self.assertEqual(region, "us-east-1") 20 | -------------------------------------------------------------------------------- /tests/test_app/tests/upload_tests.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import requests 4 | from django.conf import settings 5 | from django.core.files.base import ContentFile, File 6 | from django.test import TestCase, override_settings 7 | from minio.error import S3Error 8 | 9 | from minio_storage.storage import MinioMediaStorage 10 | 11 | from .utils import BaseTestMixin 12 | 13 | 14 | @override_settings( 15 | MINIO_STORAGE_MEDIA_USE_PRESIGNED=True, MINIO_STORAGE_STATIC_USE_PRESIGNED=True 16 | ) 17 | class UploadTests(BaseTestMixin, TestCase): 18 | def test_file_upload_success(self): 19 | self.media_storage.save("trivial.txt", ContentFile(b"12345")) 20 | 21 | @override_settings( 22 | MINIO_STORAGE_ACCESS_KEY="wrong_key", MINIO_STORAGE_SECRET_KEY="wrong_secret" 23 | ) 24 | def test_file_upload_fail_incorrect_keys(self): 25 | with self.assertRaises(S3Error): 26 | MinioMediaStorage() 27 | 28 | def test_two_files_with_the_same_name_can_be_uploaded(self): 29 | ivan = self.media_storage.save("pelican.txt", ContentFile(b"Ivan le Pelican")) 30 | jean = self.media_storage.save("pelican.txt", ContentFile(b"Jean le Pelican")) 31 | self.assertNotEqual(jean, ivan) 32 | 33 | def test_files_from_filesystem_are_uploaded_properly(self): 34 | f = File(open(os.path.join(settings.BASE_DIR, "watermelon-cat.jpg"), "br")) 35 | saved_file = self.media_storage.save("watermelon-cat.jpg", f) 36 | res = requests.get(self.media_storage.url(saved_file)) 37 | self.assertAlmostEqual( 38 | round(res.content.__sizeof__() / 100), round(f.size / 100) 39 | ) 40 | 41 | def test_files_are_uploaded_from_the_beginning(self): 42 | local_filename = os.path.join(settings.BASE_DIR, "watermelon-cat.jpg") 43 | f = open(local_filename, "br") 44 | f.seek(20000) 45 | saved_file = self.media_storage.save("watermelon-cat.jpg", f) 46 | file_size = os.stat(local_filename).st_size 47 | res = requests.get(self.media_storage.url(saved_file)) 48 | self.assertAlmostEqual( 49 | round(res.content.__sizeof__() / 100), round(file_size / 100) 50 | ) 51 | 52 | def test_files_cannot_be_open_in_write_mode(self): 53 | test_file = self.media_storage.save( 54 | "iomodetest.txt", ContentFile(b"should not change") 55 | ) 56 | with self.assertRaises(NotImplementedError): 57 | self.media_storage.open(test_file, mode="bw") 58 | 59 | def test_files_seekable(self): 60 | self.media_storage.save("read_seek_test.txt", ContentFile(b"should not change")) 61 | 62 | f = self.media_storage.open("read_seek_test.txt", mode="br") 63 | f.seek(4) 64 | f.seek(0) 65 | 66 | def test_upload_and_get_back_file_with_funky_name(self): 67 | self.media_storage.save("áčďěščřžýŽŇůúť.txt", ContentFile(b"12345")) 68 | 69 | def test_upload_file_beggining_with_dot(self): 70 | self.media_storage.save( 71 | ".hidden_file", ContentFile(b"Not really, but whatever") 72 | ) 73 | self.assertTrue(self.media_storage.exists(".hidden_file")) 74 | self.media_storage.delete(".hidden_file") 75 | self.assertFalse(self.media_storage.exists(".hidden_file")) 76 | 77 | def test_metadata(self): 78 | ivan = self.media_storage.save("pelican.txt", ContentFile(b"Ivan le Pelican")) 79 | res = self.media_storage.client.stat_object( 80 | self.media_storage.bucket_name, ivan 81 | ) 82 | metadata_attrs = { 83 | "Accept-Ranges", 84 | "Content-Length", 85 | "Content-Type", 86 | "ETag", 87 | "Last-Modified", 88 | "Server", 89 | "Vary", 90 | "X-Amz-Request-Id", 91 | "X-Xss-Protection", 92 | "Date", 93 | } 94 | assert res.metadata is not None 95 | assert metadata_attrs <= set(res.metadata.keys()) 96 | 97 | 98 | @override_settings( 99 | MINIO_STORAGE_MEDIA_OBJECT_METADATA={"Cache-Control": "max-age=1000"}, 100 | ) 101 | class TestDefaultObjectMetadata(BaseTestMixin, TestCase): 102 | def test_default_metadata(self): 103 | ivan = self.media_storage.save("pelican.txt", ContentFile(b"Ivan le Pelican")) 104 | res = self.media_storage.client.stat_object( 105 | self.media_storage.bucket_name, ivan 106 | ) 107 | 108 | assert res.metadata is not None 109 | self.assertEqual(res.metadata["Cache-Control"], "max-age=1000") 110 | -------------------------------------------------------------------------------- /tests/test_app/tests/utils.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import os 3 | import warnings 4 | 5 | from django.core.files.base import ContentFile 6 | from minio import Minio 7 | 8 | from minio_storage.storage import MinioMediaStorage, MinioStaticStorage, get_setting 9 | 10 | warnings.simplefilter("default") 11 | warnings.filterwarnings( 12 | "ignore", message="This usage is deprecated, please use pytest.* instead" 13 | ) 14 | 15 | 16 | warnings.simplefilter("ignore", ResourceWarning) 17 | 18 | 19 | def bucket_name(name): 20 | env_name = os.getenv("TOX_ENVNAME", "").encode("utf-8") 21 | env_hash = hashlib.md5(env_name).hexdigest() 22 | return "".join([name, env_hash]) 23 | 24 | 25 | class BaseTestMixin: 26 | @staticmethod 27 | def bucket_name(name): 28 | return bucket_name(name) 29 | 30 | def setUp(self): 31 | self.media_storage = MinioMediaStorage() 32 | self.static_storage = MinioStaticStorage() 33 | self.new_file = self.media_storage.save("test-file", ContentFile(b"yep")) 34 | self.second_file = self.media_storage.save("test-file", ContentFile(b"nope")) 35 | 36 | def tearDown(self): 37 | client = self.minio_client() 38 | self.obliterate_bucket(self.bucket_name("tests-media"), client=client) 39 | self.obliterate_bucket(self.bucket_name("tests-static"), client=client) 40 | 41 | def minio_client(self): 42 | minio_client = Minio( 43 | endpoint=get_setting("MINIO_STORAGE_ENDPOINT"), 44 | access_key=get_setting("MINIO_STORAGE_ACCESS_KEY"), 45 | secret_key=get_setting("MINIO_STORAGE_SECRET_KEY"), 46 | secure=get_setting("MINIO_STORAGE_USE_HTTPS"), 47 | ) 48 | return minio_client 49 | 50 | def obliterate_bucket(self, name, client=None): 51 | if client is None: 52 | client = self.minio_client() 53 | 54 | for obj in client.list_objects(name, "", True): 55 | assert obj.object_name is not None 56 | client.remove_object(name, obj.object_name) 57 | client.remove_bucket(name) 58 | -------------------------------------------------------------------------------- /tests/watermelon-cat.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/py-pa/django-minio-storage/beb2654f1e18b78c3c00f5f160288e0a40a1e1cb/tests/watermelon-cat.jpg -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | env_list = 3 | # All Pythons, oldest Django 4 | {py39,py310,py311,py312,py313}-django42-minioknown 5 | # Newest Python, all Djangos 6 | py313-django{42,51,52}-minioknown 7 | # Newest Python, newest Django, newest Minio 8 | py313-django52-minio 9 | lint 10 | docs 11 | pyright 12 | 13 | [gh-actions] 14 | python = 15 | 3.9: py39 16 | 3.10: py310 17 | 3.11: py311 18 | 3.12: py312 19 | 3.13: py313, lint, docs, pyright 20 | 21 | [testenv] 22 | package = wheel 23 | set_env = 24 | PYTHONDONTWRITEBYTECODE = 1 25 | MINIO_STORAGE_ENDPOINT = {env:MINIO_STORAGE_ENDPOINT:localhost:9153} 26 | MINIO_STORAGE_ACCESS_KEY = {env:MINIO_STORAGE_ACCESS_KEY:weak_access_key} 27 | MINIO_STORAGE_SECRET_KEY = {env:MINIO_STORAGE_SECRET_KEY:weak_secret_key} 28 | TOX_ENVNAME = {envname} 29 | deps = 30 | django42: Django==4.2.* 31 | django51: Django==5.1.* 32 | django52: Django==5.2.* 33 | minio: minio 34 | minioknown: minio==7.1.12 35 | -rdev-requirements.txt 36 | commands = 37 | pytest {posargs} 38 | 39 | [testenv:py313-django52-minioknown] 40 | commands = 41 | pytest --cov --cov-append --cov-report=term-missing {posargs} 42 | 43 | [testenv:coverage-report] 44 | package = skip 45 | depends = py313-django52-minioknown 46 | deps = 47 | coverage[toml] 48 | commands = 49 | coverage report 50 | coverage html 51 | 52 | [testenv:pyright] 53 | package = editable 54 | depends = py313-django52-minio 55 | deps = 56 | pyright 57 | django-stubs==5.2.* 58 | types-requests 59 | -rdev-requirements.txt 60 | commands = 61 | pyright --level WARNING 62 | 63 | [testenv:lint] 64 | package = skip 65 | set_env= 66 | PYTHONWARNINGS = ignore 67 | deps = 68 | ruff==0.11.8 69 | commands = 70 | ruff check 71 | ruff format --check 72 | 73 | [testenv:fmt] 74 | package = skip 75 | set_env= 76 | PYTHONWARNINGS = ignore 77 | deps = 78 | ruff==0.11.8 79 | commands = 80 | ruff check --fix-only 81 | ruff format 82 | 83 | [testenv:docs] 84 | package = skip 85 | deps = 86 | mkdocs 87 | commands = 88 | mkdocs build 89 | --------------------------------------------------------------------------------