gpt4 book ai didi

python - 上传到 Azure Blob 存储时自动设置内容类型

转载 作者:行者123 更新时间:2023-12-03 03:37:12 25 4
gpt4 key购买 nike

我正在尝试使用 Python 将数千个文件上传到 Azure 存储。它们的内容类型默认设置为“application/octet-stream”

我知道我可以使用(指定 here )设置单个文件的内容类型:

content_settings = ContentSettings(content_type="something")

但问题是所有文件的内容类型并不相同。我有图像、javascript 文件、html 文件和一百多种其他类型。

在使用 Python 将文件上传到 Azure 存储 blob 之前,如何根据计算机本地的文件自动设置内容类型?

我知道这是可行的,因为azcopy使用正确的内容类型上传。 (我测试过)

这是我编写的Python代码的一部分:

def upload(self, overwrite=False):
with ThreadPool(self._num_threads) as pool:
request_processes = []
for local_path, remote_path in path_generator()
blob_client = BlobClient.from_blob_url(blob_url=remote_path, credential=credentials)
file_extension: str = local_path.split('/')[-1].split('.')[-1]
content_settings = ContentSettings(content_type=file_extension)
kwargs: Dict[str, Any] = {'blob_type': 'BlockBlob',
'content_settings': content_settings,
'validate_content': True,
'overwrite': overwrite,
'timeout': self._timeout_seconds,
'max_concurrency': 10}
request_processes.append(pool.apply_async(self._sync_upload_file,
[blob_client, local_path],
kwds=kwargs))
for req in request_processes:
req.get(self._timeout_seconds)

@staticmethod
def _sync_upload_file(blob_client, local_path: str, *args, **kwargs):
with open(local_path, "rb") as data:
resp = blob_client.upload_blob(data, *args, **kwargs)
return resp

此代码的问题在于它使用文件扩展名(js、html、png 等)作为内容类型。例如,html 文件的内容类型应为 text/html

最佳答案

我在这个 website 中找到了一个解决方案.

他们创建了一个从 650 多个文件扩展名到内容类型的映射(字典)。但我仍然有一些文件类型不存在于这本字典中。例如“.map”、“.config”、“.info”等等。

关于python - 上传到 Azure Blob 存储时自动设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72902835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com