Package: azure-storage-file-datalake
Azure DataLake service client library for PythonOverviewThis preview package for Python includes ADLS Gen2 specific API support made available in Storage SDK. This includes:New directory level operations (Create, Rename, Delete) for hierarchical namespace enabled (HNS) storage account. For HNS enabled accounts, the rename/move operations are atomic.Permission related operations (Get/Set ACLs) for hierarchical namespace enabled (HNS) accounts.Source code|Package (PyPi)|Package (Conda)|API reference documentation|Product documentation|SamplesGetting startedPrerequisitesPython 3.7 or later is required to use this package. For more details, please read our page onAzure SDK for Python version support policy.You must have anAzure subscriptionand anAzure storage accountto use this package.Install the packageInstall the Azure DataLake Storage client library for Python withpip:pipinstallazure-storage-file-datalake--preCreate a storage accountIf you wish to create a new storage account, you can use theAzure Portal,Azure PowerShell,
orAzure CLI:# Create a new resource group to hold the storage account -# if using an existing resource group, skip this stepazgroupcreate--namemy-resource-group--locationwestus2# Install the extension 'Storage-Preview'azextensionadd--namestorage-preview# Create the storage accountazstorageaccountcreate--namemy-storage-account-name--resource-groupmy-resource-group--skuStandard_LRS--kindStorageV2--hierarchical-namespacetrueAuthenticate the clientInteraction with DataLake Storage starts with an instance of the DataLakeServiceClient class. You need an existing storage account, its URL, and a credential to instantiate the client object.Get credentialsTo authenticate the client you have a few options:Use a SAS token stringUse an account shared access keyUse a token credential fromazure.identityAlternatively, you can authenticate with a storage connection string using thefrom_connection_stringmethod. See example:Client creation with a connection string.You can omit the credential if your account URL already has a SAS token.Create clientOnce you have your account URL and credentials ready, you can create the DataLakeServiceClient:fromazure.storage.filedatalakeimportDataLakeServiceClientservice=DataLakeServiceClient(account_url="https://<my-storage-account-name>.dfs.core.windows.net/",credential=credential)Key conceptsDataLake storage offers four types of resources:The storage accountA file system in the storage accountA directory under the file systemA file in a the file system or under directoryAsync ClientsThis library includes a complete async API supported on Python 3.5+. To use it, you must
first install an async transport, such asaiohttp.
Seeazure-core documentationfor more information.Async clients and credentials should be closed when they're no longer needed. These
objects are async context managers and define asyncclosemethods.ClientsThe DataLake Storage SDK provides four different clients to interact with the DataLake Service:DataLakeServiceClient- this client interacts with the DataLake Service at the account level.
It provides operations to retrieve and configure the account properties
as well as list, create, and delete file systems within the account.
For operations relating to a specific file system, directory or file, clients for those entities
can also be retrieved using theget_file_client,get_directory_clientorget_file_system_clientfunctions.FileSystemClient- this client represents interaction with a specific
file system, even if that file system does not exist yet. It provides operations to create, delete, or
configure file systems and includes operations to list paths under file system, upload, and delete file or
directory in the file system.
For operations relating to a specific file, the client can also be retrieved using
theget_file_clientfunction.
For operations relating to a specific directory, the client can be retrieved using
theget_directory_clientfunction.DataLakeDirectoryClient- this client represents interaction with a specific
directory, even if that directory does not exist yet. It provides directory operations create, delete, rename,
get properties and set properties operations.DataLakeFileClient- this client represents interaction with a specific
file, even if that file does not exist yet. It provides file operations to append data, flush data, delete,
create, and read file.DataLakeLeaseClient- this client represents lease interactions with a FileSystemClient, DataLakeDirectoryClient
or DataLakeFileClient. It provides operations to acquire, renew, release, change, and break leases on the resources.ExamplesThe following sections provide several code snippets covering some of the most common Storage DataLake tasks, including:Client creation with a connection stringUploading a fileDownloading a fileEnumerating pathsClient creation with a connection stringCreate the DataLakeServiceClient using the connection string to your Azure Storage account.fromazure.storage.filedatalakeimportDataLakeServiceClientservice=DataLakeServiceClient.from_connection_string(conn_str="my_connection_string")Uploading a fileUpload a file to your file system.fromazure.storage.filedatalakeimportDataLakeFileClientdata=b"abc"file=DataLakeFileClient.from_connection_string("my_connection_string",file_system_name="myfilesystem",file_path="myfile")file.create_file()file.append_data(data,offset=0,length=len(data))file.flush_data(len(data))Downloading a fileDownload a file from your file system.fromazure.storage.filedatalakeimportDataLakeFileClientfile=DataLakeFileClient.from_connection_string("my_connection_string",file_system_name="myfilesystem",file_path="myfile")withopen("./BlockDestination.txt","wb")asmy_file:download=file.download_file()download.readinto(my_file)Enumerating pathsList the paths in your file system.fromazure.storage.filedatalakeimportFileSystemClientfile_system=FileSystemClient.from_connection_string("my_connection_string",file_system_name="myfilesystem")paths=file_system.get_paths()forpathinpaths:print(path.name+'\n')Optional ConfigurationOptional keyword arguments that can be passed in at the client and per-operation level.Retry Policy configurationUse the following keyword arguments when instantiating a client to configure the retry policy:retry_total(int): Total number of retries to allow. Takes precedence over other counts.
Pass inretry_total=0if you do not want to retry on requests. Defaults to 10.retry_connect(int): How many connection-related errors to retry on. Defaults to 3.retry_read(int): How many times to retry on read errors. Defaults to 3.retry_status(int): How many times to retry on bad status codes. Defaults to 3.retry_to_secondary(bool): Whether the request should be retried to secondary, if able.
This should only be enabled of RA-GRS accounts are used and potentially stale data can be handled.
Defaults toFalse.Other client / per-operation configurationOther optional configuration keyword arguments that can be specified on the client or per-operation.Client keyword arguments:connection_timeout(int): The number of seconds the client will wait to establish a connection to the server.
Defaults to 20 seconds.read_timeout(int): The number of seconds the client will wait, between consecutive read operations, for a
response from the server. This is a socket level timeout and is not affected by overall data size. Client-side read
timeouts will be automatically retried. Defaults to 60 seconds.transport(Any): User-provided transport to send the HTTP request.Per-operation keyword arguments:raw_response_hook(callable): The given callback uses the response returned from the service.raw_request_hook(callable): The given callback uses the request before being sent to service.client_request_id(str): Optional user specified identification of the request.user_agent(str): Appends the custom value to the user-agent header to be sent with the request.logging_enable(bool): Enables logging at the DEBUG level. Defaults to False. Can also be passed in at
the client level to enable it for all requests.logging_body(bool): Enables logging the request and response body. Defaults to False. Can also be passed in at
the client level to enable it for all requests.headers(dict): Pass in custom headers as key, value pairs. E.g.headers={'CustomValue': value}TroubleshootingGeneralDataLake Storage clients raise exceptions defined inAzure Core.This list can be used for reference to catch thrown exceptions. To get the specific error code of the exception, use theerror_codeattribute, i.e,exception.error_code.LoggingThis library uses the standardlogginglibrary for logging.
Basic information about HTTP sessions (URLs, headers, etc.) is logged at INFO
level.Detailed DEBUG level logging, including request/response bodies and unredacted
headers, can be enabled on a client with thelogging_enableargument:importsysimportloggingfromazure.storage.filedatalakeimportDataLakeServiceClient# Create a logger for the 'azure.storage.filedatalake' SDKlogger=logging.getLogger('azure.storage')logger.setLevel(logging.DEBUG)# Configure a console outputhandler=logging.StreamHandler(stream=sys.stdout)logger.addHandler(handler)# This client will log detailed information about its HTTP sessions, at DEBUG levelservice_client=DataLakeServiceClient.from_connection_string("your_connection_string",logging_enable=True)Similarly,logging_enablecan enable detailed logging for a single operation,
even when it isn't enabled for the client:service_client.list_file_systems(logging_enable=True)Next stepsMore sample codeGet started with ourAzure DataLake samples.Several DataLake Storage Python SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with DataLake Storage:datalake_samples_access_control.py- Examples for common DataLake Storage tasks:Set up a file systemCreate a directorySet/Get access control for the directoryCreate files under the directorySet/Get access control for each fileDelete file systemdatalake_samples_upload_download.py- Examples for common DataLake Storage tasks:Set up a file systemCreate fileAppend data to the fileFlush data to the fileDownload the uploaded dataDelete file systemAdditional documentationTable forADLS Gen1 to ADLS Gen2 API MappingFor more extensive REST documentation on Data Lake Storage Gen2, see theData Lake Storage Gen2 documentationon docs.microsoft.com.ContributingThis project welcomes contributions and suggestions.  Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct. For more information see theCode of Conduct FAQor contactopencode@microsoft.comwith any additional questions or comments.