К основному содержанию
скилл

azure-storage-file-datalake-py — скилл для Claude Code

Скилл помогает писать Python-код для Azure Data Lake Storage Gen2: работать с файловыми системами, каталогами и файлами. Пригодится для операций с данными в ADLS Gen2.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add microsoft/skills --skill azure-storage-file-datalake-py -a claude-code
Открыть на GitHub

Что делает azure-storage-file-datalake-py

Скилл описывает работу с Azure Data Lake Storage Gen2 через Python SDK azure-storage-file-datalake. В нём разобраны клиенты для уровня аккаунта, файловой системы, каталога и файла, а также создание и удаление объектов, загрузка и скачивание, просмотр содержимого и ACL.

Есть примеры синхронного и асинхронного кода. Скилл рекомендует DefaultAzureCredential и контекстные менеджеры для клиентов и учётных данных. Для установки SDK нужны azure-storage-file-datalake и azure-identity; адрес аккаунта задаётся через AZURE_STORAGE_ACCOUNT_URL. Без него подключение не настроить. В production для DefaultAzureCredential также требуется AZURE_TOKEN_CREDENTIALS=prod либо имя конкретных учётных данных.

Какие задачи решает

  • создать файловую систему в ADLS Gen2
  • загрузить файл или блоки данных в хранилище
  • скачать файл целиком или диапазон байтов
  • перечислить файлы и каталоги, в том числе рекурсивно
  • прочитать или изменить ACL каталога

Примеры запросов агенту

  • Напиши Python-код, который создаёт файловую систему в Azure Data Lake Storage Gen2 и загружает в неё локальный файл.
  • Покажи, как рекурсивно перечислить файлы в каталоге ADLS Gen2 и скачать один из них.
  • Сделай асинхронный пример загрузки и скачивания файла через SDK Azure Data Lake Storage.

Как установить azure-storage-file-datalake-py

1Через Skills CLI (Vercel)

npx skills add microsoft/skills --skill azure-storage-file-datalake-py -a claude-code

2Вручную: положить файлы

~/.claude/skills/azure-storage-file-datalake-py/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/azure-storage-file-datalake-py/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о azure-storage-file-datalake-py

Как установить azure-storage-file-datalake-py в Claude Code?

Выполни npx skills add microsoft/skills --skill azure-storage-file-datalake-py -a claude-code. Файл скилла находится по пути ~/.claude/skills/azure-storage-file-datalake-py/SKILL.md.

Что делает azure-storage-file-datalake-py?

Скилл помогает использовать Python SDK для Azure Data Lake Storage Gen2. Он охватывает операции с файловыми системами, каталогами и файлами, а также ACL и асинхронный клиент.

Какие пакеты и настройки нужны для работы с SDK?

В примерах устанавливаются azure-storage-file-datalake и azure-identity. Для подключения нужен AZURE_STORAGE_ACCOUNT_URL; в production при использовании DefaultAzureCredential задаётся AZURE_TOKEN_CREDENTIALS=prod или конкретное имя учётных данных.

Исходный текст

SKILL.md · MIT
---
name: azure-storage-file-datalake-py
description: |
  Azure Data Lake Storage Gen2 SDK for Python. Use for hierarchical file systems, big data analytics, and file/directory operations.
  Triggers: "data lake", "DataLakeServiceClient", "FileSystemClient", "ADLS Gen2", "hierarchical namespace".
license: MIT
metadata:
  author: Microsoft
  version: "1.0.0"
  package: azure-storage-file-datalake
---

# Azure Data Lake Storage Gen2 SDK for Python

Hierarchical file system for big data analytics workloads.

## Installation

```bash
pip install azure-storage-file-datalake azure-identity
```

## Environment Variables

```bash
AZURE_STORAGE_ACCOUNT_URL=https://<account>.dfs.core.windows.net  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.storage.filedatalake import DataLakeServiceClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
account_url = "https://<account>.dfs.core.windows.net"

with DataLakeServiceClient(account_url=account_url, credential=credential) as service_client:
    # Use service_client here (see following sections for operations)
    ...
```

## Client Hierarchy

| Client | Purpose |
|--------|---------|
| `DataLakeServiceClient` | Account-level operations |
| `FileSystemClient` | Container (file system) operations |
| `DataLakeDirectoryClient` | Directory operations |
| `DataLakeFileClient` | File operations |

## File System Operations

```python
# Create file system (container)
file_system_client = service_client.create_file_system("myfilesystem")

# Get existing
file_system_client = service_client.get_file_system_client("myfilesystem")

# Delete
service_client.delete_file_system("myfilesystem")

# List file systems
for fs in service_client.list_file_systems():
    print(fs.name)
```

## Directory Operations

```python
file_system_client = service_client.get_file_system_client("myfilesystem")

# Create directory
directory_client = file_system_client.create_directory("mydir")

# Create nested directories
directory_client = file_system_client.create_directory("path/to/nested/dir")

# Get directory client
directory_client = file_system_client.get_directory_client("mydir")

# Delete directory
directory_client.delete_directory()

# Rename/move directory
directory_client.rename_directory(new_name="myfilesystem/newname")
```

## File Operations

### Upload File

```python
# Get file client
file_client = file_system_client.get_file_client("path/to/file.txt")

# Upload from local file
with open("local-file.txt", "rb") as data:
    file_client.upload_data(data, overwrite=True)

# Upload bytes
file_client.upload_data(b"Hello, Data Lake!", overwrite=True)

# Append data (for large files)
file_client.append_data(data=b"chunk1", offset=0, length=6)
file_client.append_data(data=b"chunk2", offset=6, length=6)
file_client.flush_data(12)  # Commit the data
```

### Download File

```python
file_client = file_system_client.get_file_client("path/to/file.txt")

# Download all content
download = file_client.download_file()
content = download.readall()

# Download to file
with open("downloaded.txt", "wb") as f:
    download = file_client.download_file()
    download.readinto(f)

# Download range
download = file_client.download_file(offset=0, length=100)
```

### Delete File

```python
file_client.delete_file()
```

## List Contents

```python
# List paths (files and directories)
for path in file_system_client.get_paths():
    print(f"{'DIR' if path.is_directory else 'FILE'}: {path.name}")

# List paths in directory
for path in file_system_client.get_paths(path="mydir"):
    print(path.name)

# Recursive listing
for path in file_system_client.get_paths(path="mydir", recursive=True):
    print(path.name)
```

## File/Directory Properties

```python
# Get properties
properties = file_client.get_file_properties()
print(f"Size: {properties.size}")
print(f"Last modified: {properties.last_modified}")

# Set metadata
file_client.set_metadata(metadata={"processed": "true"})
```

## Access Control (ACL)

```python
# Get ACL
acl = directory_client.get_access_control()
print(f"Owner: {acl['owner']}")
print(f"Permissions: {acl['permissions']}")

# Set ACL
directory_client.set_access_control(
    owner="user-id",
    permissions="rwxr-x---"
)

# Update ACL entries
from azure.storage.filedatalake import AccessControlChangeResult
directory_client.update_access_control_recursive(
    acl="user:user-id:rwx"
)
```

## Async Client

```python
from azure.storage.filedatalake.aio import DataLakeServiceClient
from azure.identity.aio import DefaultAzureCredential

async def datalake_operations():
    async with DefaultAzureCredential() as credential:
        async with DataLakeServiceClient(
            account_url="https://<account>.dfs.core.windows.net",
            credential=credential
        ) as service_client:
            file_system_client = service_client.get_file_system_client("myfilesystem")
            file_client = file_system_client.get_file_client("test.txt")
            
            await file_client.upload_data(b"async content", overwrite=True)
            
            download = await file_client.download_file()
            content = await download.readall()

import asyncio
asyncio.run(datalake_operations())
```

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.storage.filedatalake` sync clients with `azure.storage.filedatalake.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with DataLakeServiceClient(...) as client:` (sync) or `async with DataLakeServiceClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
4. **Use hierarchical namespace** for file system semantics
5. **Use `append_data` + `flush_data`** for large file uploads
6. **Set ACLs at directory level** and inherit to children
7. **Use async client** for high-throughput scenarios
8. **Use `get_paths` with `recursive=True`** for full directory listing
9. **Set metadata** for custom file attributes
10. **Consider Blob API** for simple object storage use cases

## Reference Files

| File | Contents |
|------|----------|
| [references/capabilities.md](references/capabilities.md) | Additional non-hero capabilities, operation-group coverage, and production checklists. |
| [references/non-hero-scenarios.md](references/non-hero-scenarios.md) | Dedicated non-hero examples for secondary/advanced scenarios. |

© Microsoft · MIT · microsoft/skills

Похожие скиллы

Все скиллы по теме «Облака: AWS, Azure, GCP» →
caveman-manage JuliusBrussee Проверяет состояние и результаты экспериментов Caveman Cloud, предлагает одно действие или блокирует рискованный запрос. Нужен перед запуском, одобрением, отменой или откатом. CX Codex +1 104 200установок workers-best-practices cloudflare Скилл настраивает ИИ на проверку продакшен-кода Cloudflare Workers по актуальным правилам рантайма, типам Wrangler и антипаттернам. CX Codex +1 126 100установок cloudflare-email-service cloudflare Скилл для работы с Cloudflare Email Sending и Email Routing: помогает настроить отправку и приём писем в Workers. CX Codex +1 102 300установок firebase-basics официальный google Скилл настраивает Firebase CLI, помогает войти в аккаунт, создать или выбрать проект и скачать конфигурацию Android или iOS. CX Codex 14 100установок cloudflare-one cloudflare Помогает агенту проектировать, настраивать и разбирать развёртывания Cloudflare One Zero Trust и SASE. Пригодится, когда нужно спланировать Access, Gateway или туннели без похода в документацию вручную. CX Codex +1 93 100установок cloudflare-one-migrations cloudflare Помогает спланировать переход с VPN, SWG или SASE на Cloudflare One: сопоставляет политики, находит пробелы и расписывает порядок выката. CX Codex +1 89 500установок

Из того же набора143

Весь набор →
azure-cosmos-ts Скилл для работы с Azure Cosmos DB через JavaScript/TypeScript SDK: CRUD документов, запросы, массовые операции. Пригодится, когда агент пишет код доступа к данным. 1установок azure-appconfiguration-ts Скилл учит агента работать с Azure App Configuration из TypeScript: настройки, фичефлаги, ссылки на Key Vault и динамическое обновление. 1установок azure-ai-projects-ts Подсказывает агенту, как работать с Azure AI Projects SDK для JavaScript: агенты, подключения, деплойменты, датасеты, индексы и оценки. 1установок azure-ai-contentsafety-ts Скилл помогает подключить Azure AI Content Safety из TypeScript-кода: проверять текст и изображения, а также вести списки запрещённых слов. 1установок azure-servicebus-py Скилл помогает писать код на Python для Azure Service Bus: отправлять и получать сообщения через очереди, топики и подписки. Пригодится при добавлении обмена сообщениями в приложение. 1установок azure-monitor-opentelemetry-exporter-py Скилл для низкоуровневой отправки трейсов, метрик и логов OpenTelemetry в Application Insights из Python. Пригодится, когда нужен свой конвейер телеметрии. 1установок azure-mgmt-apicenter-py Скилл помогает работать с Azure API Center через Python: вести каталог API, версии, определения, окружения и развёртывания. 1установок azure-messaging-webpubsubservice-py Скилл по Python SDK для Azure Web PubSub Service: рассылка сообщений по WebSocket, группы, токены доступа и управление подключениями. 1установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой