Skip to content

ValueError: path in endpoint is not allowed

win11 + minio + django5.0 + python3.12

在Django中集成minio时,minio的链接配置是这样的:

python
MINIO_CONFIG = {
    "access_key": "minioadmin",
    "secret_key": "minioadmin",
    "endpoint": "http://127.0.0.1:9000",
    "secure": False,
}
python
import os
from minio import Minio
from minio.error import S3Error
from datetime import timedelta
from minio.deleteobjects import DeleteObject
from django.conf import settings

class MinioClient(MinioBucket, MinioObject):
    """https://www.cnblogs.com/xujunkai/p/14749165.html原代码出处"""
    client = None
    policy = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetBucketLocation","s3:ListBucket"],"Resource":["arn:aws:s3:::%s"]},{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}'

    def __new__(cls, *args, **kwargs):
        if not cls.client:
            cls.client = object.__new__(cls)
        return cls.client

    def __init__(self):
        # 创建minio的连接对象
        self.client = Minio(**settings.MINIO_CONFIG)
python
import os
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from django.views.generic import View
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.forms import ModelForm, Form
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
from django.conf import settings
from apps.store.models import UserInfo

from utils.minioBucket import MinioClient

class UserInfoForm(ModelForm):

    class Meta:
        model = UserInfo
        fields = ['username', 'avatar', 'cert']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 为所有的字段添加相同的属性
        for field in self.fields.values():
            field.widget.attrs.update({"class": "form-control"})
            field.error_messages.update({"required": "该字段不能为空"})

    def clean_cert(self):
        # 校验就省略了
        file = self.files.get('cert')
        if not file:
            raise ValidationError("文件不能为空")
        if file.size > settings.FILE_SIZE:
            raise ValidationError("文件大小不能超过10M")
        if file.name.split('.')[-1] not in settings.FILE_TYPE:
            raise ValidationError(f"文件类型不正确,仅支持{settings.FILE_TYPE}")
        # 保存文件到minio
        mc = MinioClient()
        
        return file

但是Django项目中进行调用编写的minio的类时,运行报错:

bash
Internal Server Error: /store/minio_useradd/
......省略不相关的报错.......
  File "D:\code\dj5\apps\store\views\minio_view.py", line 38, in clean_cert
    mc2 = MinioClient()
          ^^^^^^^^^^^^^
  File "D:\code\dj5\utils\minioBucket.py", line 236, in __init__
    self.client = Minio(**settings.MINIO_CONFIG)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\software\miniconda3\envs\dj5py312\Lib\site-packages\minio\api.py", line 152, in __init__
    self._base_url = BaseURL(
                     ^^^^^^^^
  File "C:\software\miniconda3\envs\dj5py312\Lib\site-packages\minio\helpers.py", line 541, in __init__
    url = _parse_url(endpoint)
          ^^^^^^^^^^^^^^^^^^^^
  File "C:\software\miniconda3\envs\dj5py312\Lib\site-packages\minio\helpers.py", line 502, in _parse_url
    raise ValueError("path in endpoint is not allowed")
ValueError: path in endpoint is not allowed

其原因就是配置中的endpoint参数的问题:

python
MINIO_CONFIG = {
    "access_key": "minioadmin",
    "secret_key": "minioadmin",
    "endpoint": "http://127.0.0.1:9000",
    "secure": False,
}

我发现两种解决方案:

bash
# 第一种,去掉前面的http://或者https://
"endpoint": "127.0.0.1:9000"

# 第二种方案,在路径最后加/
"endpoint": "http://127.0.0.1:9000/"

这俩试着来吧。

参考: