如何使用 Python 获取 Azure 文件存储的文件属性 REST API "content_type"

How to get "content_type" using Get File Properties REST API for Azure Files Storage using Python

我正在尝试为 Azure 文件共享中的文件获取“content_type”属性。我可以得到“last_modified”和“大小”但不能得到“content_type”

from azure.storage.file import *
from azure.storage.fileshare import *

def azure_connect_conn_string(source_file_connection_string, source_share_name):
    try:
        share_service = ShareServiceClient.from_connection_string(source_file_connection_string)#ShareServiceClient interact with the account level
        share_client = share_service.get_share_client(source_share_name) #desired share name is accessed
        file_service = FileService(connection_string=source_file_connection_string)
        print("Connection String -- Connected.")
        return share_client, file_service #returns the share client

    except Exception as ex:
        print("Error: " + str(ex))

def fileshare_content_list(connection_instance, directory_name, file_service, share_name):
    d_client = connection_instance.get_directory_client(directory_name)
    my_files = d_client.list_directories_and_files()
    directory_list = []

    for file in my_files:
        if file.get('is_directory'):
            #cannot get size of directory, only of files
            file_name = file.get('name')
            file_lastmod = file.get('last_modified')
            file_type = 'directory'
            file_size = 'unknown'

        else:
            file_name = file.get('name')
            file_props = file_service.get_file_properties(share_name, directory_name, file_name)
            file_lastmod = file_props.properties.last_modified
            file_size = file.get('size')
            print(file_name)
            print(file_lastmod)
            print(file_size)
            print(file_props.properties.content_type)

def main():
    try:
        azure_connection_string = 'DefaultEndpointsProtocol=https;AccountName=ecpcdmsdatamartexternal;AccountKey=neNa1jtdyVljMN/j403/rHwdYBpPUtKTreeYM4UsKiosiOfKdePgyZdJl8SK9UdAlsXwVvOkNdNWZjnOCyn/lw==;EndpointSuffix=core.windows.net'
        share_name = "ecdmpext"
        directory_name = "data"
        connection_instance, file_service = azure_connect_conn_string(azure_connection_string, share_name)

        ## List files
        fileshare_content_list(connection_instance, directory_name, file_service, share_name)
        print('Done')
    
    except Exception as ex:
        print('main | Error: ', ex)

if __name__ == "__main__":
    main()

我收到错误 'FileProperties' object has no attribute 'content_type'

当我尝试使用 file.get("content_type") 时,我只得到“None”。 我将 file.get() 用于“大小”和“名称”,对于“last_modified”我必须使用 file_service.get_file_properties.properties.last_modified 但两种方法都不适用于“content_type”。

你快到了:)。 content_type 属性 实际上是 content_settings property in File's property returned by get_file_properties 的子 属性。

所以你的代码应该是这样的:

file_content_type = file_props.properties.content_settings.content_type