Develop Python Jobs

更新时间:
复制 MD 格式

This topic describes the background information, limits, development methods, debugging methods, and connector usage for Flink Python API jobs.

Background information

You must develop Flink Python jobs locally. After the development is complete, deploy and start the jobs on the Flink development console to view the business results. For more information about the overall procedure, see Flink Python jobs.

Development environment requirements

  • Realtime Compute for Apache Flink engine versions earlier than VVR 8.0.11 come with Python 3.7.9 pre-installed. VVR 8.0.11 and later come with Python 3.9.21 pre-installed. VVR 11.7 and later come with Python 3.9.21, 3.10.19, and 3.11.14 pre-installed.

    Note

    We recommend that the Python version in your local development environment matches the Python version pre-installed with the target VVR engine.

    Note

    VVR 11.7 and later use Python 3.9 by default. If you want to use the pre-installed Python 3.10 or 3.11, configure the job as follows:

    1. On the O&M Center > Job O&M page, click the name of the target job.

    2. On the Deployment Details tab, in the Running Parameters section, click Edit on the right side, and add the following configuration in the Additional Configuration field (using Python 3.11 as an example):

      python.executable: python3.11
      python.client.executable: python3.11
  • PyFlink is installed, and its version matches the target VVR engine version. For example, if the engine you selected on the deployment page is vvr-11.7.0-jdk11-flink-1.20, you need to install:

    pip install ververica-flink==11.7.0
    Note

    VVR 11.5 and earlier do not provide a dedicated PyFlink package. You need to install the corresponding version of the open source PyFlink. For example, if the engine you selected on the deployment page is vvr-8.0.9-flink-1.17, you need to install apache-flink==1.17.*.

    pip install apache-flink==1.17.2
  • An IDE is installed. PyCharm or VS Code is recommended.

  • You must develop Python jobs locally, and then deploy and run them on the Realtime Compute for Apache Flink console.

Limits

Due to the impact of deployment environments and network environments on Flink, take note of the following limits when you develop Python jobs:

  • Only open source Flink V1.13 and later are supported.

  • The Flink workspace comes with a pre-installed Python environment, which includes commonly used Python libraries such as Pandas, NumPy, and PyArrow. For details, see Pre-installed package list at the end of this topic.

  • The Flink runtime environment supports only JDK 8 and JDK 11. If your Python job depends on third-party JAR packages, make sure that the JAR packages are compatible.

  • VVR 4.x supports only open source Scala V2.11. VVR 6.x and later support only open source Scala V2.12. If your Python job depends on third-party JAR packages, make sure that the JAR package dependencies match the corresponding Scala version.

Job development

Choosing between Table API/SQL and DataStream API

PyFlink supports two development approaches: Table API/SQL and DataStream API. Table API/SQL is recommended for the following reasons:

  • Better performance: The optimized execution plan of Table API/SQL runs entirely within the JVM. In contrast, DataStream API requires row-by-row serialization and deserialization between the JVM and the Python process, which introduces significant performance overhead.

  • More comprehensive features: Table API/SQL provides more complete support for connectors, data formats, and window functions, and shares the same connector ecosystem as SQL jobs.

  • Community recommendation: The Apache Flink community prioritizes Table API/SQL as the primary development direction for PyFlink.

Use DataStream API only for complex custom logic scenarios that cannot be expressed in SQL.

Development references

You can refer to the following documents to develop Flink business code locally. After development is complete, upload the code to the Flink development console and deploy the job.

Project structure

The recommended project structure for Python jobs is as follows:

my-flink-python-project/
├── my_job.py                # 主作业文件
├── udfs.py                  # 自定义函数(可选)
├── requirements.txt         # 第三方Python依赖(可选)
└── config.properties        # 配置文件(可选)

Dependency management

For information about how to use custom Python virtual environments, third-party Python packages, JAR files, and data files in Python jobs, see Use Python dependencies.

User-defined functions (UDFs)

The following is a development example of a Python UDSF that masks sensitive string data:

from pyflink.table import DataTypes
from pyflink.table.udf import udf

@udf(result_type=DataTypes.STRING())def mask_phone(phone: str):"""手机号脱敏:保留前3位和后4位,中间用****替代"""if phone is None or len(phone) != 11:return phone
    return phone[:3] + '****' + phone[7:]

Use this UDF in a SQL job:

CREATE TEMPORARY FUNCTION mask_phone AS 'udfs.mask_phone' LANGUAGE PYTHON;INSERT INTO sink_table
SELECT name, mask_phone(phone) AS masked_phone
FROM source_table;

For information about how to register, update, and delete UDFs, see Manage UDFs.

Use connectors

For the list of connectors supported by Flink, see Supported connectors. To use a connector, perform the following steps:

  1. Log on to the Realtime Compute console.

  2. Click Console in the Actions column of the target workspace.

  3. In the left-side navigation pane, click File Management.

  4. Click Upload Resource and select the Python package of the target connector to upload.

    You can upload a self-developed connector or a connector provided by Flink. To download the official Python packages of connectors provided by Flink, see Connector list.

  5. On the O&M Center > Job O&M page, click Create Deployment > Python Deployment. Select the Python package of the target connector for the Additional Dependencies field, configure other parameters, and deploy the job.

  6. Click the name of the deployed job. In the Deployment Details tab, in the Running Parameters section, click Edit. In Additional Configuration, add the location information of the Python connector packages.

    If your job depends on multiple connector Python packages, for example, two packages named connector-1.jar and connector-2.jar, the configuration is as follows.

    pipeline.classpaths: 'file:///flink/usrlib/connector-1.jar;file:///flink/usrlib/connector-2.jar'
  7. To use built-in connectors, data formats, and catalogs (VVR 11.2 and later only), add the configuration in the Running Parameters section under Additional Configuration of the job. Example:

    ## 多个连接器使用
    pipeline.used-builtin-connectors: kafka;sls
    ## 传输数据的多种数据格式
    pipeline.used-builtin-formats: avro;parquet
    ## 使用了多个已经创建的Catalog
    pipeline.used-builtin-catalogs: catalogname1;catalogname2

For details about how to use connectors, see Complete sample code.

Job debugging

You can use logging in the code implementation of Python UDFs to output log information for troubleshooting. Example:

import logging

@udf(result_type=DataTypes.BIGINT())
def add(i, j):
  logging.info("hello world")
  return i + j

After log output, you can view the logs in the TaskManager log files.

Local debugging

Because Realtime Compute for Apache Flink does not have Internet access by default, your code may not be able to directly connect to online data sources for testing locally. We recommend the following approaches for local debugging:

  • Unit testing: Perform independent unit tests on UDFs to ensure that the function logic is correct.

  • Local execution: Use local data sources (such as files or in-memory data) to simulate inputs, and run the job locally to verify the processing logic. Example:

    from pyflink.datastream import StreamExecutionEnvironment
    
    env = StreamExecutionEnvironment.get_execution_environment()# 使用本地数据源进行测试
    ds = env.from_collection([('Alice', 1), ('Bob', 2), ('Alice', 3)])
    ds.key_by(lambda x: x[0]).sum(1).print()
    env.execute("local_test")
  • Remote debugging: To debug by connecting to online data sources, see Run and debug jobs with connectors locally.

Job deployment

After the Python job development is complete, upload the job to the Realtime Compute console for deployment. Perform the following steps:

  1. Log on to the Realtime Compute console and go to the target workspace.

  2. In the left-side navigation pane, click File Management and upload the Python job file (.py or .zip). If there are third-party dependencies or configuration files, upload them as well.

  3. On the O&M Center > Job O&M page, click Create Deployment > Python Deployment and fill in the deployment information.

    Parameter

    Description

    Python File Path

    Select the uploaded Python job file.

    Entry Module

    If the job file is a .py file, this field is not required. If the job file is a .zip file, specify the entry module name, for example, my_job.

    Additional Dependencies

    Select connector JAR files or configuration files if applicable.

    Python Libraries

    Select third-party Python packages (.whl or .zip) if applicable.

    Python Archives

    Select a custom Python virtual environment (.zip) if applicable.

  4. Click Deploy.

For more information about deployment parameters, see Deploy a job.

Complete sample code

This example demonstrates a Python streaming job that reads data from Kafka, performs simple processing, and writes the results to MySQL. This is for reference only.

Note

This example does not include the configuration of running parameters such as checkpoints and restart strategies. You can customize these configurations on the Deployment Details page after deploying the job. For more information, see Configure job deployment information.

import logging
import sys

from pyflink.common import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.table import StreamTableEnvironment

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

def kafka_to_mysql():
    # 创建执行环境
    env = StreamExecutionEnvironment.get_execution_environment()
    t_env = StreamTableEnvironment.create(env)

    # 创建 Kafka 源表
    t_env.execute_sql("""
        CREATE TABLE kafka_source (
            `id` INT,
            `name` STRING,
            `score` INT,
            `event_time` TIMESTAMP(3),
            WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
        ) WITH (
            'connector' = 'kafka',
            'topic' = 'student_topic',
            'properties.bootstrap.servers' = 'your-kafka-broker:9092',
            'properties.group.id' = 'my-group',
            'scan.startup.mode' = 'latest-offset',
            'format' = 'json'
        )
    """)

    # 创建 MySQL 结果表
    t_env.execute_sql("""
        CREATE TABLE mysql_sink (
            `id` INT,
            `name` STRING,
            `score` INT,
            PRIMARY KEY (id) NOT ENFORCED
        ) WITH (
            'connector' = 'jdbc',
            'url' = 'jdbc:mysql://your-mysql-host:3306/my_database',
            'table-name' = 'student',
            'username' = 'your_username',
            'password' = 'your_password'
        )
    """)

    # 筛选分数大于60的记录并写入 MySQL
    t_env.execute_sql("""
        INSERT INTO mysql_sink
        SELECT id, name, score
        FROM kafka_source
        WHERE score >= 60
    """)

if __name__ == '__main__':
    kafka_to_mysql()

Pre-installed packages

VVR-11

The following packages are pre-installed in the Flink workspace.

Package

Version

apache-beam

2.48.0

avro-python3

1.10.2

brotlipy

0.7.0

certifi

2022.12.7

cffi

1.15.1

charset-normalizer

2.0.4

cloudpickle

2.2.1

conda

22.11.1

conda-content-trust

0.1.3

conda-package-handling

1.9.0

crcmod

1.7

cryptography

38.0.1

Cython

3.0.12

dill

0.3.1.1

dnspython

2.7.0

docopt

0.6.2

exceptiongroup

1.3.0

fastavro

1.12.1

fasteners

0.20

find_libpython

0.5.0

grpcio

1.56.2

grpcio-tools

1.56.2

hdfs

2.7.3

httplib2

0.22.0

idna

3.4

importlib_metadata

8.7.0

iniconfig

2.1.0

isort

6.1.0

numpy

1.24.4

objsize

0.6.1

orjson

3.9.15

packaging

25.0

pandas

2.3.3

pemja

0.5.5

pip

22.3.1

pluggy

1.0.0

proto-plus

1.26.1

protobuf

4.25.8

py-spy

0.4.0

py4j

0.10.9.7

pyarrow

11.0.0

pyarrow-hotfix

0.6

pycodestyle

2.14.0

pycosat

0.6.4

pycparser

2.21

pydot

1.4.2

pymongo

4.15.4

pyOpenSSL

22.0.0

pyparsing

3.2.5

PySocks

1.7.1

pytest

7.4.4

python-dateutil

2.9.0

pytz

2025.2

regex

2025.11.3

requests

2.32.5

ruamel.yaml

0.18.16

ruamel.yaml.clib

0.2.14

setuptools

70.0.0

six

1.16.0

tomli

2.3.0

toolz

0.12.0

tqdm

4.64.1

typing_extensions

4.15.0

tzdata

2025.2

urllib3

1.26.13

wheel

0.38.4

zipp

3.23.0

zstandard

0.25.0

torch

2.5.1

torchvision

0.20.1

transformers

4.57.6

opencv-python-headless

4.10.0.84

pillow

11.3.0

ultralytics

8.4.66

easyocr

1.7.2

open-clip-torch

2.32.0

rembg

2.0.61

onnxruntime

1.16.3

av

14.2.0

librosa

0.11.0

soundfile

0.13.1

imagehash

4.3.2

safetensors

0.7.0

huggingface-hub

0.36.2

tokenizers

0.22.2

timm

1.0.27

scikit-learn

1.6.1

scikit-image

0.24.0

scipy

1.13.1

numba

0.60.0

llvmlite

0.43.0

matplotlib

3.9.4

pywavelets

1.6.0

tifffile

2024.8.30

shapely

2.0.7

pymatting

1.1.15

audioread

3.1.0

soxr

0.5.0.post1

joblib

1.5.3

threadpoolctl

3.6.0

sympy

1.13.1

mpmath

1.3.0

python-bidi

0.6.10

filelock

3.19.1

pyyaml

6.0.3

decorator

5.3.1

msgpack

1.1.2

ftfy

6.3.1

wcwidth

0.8.1

contourpy

1.3.0

cycler

0.12.1

fonttools

4.60.2

importlib-resources

5.4.0

kiwisolver

1.4.7

lazy-loader

0.5

attrs

26.1.0

jsonschema

4.25.1

jsonschema-specifications

2025.9.1

referencing

0.36.2

rpds-py

0.27.1

pooch

1.9.0

platformdirs

4.4.0

VVR-8

The following packages are pre-installed in the Flink workspace.

Package

Version

apache-beam

2.43.0

avro-python3

1.9.2.1

certifi

2025.7.9

charset-normalizer

3.4.2

cloudpickle

2.2.0

crcmod

1.7

Cython

0.29.24

dill

0.3.1.1

docopt

0.6.2

fastavro

1.4.7

fasteners

0.19

find_libpython

0.4.1

grpcio

1.46.3

grpcio-tools

1.46.3

hdfs

2.7.3

httplib2

0.20.4

idna

3.10

isort

6.0.1

numpy

1.21.6

objsize

0.5.2

orjson

3.10.18

pandas

1.3.5

pemja

0.3.2

pip

22.3.1

proto-plus

1.26.1

protobuf

3.20.3

py4j

0.10.9.7

pyarrow

8.0.0

pycodestyle

2.14.0

pydot

1.4.2

pymongo

3.13.0

pyparsing

3.2.3

python-dateutil

2.9.0

pytz

2025.2

regex

2024.11.6

requests

2.32.4

setuptools

58.1.0

six

1.17.0

typing_extensions

4.14.1

urllib3

2.5.0

wheel

0.33.4

zstandard

0.23.0

VVR-6

The following packages are pre-installed in the Flink workspace.

Package

Version

apache-beam

2.27.0

avro-python3

1.9.2.1

certifi

2024.8.30

charset-normalizer

3.3.2

cloudpickle

1.2.2

crcmod

1.7

Cython

0.29.16

dill

0.3.1.1

docopt

0.6.2

fastavro

0.23.6

future

0.18.3

grpcio

1.29.0

hdfs

2.7.3

httplib2

0.17.4

idna

3.8

importlib-metadata

6.7.0

isort

5.11.5

jsonpickle

2.0.0

mock

2.0.0

numpy

1.19.5

oauth2client

4.1.3

pandas

1.1.5

pbr

6.1.0

pemja

0.1.4

pip

20.1.1

protobuf

3.17.3

py4j

0.10.9.3

pyarrow

2.0.0

pyasn1

0.5.1

pyasn1-modules

0.3.0

pycodestyle

2.10.0

pydot

1.4.2

pymongo

3.13.0

pyparsing

3.1.4

python-dateutil

2.8.0

pytz

2024.1

requests

2.31.0

rsa

4.9

setuptools

47.1.0

six

1.16.0

typing-extensions

3.7.4.3

urllib3

2.0.7

wheel

0.42.0

zipp

3.15.0

References

  • For a complete development workflow example of Flink Python jobs, see Flink Python jobs.

  • For information about using custom Python virtual environments, third-party Python packages, JAR files, and data files in Flink Python jobs, see Use Python dependencies.

  • Realtime Compute for Apache Flink also supports SQL and DataStream jobs. For more information, see Job development guide and Develop JAR jobs.