Sources de données Spark Python

VérifiéSûr

Construisez des sources de données personnalisées pour Apache Spark en utilisant l'API PySpark DataSource, en lecture et écriture par lots et en continu.

Spar Skills Guide Bot
Data & IAAvancé
26/07/2026
Claude CodeCursorCodex
#apache-spark#pyspark#data-source#connectors#streaming

Recommandé pour

Synthèse automatique

Guide la création de sources de données Python personnalisées pour Apache Spark 4.0+ via l'API PySpark DataSource, en lecture et écriture, batch comme streaming.

Points forts

  • Couvre les quatre modes (lecture/écriture batch et streaming) avec une structure d'héritage plate adaptée à la sérialisation PySpark
  • Rappelle les contraintes réelles du modèle driver/executor, notamment les imports de bibliothèques à placer dans les méthodes exécutées sur les workers
  • Propose des stratégies de partitionnement concrètes (temporelle, plage de tokens, plage d'ID) et une organisation de projet avec tests pytest-spark
  • Insiste sur la sobriété des dépendances, un point critique quand chaque paquet doit être installé sur tous les nœuds du cluster

Limites

  • Suppose une bonne connaissance préalable de Spark, du modèle driver/executor et de l'API DataSource
  • Ne fournit pas de code complet prêt à l'emploi dans le SKILL.md lui-même : l'essentiel renvoie à des fichiers de référence externes
  • La section sur l'authentification est tronquée et reste peu détaillée
Quand l'utiliser

À utiliser quand aucun connecteur natif n'existe et qu'il faut lire ou écrire des données dans un système externe depuis Spark en Python.

Quand l'éviter

À éviter si un connecteur Spark existant (JDBC, Kafka, Delta, etc.) couvre déjà le besoin ou si le travail se fait en Scala/Java.

Analyse de sécurité

Sûr
Score qualité82/100

This skill is pure instructional documentation for building PySpark DataSource connectors. It contains no executable commands beyond benign developer tooling (uv init, pytest, ruff), no destructive operations, no network exfiltration, no credential harvesting, and no safety-disabling instructions. The auth guidance discusses credential patterns abstractly but never instructs sending secrets anywhere. Execution risk is negligible.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Custom REST API connector
I need to read data from our internal REST API into a Spark DataFrame, but there's no native connector. Can you build a PySpark batch data source with pagination?
Streaming sink to a message queue
Write a PySpark streaming data source that pushes rows from a Structured Streaming query into our custom queue system.
Partitioned database reader
Build a Spark Python data source that reads from our Postgres table in parallel — partition by ID range and keep the dependencies minimal.

name: spark-python-data-source description: Build custom Python data sources for Apache Spark using the PySpark DataSource API — batch and streaming readers/writers for external systems. Use this skill whenever someone wants to connect Spark to an external system (database, API, message queue, custom protocol), build a Spark connector or plugin in Python, implement a DataSourceReader or DataSourceWriter, pull data from or push data to a system via Spark, or work with the PySpark DataSource API in any way. Even if they just say "read from X in Spark" or "write DataFrame to Y" and there's no native connector, this skill applies.

spark-python-data-source

Build custom Python data sources for Apache Spark 4.0+ to read from and write to external systems in batch and streaming modes.

Instructions

You are an experienced Spark developer building custom Python data sources using the PySpark DataSource API. Follow these principles and patterns.

Core Architecture

Each data source follows a flat, single-level inheritance structure:

  1. DataSource class — entry point that returns readers/writers
  2. Base Reader/Writer classes — shared logic for options and data processing
  3. Batch classes — inherit from base + DataSourceReader/DataSourceWriter
  4. Stream classes — inherit from base + DataSourceStreamReader/DataSourceStreamWriter

See implementation-template.md for the full annotated skeleton covering all four modes (batch read/write, stream read/write).

Spark-Specific Design Constraints

These are specific to the PySpark DataSource API and its driver/executor architecture — general Python best practices (clean code, minimal dependencies, no premature abstraction) still apply but aren't repeated here.

Flat single-level inheritance only. PySpark serializes reader/writer instances to ship them to executors. Complex inheritance hierarchies and abstract base classes break serialization and make cross-process debugging painful. Use one shared base class mixed with the PySpark interface (e.g., class YourBatchWriter(YourWriter, DataSourceWriter)).

Import third-party libraries inside executor methods. The read() and write() methods run on remote executor processes that don't share the driver's Python environment. Top-level imports from the driver won't be available on executors — always import libraries like requests or database drivers inside the methods that run on workers.

Minimize dependencies. Every package you add must be installed on all executor nodes in the cluster, not just the driver. Prefer the standard library; when external packages are needed, keep them few and well-known.

No async/await unless the external system's SDK is async-only. The PySpark DataSource API is synchronous, so async adds complexity with no benefit.

Project Setup

Create a Python project using a packaging tool such as uv, poetry, or hatch. Examples use uv (substitute your tool of choice):

uv init your-datasource
cd your-datasource
uv add pyspark pytest pytest-spark
your-datasource/
├── pyproject.toml
├── src/
│   └── your_datasource/
│       ├── __init__.py
│       └── datasource.py
└── tests/
    ├── conftest.py
    └── test_datasource.py

Run all commands through the packaging tool so they execute within the correct virtual environment:

uv run pytest                       # Run tests
uv run ruff check src/              # Lint
uv run ruff format src/             # Format
uv build                            # Build wheel

Key Implementation Decisions

Partitioning Strategy — choose based on data source characteristics:

  • Time-based: for APIs with temporal data
  • Token-range: for distributed databases
  • ID-range: for paginated APIs
  • See partitioning-patterns.md for implementations of each strategy

Authentication — support multiple methods in priority order:

  • Databricks Unity Catalog credentials
  • Cloud default credentials (managed identity)
  • Explicit credentials (service principal, API key, username/password)
  • See authentication-patterns.md for patterns with fallback chains

Type Conversion — map between Spark and external types:

  • Handle nulls, timestamps, UUIDs, collections
  • See type-conversion.md for bidirectional mapping tables and helpers

Streaming Offsets — design for exactly-once semantics:

  • JSON-serializable offset class
  • Non-overlapping partition boundaries
  • See streaming-patterns.md for offset tracking and watermark patterns

Error Handling — implement retries and resilience:

  • Exponential backoff for transient failures (network, rate limits)
  • Circuit breakers for cascading failures
  • See error-handling.md for retry decorators and failure classification

Testing

import pytest
from unittest.mock import patch, Mock

@pytest.fixture
def spark():
    from pyspark.sql import SparkSession
    return SparkSession.builder.master("local[2]").getOrCreate()

def test_data_source_name():
    assert YourDataSource.name() == "your-format"

def test_writer_sends_data(spark):
    with patch('requests.post') as mock_post:
        mock_post.return_value = Mock(status_code=200)

        df = spark.createDataFrame([(1, "test")], ["id", "value"])
        df.write.format("your-format").option("url", "http://api").save()

        assert mock_post.called

See testing-patterns.md for unit/integration test patterns, fixtures, and running tests.

Reference Implementations

Study these for real-world patterns:

Example Prompts

Create a Spark data source for reading from MongoDB with sharding support
Build a streaming connector for RabbitMQ with at-least-once delivery
Implement a batch writer for Snowflake with staged uploads
Write a data source for REST API with OAuth2 authentication and pagination

Related

  • databricks-testing: Test data sources on Databricks clusters
  • databricks-spark-declarative-pipelines: Use custom sources in DLT pipelines
  • python-dev: Python development best practices

References

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/spark-python-data-source-ms1aw5n1' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/spark-python-data-source-ms1aw5n1/download' --output '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md.part' && mv '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md.part' '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.claude/skills/spark-python-data-source'

Cursor
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.cursor/skills/spark-python-data-source'

Codex
test -f '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && test -s '.skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/spark-python-data-source' && cp -R '.skill-downloads/spark-python-data-source-ms1aw5n1' '.agents/skills/spark-python-data-source'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/spark-python-data-source-ms1aw5n1'

openskills read 'spark-python-data-source-ms1aw5n1'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/spark-python-data-source-ms1aw5n1/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires