【问题标题】:"encoding with 'idna' codec failed (UnicodeError: label too long)" when I call the following django api code to upload a file to Azure Blob Storage当我调用以下 django api 代码将文件上传到 Azure Blob 存储时,“使用 'idna' 编解码器编码失败(UnicodeError:标签太长)”
【发布时间】:2020-04-06 00:57:37
【问题描述】:
import os

from azure.storage.blob import BlockBlobService, baseblobservice
from django.http import JsonResponse
from rest_framework.decorators import api_view


@api_view(['GET', 'POST'])
def upload_to_blob(request):
    try:
        container_name = 'xyzxyzxyz'
        connection_string = "DefaultEndpointsProtocol=https;AccountName=dapblobstorage;AccountKey=abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefgh==;"
        local_file_path = "D:\Work\\uploadToBLOB API\\test\\a4.csv"
        upload_location = "kuldeep/api"

        block_blob_service = BlockBlobService(connection_string)

        if os.path.exists(local_file_path):
            block_blob_service.create_blob_from_path(container_name=container_name
                                                    , blob_name=(upload_location.strip('/') + '/' + os.path.basename(local_file_path))
                                                    , file_path=local_file_path)

        return JsonResponse({'message': f'{os.path.basename(local_file_path)} uploaded successfully!'}, status=200, safe=False)
    except Exception as err:
        loggers.error(err, exc_info=True)
        return JsonResponse({'message': f'File upload failed with error - {err}'}, status=500, safe=False)

响应:{“消息”:“文件上传失败并出现错误 - 使用 'idna' 编解码器编码失败(UnicodeError:标签太长)”}

请帮忙!

【问题讨论】:

    标签: python django azure azure-storage azure-blob-storage


    【解决方案1】:

    您的问题是由错误的代码block_blob_service = BlockBlobService(connection_string)引起的。

    根据azure-storage-python/azure-storage-blob/azure/storage/blob/blockblobservice.py源码中的构造函数BlockBlobService,如下图,

    如果你想使用 Azure 存储的连接字符串来创建一个BlockBlobService 对象,你应该将你的connection_string 变量的值传递给它的参数connection_string,如下代码所示。

    block_blob_service = BlockBlobService(connection_string=connection_string)
    

    如果不是,您的connection_string 变量的值将与account_name 参数的值一样,并导致问题https://bugs.python.org/issue32958 在打开套接字时用于Azure 存储的url。

    同时,请在local_file_pathD:\ 中添加一个反斜杠以使其正确并避免用作WorkW 的转义字符,或者只使用斜杠/ 而不是双反斜杠路径中的\\D:/Work/uploadToBLOB API/test/a4.csv 与 Windows 上的D:\\Work\\uploadToBLOB API\\test\\a4.csv 相同。

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2021-08-08
      • 2018-01-04
      • 2018-09-02
      相关资源
      最近更新 更多