apache-airflow-providers-standard 0.1.0rc1__py3-none-any.whl → 1.0.0.dev0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of apache-airflow-providers-standard might be problematic. Click here for more details.

Files changed (37) hide show
  1. airflow/providers/standard/LICENSE +52 -0
  2. airflow/providers/standard/__init__.py +1 -23
  3. airflow/providers/standard/get_provider_info.py +7 -54
  4. airflow/providers/standard/operators/datetime.py +3 -8
  5. airflow/providers/standard/operators/weekday.py +4 -11
  6. airflow/providers/standard/sensors/date_time.py +8 -32
  7. airflow/providers/standard/sensors/time.py +5 -28
  8. airflow/providers/standard/sensors/time_delta.py +10 -48
  9. airflow/providers/standard/sensors/weekday.py +2 -7
  10. {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/METADATA +36 -20
  11. apache_airflow_providers_standard-1.0.0.dev0.dist-info/RECORD +15 -0
  12. {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/WHEEL +1 -1
  13. airflow/providers/standard/hooks/__init__.py +0 -16
  14. airflow/providers/standard/hooks/filesystem.py +0 -89
  15. airflow/providers/standard/hooks/package_index.py +0 -95
  16. airflow/providers/standard/hooks/subprocess.py +0 -119
  17. airflow/providers/standard/operators/bash.py +0 -310
  18. airflow/providers/standard/operators/empty.py +0 -39
  19. airflow/providers/standard/operators/generic_transfer.py +0 -138
  20. airflow/providers/standard/operators/latest_only.py +0 -83
  21. airflow/providers/standard/operators/python.py +0 -1132
  22. airflow/providers/standard/operators/trigger_dagrun.py +0 -292
  23. airflow/providers/standard/sensors/bash.py +0 -120
  24. airflow/providers/standard/sensors/external_task.py +0 -509
  25. airflow/providers/standard/sensors/filesystem.py +0 -158
  26. airflow/providers/standard/sensors/python.py +0 -85
  27. airflow/providers/standard/triggers/__init__.py +0 -16
  28. airflow/providers/standard/triggers/external_task.py +0 -211
  29. airflow/providers/standard/triggers/file.py +0 -131
  30. airflow/providers/standard/triggers/temporal.py +0 -114
  31. airflow/providers/standard/utils/__init__.py +0 -16
  32. airflow/providers/standard/utils/python_virtualenv.py +0 -209
  33. airflow/providers/standard/utils/python_virtualenv_script.jinja2 +0 -77
  34. airflow/providers/standard/utils/sensor_helper.py +0 -119
  35. airflow/providers/standard/version_compat.py +0 -36
  36. apache_airflow_providers_standard-0.1.0rc1.dist-info/RECORD +0 -38
  37. {apache_airflow_providers_standard-0.1.0rc1.dist-info → apache_airflow_providers_standard-1.0.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -1,1132 +0,0 @@
1
- #
2
- # Licensed to the Apache Software Foundation (ASF) under one
3
- # or more contributor license agreements. See the NOTICE file
4
- # distributed with this work for additional information
5
- # regarding copyright ownership. The ASF licenses this file
6
- # to you under the Apache License, Version 2.0 (the
7
- # "License"); you may not use this file except in compliance
8
- # with the License. You may obtain a copy of the License at
9
- #
10
- # http://www.apache.org/licenses/LICENSE-2.0
11
- #
12
- # Unless required by applicable law or agreed to in writing,
13
- # software distributed under the License is distributed on an
14
- # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15
- # KIND, either express or implied. See the License for the
16
- # specific language governing permissions and limitations
17
- # under the License.
18
- from __future__ import annotations
19
-
20
- import inspect
21
- import json
22
- import logging
23
- import os
24
- import shutil
25
- import subprocess
26
- import sys
27
- import textwrap
28
- import types
29
- from abc import ABCMeta, abstractmethod
30
- from collections.abc import Collection, Container, Iterable, Mapping, Sequence
31
- from functools import cache
32
- from pathlib import Path
33
- from tempfile import TemporaryDirectory
34
- from typing import TYPE_CHECKING, Any, Callable, NamedTuple, cast
35
-
36
- import lazy_object_proxy
37
-
38
- from airflow.exceptions import (
39
- AirflowConfigException,
40
- AirflowException,
41
- AirflowSkipException,
42
- DeserializingResultError,
43
- )
44
- from airflow.models.baseoperator import BaseOperator
45
- from airflow.models.skipmixin import SkipMixin
46
- from airflow.models.variable import Variable
47
- from airflow.operators.branch import BranchMixIn
48
- from airflow.providers.standard.utils.python_virtualenv import prepare_virtualenv, write_python_script
49
- from airflow.providers.standard.version_compat import AIRFLOW_V_2_10_PLUS, AIRFLOW_V_3_0_PLUS
50
- from airflow.utils import hashlib_wrapper
51
- from airflow.utils.context import context_copy_partial, context_merge
52
- from airflow.utils.file import get_unique_dag_module_name
53
- from airflow.utils.operator_helpers import KeywordParameters
54
- from airflow.utils.process_utils import execute_in_subprocess, execute_in_subprocess_with_kwargs
55
-
56
- log = logging.getLogger(__name__)
57
-
58
- if TYPE_CHECKING:
59
- from typing import Literal
60
-
61
- from pendulum.datetime import DateTime
62
-
63
- try:
64
- from airflow.sdk.definitions.context import Context
65
- except ImportError:
66
- # TODO: Remove once provider drops support for Airflow 2
67
- from airflow.utils.context import Context
68
-
69
- _SerializerTypeDef = Literal["pickle", "cloudpickle", "dill"]
70
-
71
-
72
- @cache
73
- def _parse_version_info(text: str) -> tuple[int, int, int, str, int]:
74
- """Parse python version info from a text."""
75
- parts = text.strip().split(".")
76
- if len(parts) != 5:
77
- msg = f"Invalid Python version info, expected 5 components separated by '.', but got {text!r}."
78
- raise ValueError(msg)
79
- try:
80
- return int(parts[0]), int(parts[1]), int(parts[2]), parts[3], int(parts[4])
81
- except ValueError:
82
- msg = f"Unable to convert parts {parts} parsed from {text!r} to (int, int, int, str, int)."
83
- raise ValueError(msg) from None
84
-
85
-
86
- class _PythonVersionInfo(NamedTuple):
87
- """Provide the same interface as ``sys.version_info``."""
88
-
89
- major: int
90
- minor: int
91
- micro: int
92
- releaselevel: str
93
- serial: int
94
-
95
- @classmethod
96
- def from_executable(cls, executable: str) -> _PythonVersionInfo:
97
- """Parse python version info from an executable."""
98
- cmd = [executable, "-c", 'import sys; print(".".join(map(str, sys.version_info)))']
99
- try:
100
- result = subprocess.check_output(cmd, text=True)
101
- except Exception as e:
102
- raise ValueError(f"Error while executing command {cmd}: {e}")
103
- return cls(*_parse_version_info(result.strip()))
104
-
105
-
106
- class PythonOperator(BaseOperator):
107
- """
108
- Executes a Python callable.
109
-
110
- .. seealso::
111
- For more information on how to use this operator, take a look at the guide:
112
- :ref:`howto/operator:PythonOperator`
113
-
114
- When running your callable, Airflow will pass a set of keyword arguments that can be used in your
115
- function. This set of kwargs correspond exactly to what you can use in your jinja templates.
116
- For this to work, you need to define ``**kwargs`` in your function header, or you can add directly the
117
- keyword arguments you would like to get - for example with the below code your callable will get
118
- the values of ``ti`` context variables.
119
-
120
- With explicit arguments:
121
-
122
- .. code-block:: python
123
-
124
- def my_python_callable(ti):
125
- pass
126
-
127
- With kwargs:
128
-
129
- .. code-block:: python
130
-
131
- def my_python_callable(**kwargs):
132
- ti = kwargs["ti"]
133
-
134
-
135
- :param python_callable: A reference to an object that is callable
136
- :param op_args: a list of positional arguments that will get unpacked when
137
- calling your callable
138
- :param op_kwargs: a dictionary of keyword arguments that will get unpacked
139
- in your function
140
- :param templates_dict: a dictionary where the values are templates that
141
- will get templated by the Airflow engine sometime between
142
- ``__init__`` and ``execute`` takes place and are made available
143
- in your callable's context after the template has been applied. (templated)
144
- :param templates_exts: a list of file extensions to resolve while
145
- processing templated fields, for examples ``['.sql', '.hql']``
146
- :param show_return_value_in_logs: a bool value whether to show return_value
147
- logs. Defaults to True, which allows return value log output.
148
- It can be set to False to prevent log output of return value when you return huge data
149
- such as transmission a large amount of XCom to TaskAPI.
150
- """
151
-
152
- template_fields: Sequence[str] = ("templates_dict", "op_args", "op_kwargs")
153
- template_fields_renderers = {"templates_dict": "json", "op_args": "py", "op_kwargs": "py"}
154
- BLUE = "#ffefeb"
155
- ui_color = BLUE
156
-
157
- # since we won't mutate the arguments, we should just do the shallow copy
158
- # there are some cases we can't deepcopy the objects(e.g protobuf).
159
- shallow_copy_attrs: Sequence[str] = ("python_callable", "op_kwargs")
160
-
161
- def __init__(
162
- self,
163
- *,
164
- python_callable: Callable,
165
- op_args: Collection[Any] | None = None,
166
- op_kwargs: Mapping[str, Any] | None = None,
167
- templates_dict: dict[str, Any] | None = None,
168
- templates_exts: Sequence[str] | None = None,
169
- show_return_value_in_logs: bool = True,
170
- **kwargs,
171
- ) -> None:
172
- super().__init__(**kwargs)
173
- if not callable(python_callable):
174
- raise AirflowException("`python_callable` param must be callable")
175
- self.python_callable = python_callable
176
- self.op_args = op_args or ()
177
- self.op_kwargs = op_kwargs or {}
178
- self.templates_dict = templates_dict
179
- if templates_exts:
180
- self.template_ext = templates_exts
181
- self.show_return_value_in_logs = show_return_value_in_logs
182
-
183
- def execute(self, context: Context) -> Any:
184
- context_merge(context, self.op_kwargs, templates_dict=self.templates_dict)
185
- self.op_kwargs = self.determine_kwargs(context)
186
-
187
- if AIRFLOW_V_3_0_PLUS:
188
- from airflow.utils.context import context_get_outlet_events
189
-
190
- self._asset_events = context_get_outlet_events(context)
191
- elif AIRFLOW_V_2_10_PLUS:
192
- from airflow.utils.context import context_get_outlet_events
193
-
194
- self._dataset_events = context_get_outlet_events(context)
195
-
196
- return_value = self.execute_callable()
197
- if self.show_return_value_in_logs:
198
- self.log.info("Done. Returned value was: %s", return_value)
199
- else:
200
- self.log.info("Done. Returned value not shown")
201
-
202
- return return_value
203
-
204
- def determine_kwargs(self, context: Mapping[str, Any]) -> Mapping[str, Any]:
205
- return KeywordParameters.determine(self.python_callable, self.op_args, context).unpacking()
206
-
207
- def execute_callable(self) -> Any:
208
- """
209
- Call the python callable with the given arguments.
210
-
211
- :return: the return value of the call.
212
- """
213
- try:
214
- from airflow.utils.operator_helpers import ExecutionCallableRunner
215
-
216
- asset_events = self._asset_events if AIRFLOW_V_3_0_PLUS else self._dataset_events
217
-
218
- runner = ExecutionCallableRunner(self.python_callable, asset_events, logger=self.log)
219
- except ImportError:
220
- # Handle Pre Airflow 3.10 case where ExecutionCallableRunner was not available
221
- return self.python_callable(*self.op_args, **self.op_kwargs)
222
- return runner.run(*self.op_args, **self.op_kwargs)
223
-
224
-
225
- class BranchPythonOperator(PythonOperator, BranchMixIn):
226
- """
227
- A workflow can "branch" or follow a path after the execution of this task.
228
-
229
- It derives the PythonOperator and expects a Python function that returns
230
- a single task_id, a single task_group_id, or a list of task_ids and/or
231
- task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned
232
- should point to a task or task group directly downstream from {self}. All
233
- other "branches" or directly downstream tasks are marked with a state of
234
- ``skipped`` so that these paths can't move forward. The ``skipped`` states
235
- are propagated downstream to allow for the DAG state to fill up and
236
- the DAG run's state to be inferred.
237
- """
238
-
239
- def execute(self, context: Context) -> Any:
240
- return self.do_branch(context, super().execute(context))
241
-
242
-
243
- class ShortCircuitOperator(PythonOperator, SkipMixin):
244
- """
245
- Allows a pipeline to continue based on the result of a ``python_callable``.
246
-
247
- The ShortCircuitOperator is derived from the PythonOperator and evaluates the result of a
248
- ``python_callable``. If the returned result is False or a falsy value, the pipeline will be
249
- short-circuited. Downstream tasks will be marked with a state of "skipped" based on the short-circuiting
250
- mode configured. If the returned result is True or a truthy value, downstream tasks proceed as normal and
251
- an ``XCom`` of the returned result is pushed.
252
-
253
- The short-circuiting can be configured to either respect or ignore the ``trigger_rule`` set for
254
- downstream tasks. If ``ignore_downstream_trigger_rules`` is set to True, the default setting, all
255
- downstream tasks are skipped without considering the ``trigger_rule`` defined for tasks. However, if this
256
- parameter is set to False, the direct downstream tasks are skipped but the specified ``trigger_rule`` for
257
- other subsequent downstream tasks are respected. In this mode, the operator assumes the direct downstream
258
- tasks were purposely meant to be skipped but perhaps not other subsequent tasks.
259
-
260
- .. seealso::
261
- For more information on how to use this operator, take a look at the guide:
262
- :ref:`howto/operator:ShortCircuitOperator`
263
-
264
- :param ignore_downstream_trigger_rules: If set to True, all downstream tasks from this operator task will
265
- be skipped. This is the default behavior. If set to False, the direct, downstream task(s) will be
266
- skipped but the ``trigger_rule`` defined for all other downstream tasks will be respected.
267
- """
268
-
269
- def __init__(self, *, ignore_downstream_trigger_rules: bool = True, **kwargs) -> None:
270
- super().__init__(**kwargs)
271
- self.ignore_downstream_trigger_rules = ignore_downstream_trigger_rules
272
-
273
- def execute(self, context: Context) -> Any:
274
- condition = super().execute(context)
275
- self.log.info("Condition result is %s", condition)
276
-
277
- if condition:
278
- self.log.info("Proceeding with downstream tasks...")
279
- return condition
280
-
281
- if not self.downstream_task_ids:
282
- self.log.info("No downstream tasks; nothing to do.")
283
- return condition
284
-
285
- dag_run = context["dag_run"]
286
-
287
- def get_tasks_to_skip():
288
- if self.ignore_downstream_trigger_rules is True:
289
- tasks = context["task"].get_flat_relatives(upstream=False)
290
- else:
291
- tasks = context["task"].get_direct_relatives(upstream=False)
292
- for t in tasks:
293
- if not t.is_teardown:
294
- yield t
295
-
296
- to_skip = get_tasks_to_skip()
297
-
298
- # this let's us avoid an intermediate list unless debug logging
299
- if self.log.getEffectiveLevel() <= logging.DEBUG:
300
- self.log.debug("Downstream task IDs %s", to_skip := list(get_tasks_to_skip()))
301
-
302
- self.log.info("Skipping downstream tasks")
303
- if AIRFLOW_V_3_0_PLUS:
304
- self.skip(
305
- dag_id=dag_run.dag_id,
306
- run_id=dag_run.run_id,
307
- tasks=to_skip,
308
- map_index=context["ti"].map_index,
309
- )
310
- else:
311
- self.skip(
312
- dag_run=dag_run,
313
- tasks=to_skip,
314
- execution_date=cast("DateTime", dag_run.logical_date), # type: ignore[call-arg, union-attr]
315
- map_index=context["ti"].map_index,
316
- )
317
-
318
- self.log.info("Done.")
319
- # returns the result of the super execute method as it is instead of returning None
320
- return condition
321
-
322
-
323
- def _load_pickle():
324
- import pickle
325
-
326
- return pickle
327
-
328
-
329
- def _load_dill():
330
- try:
331
- import dill
332
- except ModuleNotFoundError:
333
- log.error("Unable to import `dill` module. Please please make sure that it installed.")
334
- raise
335
- return dill
336
-
337
-
338
- def _load_cloudpickle():
339
- try:
340
- import cloudpickle
341
- except ModuleNotFoundError:
342
- log.error(
343
- "Unable to import `cloudpickle` module. "
344
- "Please install it with: pip install 'apache-airflow[cloudpickle]'"
345
- )
346
- raise
347
- return cloudpickle
348
-
349
-
350
- _SERIALIZERS: dict[_SerializerTypeDef, Any] = {
351
- "pickle": lazy_object_proxy.Proxy(_load_pickle),
352
- "dill": lazy_object_proxy.Proxy(_load_dill),
353
- "cloudpickle": lazy_object_proxy.Proxy(_load_cloudpickle),
354
- }
355
-
356
-
357
- class _BasePythonVirtualenvOperator(PythonOperator, metaclass=ABCMeta):
358
- BASE_SERIALIZABLE_CONTEXT_KEYS = {
359
- "ds",
360
- "ds_nodash",
361
- "expanded_ti_count",
362
- "inlets",
363
- "outlets",
364
- "run_id",
365
- "task_instance_key_str",
366
- "test_mode",
367
- "ts",
368
- "ts_nodash",
369
- "ts_nodash_with_tz",
370
- # The following should be removed when Airflow 2 support is dropped.
371
- "next_ds",
372
- "next_ds_nodash",
373
- "prev_ds",
374
- "prev_ds_nodash",
375
- "tomorrow_ds",
376
- "tomorrow_ds_nodash",
377
- "yesterday_ds",
378
- "yesterday_ds_nodash",
379
- }
380
- if AIRFLOW_V_3_0_PLUS:
381
- BASE_SERIALIZABLE_CONTEXT_KEYS.add("task_reschedule_count")
382
-
383
- PENDULUM_SERIALIZABLE_CONTEXT_KEYS = {
384
- "data_interval_end",
385
- "data_interval_start",
386
- "logical_date",
387
- "prev_data_interval_end_success",
388
- "prev_data_interval_start_success",
389
- "prev_start_date_success",
390
- "prev_end_date_success",
391
- # The following should be removed when Airflow 2 support is dropped.
392
- "execution_date",
393
- "next_execution_date",
394
- "prev_execution_date",
395
- "prev_execution_date_success",
396
- }
397
- if AIRFLOW_V_3_0_PLUS:
398
- PENDULUM_SERIALIZABLE_CONTEXT_KEYS.add("start_date")
399
-
400
- AIRFLOW_SERIALIZABLE_CONTEXT_KEYS = {
401
- "macros",
402
- "conf",
403
- "dag",
404
- "dag_run",
405
- "task",
406
- "params",
407
- "triggering_asset_events",
408
- # The following should be removed when Airflow 2 support is dropped.
409
- "triggering_dataset_events",
410
- }
411
-
412
- def __init__(
413
- self,
414
- *,
415
- python_callable: Callable,
416
- serializer: _SerializerTypeDef | None = None,
417
- op_args: Collection[Any] | None = None,
418
- op_kwargs: Mapping[str, Any] | None = None,
419
- string_args: Iterable[str] | None = None,
420
- templates_dict: dict | None = None,
421
- templates_exts: list[str] | None = None,
422
- expect_airflow: bool = True,
423
- skip_on_exit_code: int | Container[int] | None = None,
424
- env_vars: dict[str, str] | None = None,
425
- inherit_env: bool = True,
426
- **kwargs,
427
- ):
428
- if (
429
- not isinstance(python_callable, types.FunctionType)
430
- or isinstance(python_callable, types.LambdaType)
431
- and python_callable.__name__ == "<lambda>"
432
- ):
433
- raise ValueError(f"{type(self).__name__} only supports functions for python_callable arg")
434
- if inspect.isgeneratorfunction(python_callable):
435
- raise ValueError(f"{type(self).__name__} does not support using 'yield' in python_callable")
436
- super().__init__(
437
- python_callable=python_callable,
438
- op_args=op_args,
439
- op_kwargs=op_kwargs,
440
- templates_dict=templates_dict,
441
- templates_exts=templates_exts,
442
- **kwargs,
443
- )
444
- self.string_args = string_args or []
445
-
446
- serializer = serializer or "pickle"
447
- if serializer not in _SERIALIZERS:
448
- msg = (
449
- f"Unsupported serializer {serializer!r}. "
450
- f"Expected one of {', '.join(map(repr, _SERIALIZERS))}"
451
- )
452
- raise AirflowException(msg)
453
-
454
- self.pickling_library = _SERIALIZERS[serializer]
455
- self.serializer: _SerializerTypeDef = serializer
456
-
457
- self.expect_airflow = expect_airflow
458
- self.skip_on_exit_code = (
459
- skip_on_exit_code
460
- if isinstance(skip_on_exit_code, Container)
461
- else [skip_on_exit_code]
462
- if skip_on_exit_code is not None
463
- else []
464
- )
465
- self.env_vars = env_vars
466
- self.inherit_env = inherit_env
467
-
468
- @abstractmethod
469
- def _iter_serializable_context_keys(self):
470
- pass
471
-
472
- def execute(self, context: Context) -> Any:
473
- serializable_keys = set(self._iter_serializable_context_keys())
474
- serializable_context = context_copy_partial(context, serializable_keys)
475
- return super().execute(context=serializable_context)
476
-
477
- def get_python_source(self):
478
- """Return the source of self.python_callable."""
479
- return textwrap.dedent(inspect.getsource(self.python_callable))
480
-
481
- def _write_args(self, file: Path):
482
- if self.op_args or self.op_kwargs:
483
- self.log.info("Use %r as serializer.", self.serializer)
484
- file.write_bytes(self.pickling_library.dumps({"args": self.op_args, "kwargs": self.op_kwargs}))
485
-
486
- def _write_string_args(self, file: Path):
487
- file.write_text("\n".join(map(str, self.string_args)))
488
-
489
- def _read_result(self, path: Path):
490
- if path.stat().st_size == 0:
491
- return None
492
- try:
493
- return self.pickling_library.loads(path.read_bytes())
494
- except ValueError as value_error:
495
- raise DeserializingResultError() from value_error
496
-
497
- def __deepcopy__(self, memo):
498
- # module objects can't be copied _at all__
499
- memo[id(self.pickling_library)] = self.pickling_library
500
- return super().__deepcopy__(memo)
501
-
502
- def _execute_python_callable_in_subprocess(self, python_path: Path):
503
- with TemporaryDirectory(prefix="venv-call") as tmp:
504
- tmp_dir = Path(tmp)
505
- op_kwargs: dict[str, Any] = dict(self.op_kwargs)
506
- if self.templates_dict:
507
- op_kwargs["templates_dict"] = self.templates_dict
508
- input_path = tmp_dir / "script.in"
509
- output_path = tmp_dir / "script.out"
510
- string_args_path = tmp_dir / "string_args.txt"
511
- script_path = tmp_dir / "script.py"
512
- termination_log_path = tmp_dir / "termination.log"
513
- airflow_context_path = tmp_dir / "airflow_context.json"
514
-
515
- self._write_args(input_path)
516
- self._write_string_args(string_args_path)
517
-
518
- jinja_context = {
519
- "op_args": self.op_args,
520
- "op_kwargs": op_kwargs,
521
- "expect_airflow": self.expect_airflow,
522
- "pickling_library": self.serializer,
523
- "python_callable": self.python_callable.__name__,
524
- "python_callable_source": self.get_python_source(),
525
- }
526
-
527
- if inspect.getfile(self.python_callable) == self.dag.fileloc:
528
- jinja_context["modified_dag_module_name"] = get_unique_dag_module_name(self.dag.fileloc)
529
-
530
- write_python_script(
531
- jinja_context=jinja_context,
532
- filename=os.fspath(script_path),
533
- render_template_as_native_obj=self.dag.render_template_as_native_obj,
534
- )
535
-
536
- env_vars = dict(os.environ) if self.inherit_env else {}
537
- if self.env_vars:
538
- env_vars.update(self.env_vars)
539
-
540
- try:
541
- cmd: list[str] = [
542
- os.fspath(python_path),
543
- os.fspath(script_path),
544
- os.fspath(input_path),
545
- os.fspath(output_path),
546
- os.fspath(string_args_path),
547
- os.fspath(termination_log_path),
548
- os.fspath(airflow_context_path),
549
- ]
550
- if AIRFLOW_V_2_10_PLUS:
551
- execute_in_subprocess(
552
- cmd=cmd,
553
- env=env_vars,
554
- )
555
- else:
556
- execute_in_subprocess_with_kwargs(
557
- cmd=cmd,
558
- env=env_vars,
559
- )
560
- except subprocess.CalledProcessError as e:
561
- if e.returncode in self.skip_on_exit_code:
562
- raise AirflowSkipException(f"Process exited with code {e.returncode}. Skipping.")
563
- elif termination_log_path.exists() and termination_log_path.stat().st_size > 0:
564
- error_msg = f"Process returned non-zero exit status {e.returncode}.\n"
565
- with open(termination_log_path) as file:
566
- error_msg += file.read()
567
- raise AirflowException(error_msg) from None
568
- else:
569
- raise
570
-
571
- if 0 in self.skip_on_exit_code:
572
- raise AirflowSkipException("Process exited with code 0. Skipping.")
573
-
574
- return self._read_result(output_path)
575
-
576
- def determine_kwargs(self, context: Mapping[str, Any]) -> Mapping[str, Any]:
577
- keyword_params = KeywordParameters.determine(self.python_callable, self.op_args, context)
578
- if AIRFLOW_V_3_0_PLUS:
579
- return keyword_params.unpacking()
580
- else:
581
- return keyword_params.serializing() # type: ignore[attr-defined]
582
-
583
-
584
- class PythonVirtualenvOperator(_BasePythonVirtualenvOperator):
585
- """
586
- Run a function in a virtualenv that is created and destroyed automatically.
587
-
588
- The function (has certain caveats) must be defined using def, and not be
589
- part of a class. All imports must happen inside the function
590
- and no variables outside the scope may be referenced. A global scope
591
- variable named virtualenv_string_args will be available (populated by
592
- string_args). In addition, one can pass stuff through op_args and op_kwargs, and one
593
- can use a return value.
594
- Note that if your virtualenv runs in a different Python major version than Airflow,
595
- you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to
596
- Airflow through plugins. You can use string_args though.
597
-
598
- .. seealso::
599
- For more information on how to use this operator, take a look at the guide:
600
- :ref:`howto/operator:PythonVirtualenvOperator`
601
-
602
- :param python_callable: A python function with no references to outside variables,
603
- defined with def, which will be run in a virtual environment.
604
- :param requirements: Either a list of requirement strings, or a (templated)
605
- "requirements file" as specified by pip.
606
- :param python_version: The Python version to run the virtual environment with. Note that
607
- both 2 and 2.7 are acceptable forms.
608
- :param serializer: Which serializer use to serialize the args and result. It can be one of the following:
609
-
610
- - ``"pickle"``: (default) Use pickle for serialization. Included in the Python Standard Library.
611
- - ``"cloudpickle"``: Use cloudpickle for serialize more complex types,
612
- this requires to include cloudpickle in your requirements.
613
- - ``"dill"``: Use dill for serialize more complex types,
614
- this requires to include dill in your requirements.
615
- :param system_site_packages: Whether to include
616
- system_site_packages in your virtual environment.
617
- See virtualenv documentation for more information.
618
- :param pip_install_options: a list of pip install options when installing requirements
619
- See 'pip install -h' for available options
620
- :param op_args: A list of positional arguments to pass to python_callable.
621
- :param op_kwargs: A dict of keyword arguments to pass to python_callable.
622
- :param string_args: Strings that are present in the global var virtualenv_string_args,
623
- available to python_callable at runtime as a list[str]. Note that args are split
624
- by newline.
625
- :param templates_dict: a dictionary where the values are templates that
626
- will get templated by the Airflow engine sometime between
627
- ``__init__`` and ``execute`` takes place and are made available
628
- in your callable's context after the template has been applied
629
- :param templates_exts: a list of file extensions to resolve while
630
- processing templated fields, for examples ``['.sql', '.hql']``
631
- :param expect_airflow: expect Airflow to be installed in the target environment. If true, the operator
632
- will raise warning if Airflow is not installed, and it will attempt to load Airflow
633
- macros when starting.
634
- :param skip_on_exit_code: If python_callable exits with this exit code, leave the task
635
- in ``skipped`` state (default: None). If set to ``None``, any non-zero
636
- exit code will be treated as a failure.
637
- :param index_urls: an optional list of index urls to load Python packages from.
638
- If not provided the system pip conf will be used to source packages from.
639
- :param venv_cache_path: Optional path to the virtual environment parent folder in which the
640
- virtual environment will be cached, creates a sub-folder venv-{hash} whereas hash will be replaced
641
- with a checksum of requirements. If not provided the virtual environment will be created and deleted
642
- in a temp folder for every execution.
643
- :param env_vars: A dictionary containing additional environment variables to set for the virtual
644
- environment when it is executed.
645
- :param inherit_env: Whether to inherit the current environment variables when executing the virtual
646
- environment. If set to ``True``, the virtual environment will inherit the environment variables
647
- of the parent process (``os.environ``). If set to ``False``, the virtual environment will be
648
- executed with a clean environment.
649
- """
650
-
651
- template_fields: Sequence[str] = tuple(
652
- {"requirements", "index_urls", "venv_cache_path"}.union(PythonOperator.template_fields)
653
- )
654
- template_ext: Sequence[str] = (".txt",)
655
-
656
- def __init__(
657
- self,
658
- *,
659
- python_callable: Callable,
660
- requirements: None | Iterable[str] | str = None,
661
- python_version: str | None = None,
662
- serializer: _SerializerTypeDef | None = None,
663
- system_site_packages: bool = True,
664
- pip_install_options: list[str] | None = None,
665
- op_args: Collection[Any] | None = None,
666
- op_kwargs: Mapping[str, Any] | None = None,
667
- string_args: Iterable[str] | None = None,
668
- templates_dict: dict | None = None,
669
- templates_exts: list[str] | None = None,
670
- expect_airflow: bool = True,
671
- skip_on_exit_code: int | Container[int] | None = None,
672
- index_urls: None | Collection[str] | str = None,
673
- venv_cache_path: None | os.PathLike[str] = None,
674
- env_vars: dict[str, str] | None = None,
675
- inherit_env: bool = True,
676
- **kwargs,
677
- ):
678
- if (
679
- python_version
680
- and str(python_version)[0] != str(sys.version_info.major)
681
- and (op_args or op_kwargs)
682
- ):
683
- raise AirflowException(
684
- "Passing op_args or op_kwargs is not supported across different Python "
685
- "major versions for PythonVirtualenvOperator. Please use string_args."
686
- f"Sys version: {sys.version_info}. Virtual environment version: {python_version}"
687
- )
688
- if python_version is not None and not isinstance(python_version, str):
689
- raise AirflowException(
690
- "Passing non-string types (e.g. int or float) as python_version not supported"
691
- )
692
- if not requirements:
693
- self.requirements: list[str] = []
694
- elif isinstance(requirements, str):
695
- self.requirements = [requirements]
696
- else:
697
- self.requirements = list(requirements)
698
- self.python_version = python_version
699
- self.system_site_packages = system_site_packages
700
- self.pip_install_options = pip_install_options
701
- if isinstance(index_urls, str):
702
- self.index_urls: list[str] | None = [index_urls]
703
- elif isinstance(index_urls, Collection):
704
- self.index_urls = list(index_urls)
705
- else:
706
- self.index_urls = None
707
- self.venv_cache_path = venv_cache_path
708
- super().__init__(
709
- python_callable=python_callable,
710
- serializer=serializer,
711
- op_args=op_args,
712
- op_kwargs=op_kwargs,
713
- string_args=string_args,
714
- templates_dict=templates_dict,
715
- templates_exts=templates_exts,
716
- expect_airflow=expect_airflow,
717
- skip_on_exit_code=skip_on_exit_code,
718
- env_vars=env_vars,
719
- inherit_env=inherit_env,
720
- **kwargs,
721
- )
722
-
723
- def _requirements_list(self, exclude_cloudpickle: bool = False) -> list[str]:
724
- """Prepare a list of requirements that need to be installed for the virtual environment."""
725
- requirements = [str(dependency) for dependency in self.requirements]
726
- if not self.system_site_packages:
727
- if (
728
- self.serializer == "cloudpickle"
729
- and not exclude_cloudpickle
730
- and "cloudpickle" not in requirements
731
- ):
732
- requirements.append("cloudpickle")
733
- elif self.serializer == "dill" and "dill" not in requirements:
734
- requirements.append("dill")
735
- requirements.sort() # Ensure a hash is stable
736
- return requirements
737
-
738
- def _prepare_venv(self, venv_path: Path) -> None:
739
- """Prepare the requirements and installs the virtual environment."""
740
- requirements_file = venv_path / "requirements.txt"
741
- requirements_file.write_text("\n".join(self._requirements_list()))
742
- prepare_virtualenv(
743
- venv_directory=str(venv_path),
744
- python_bin=f"python{self.python_version}" if self.python_version else "python",
745
- system_site_packages=self.system_site_packages,
746
- requirements_file_path=str(requirements_file),
747
- pip_install_options=self.pip_install_options,
748
- index_urls=self.index_urls,
749
- )
750
-
751
- def _calculate_cache_hash(self, exclude_cloudpickle: bool = False) -> tuple[str, str]:
752
- """
753
- Generate the hash of the cache folder to use.
754
-
755
- The following factors are used as input for the hash:
756
- - (sorted) list of requirements
757
- - pip install options
758
- - flag of system site packages
759
- - python version
760
- - Variable to override the hash with a cache key
761
- - Index URLs
762
-
763
- Returns a hash and the data dict which is the base for the hash as text.
764
- """
765
- hash_dict = {
766
- "requirements_list": self._requirements_list(exclude_cloudpickle=exclude_cloudpickle),
767
- "pip_install_options": self.pip_install_options,
768
- "index_urls": self.index_urls,
769
- "cache_key": str(Variable.get("PythonVirtualenvOperator.cache_key", "")),
770
- "python_version": self.python_version,
771
- "system_site_packages": self.system_site_packages,
772
- }
773
- hash_text = json.dumps(hash_dict, sort_keys=True)
774
- hash_object = hashlib_wrapper.md5(hash_text.encode())
775
- requirements_hash = hash_object.hexdigest()
776
- return requirements_hash[:8], hash_text
777
-
778
- def _ensure_venv_cache_exists(self, venv_cache_path: Path) -> Path:
779
- """Ensure a valid virtual environment is set up and will create inplace."""
780
- cache_hash, hash_data = self._calculate_cache_hash()
781
- venv_path = venv_cache_path / f"venv-{cache_hash}"
782
- self.log.info("Python virtual environment will be cached in %s", venv_path)
783
- venv_path.parent.mkdir(parents=True, exist_ok=True)
784
- with open(f"{venv_path}.lock", "w") as f:
785
- # Ensure that cache is not build by parallel workers
786
- import fcntl
787
-
788
- fcntl.flock(f, fcntl.LOCK_EX)
789
-
790
- hash_marker = venv_path / "install_complete_marker.json"
791
- try:
792
- if venv_path.exists():
793
- if hash_marker.exists():
794
- previous_hash_data = hash_marker.read_text(encoding="utf8")
795
- if previous_hash_data == hash_data:
796
- self.log.info("Re-using cached Python virtual environment in %s", venv_path)
797
- return venv_path
798
-
799
- _, hash_data_before_upgrade = self._calculate_cache_hash(exclude_cloudpickle=True)
800
- if previous_hash_data == hash_data_before_upgrade:
801
- self.log.warning(
802
- "Found a previous virtual environment in with outdated dependencies %s, "
803
- "deleting and re-creating.",
804
- venv_path,
805
- )
806
- else:
807
- self.log.error(
808
- "Unicorn alert: Found a previous virtual environment in %s "
809
- "with the same hash but different parameters. Previous setup: '%s' / "
810
- "Requested venv setup: '%s'. Please report a bug to airflow!",
811
- venv_path,
812
- previous_hash_data,
813
- hash_data,
814
- )
815
- else:
816
- self.log.warning(
817
- "Found a previous (probably partial installed) virtual environment in %s, "
818
- "deleting and re-creating.",
819
- venv_path,
820
- )
821
-
822
- shutil.rmtree(venv_path)
823
-
824
- venv_path.mkdir(parents=True)
825
- self._prepare_venv(venv_path)
826
- hash_marker.write_text(hash_data, encoding="utf8")
827
- except Exception as e:
828
- shutil.rmtree(venv_path)
829
- raise AirflowException(f"Unable to create new virtual environment in {venv_path}") from e
830
- self.log.info("New Python virtual environment created in %s", venv_path)
831
- return venv_path
832
-
833
- def execute_callable(self):
834
- if self.venv_cache_path:
835
- venv_path = self._ensure_venv_cache_exists(Path(self.venv_cache_path))
836
- python_path = venv_path / "bin" / "python"
837
- return self._execute_python_callable_in_subprocess(python_path)
838
-
839
- with TemporaryDirectory(prefix="venv") as tmp_dir:
840
- tmp_path = Path(tmp_dir)
841
- self._prepare_venv(tmp_path)
842
- python_path = tmp_path / "bin" / "python"
843
- result = self._execute_python_callable_in_subprocess(python_path)
844
- return result
845
-
846
- def _iter_serializable_context_keys(self):
847
- yield from self.BASE_SERIALIZABLE_CONTEXT_KEYS
848
- if self.system_site_packages or "apache-airflow" in self.requirements:
849
- yield from self.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS
850
- yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
851
- elif "pendulum" in self.requirements:
852
- yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
853
-
854
-
855
- class BranchPythonVirtualenvOperator(PythonVirtualenvOperator, BranchMixIn):
856
- """
857
- A workflow can "branch" or follow a path after the execution of this task in a virtual environment.
858
-
859
- It derives the PythonVirtualenvOperator and expects a Python function that returns
860
- a single task_id, a single task_group_id, or a list of task_ids and/or
861
- task_group_ids to follow. The task_id(s) and/or task_group_id(s) returned
862
- should point to a task or task group directly downstream from {self}. All
863
- other "branches" or directly downstream tasks are marked with a state of
864
- ``skipped`` so that these paths can't move forward. The ``skipped`` states
865
- are propagated downstream to allow for the DAG state to fill up and
866
- the DAG run's state to be inferred.
867
-
868
- .. seealso::
869
- For more information on how to use this operator, take a look at the guide:
870
- :ref:`howto/operator:BranchPythonVirtualenvOperator`
871
- """
872
-
873
- def execute(self, context: Context) -> Any:
874
- return self.do_branch(context, super().execute(context))
875
-
876
-
877
- class ExternalPythonOperator(_BasePythonVirtualenvOperator):
878
- """
879
- Run a function in a virtualenv that is not re-created.
880
-
881
- Reused as is without the overhead of creating the virtual environment (with certain caveats).
882
-
883
- The function must be defined using def, and not be
884
- part of a class. All imports must happen inside the function
885
- and no variables outside the scope may be referenced. A global scope
886
- variable named virtualenv_string_args will be available (populated by
887
- string_args). In addition, one can pass stuff through op_args and op_kwargs, and one
888
- can use a return value.
889
- Note that if your virtual environment runs in a different Python major version than Airflow,
890
- you cannot use return values, op_args, op_kwargs, or use any macros that are being provided to
891
- Airflow through plugins. You can use string_args though.
892
-
893
- If Airflow is installed in the external environment in different version that the version
894
- used by the operator, the operator will fail.,
895
-
896
- .. seealso::
897
- For more information on how to use this operator, take a look at the guide:
898
- :ref:`howto/operator:ExternalPythonOperator`
899
-
900
- :param python: Full path string (file-system specific) that points to a Python binary inside
901
- a virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path
902
- (so usually start with "/" or "X:/" depending on the filesystem/os used).
903
- :param python_callable: A python function with no references to outside variables,
904
- defined with def, which will be run in a virtual environment.
905
- :param serializer: Which serializer use to serialize the args and result. It can be one of the following:
906
-
907
- - ``"pickle"``: (default) Use pickle for serialization. Included in the Python Standard Library.
908
- - ``"cloudpickle"``: Use cloudpickle for serialize more complex types,
909
- this requires to include cloudpickle in your requirements.
910
- - ``"dill"``: Use dill for serialize more complex types,
911
- this requires to include dill in your requirements.
912
- :param op_args: A list of positional arguments to pass to python_callable.
913
- :param op_kwargs: A dict of keyword arguments to pass to python_callable.
914
- :param string_args: Strings that are present in the global var virtualenv_string_args,
915
- available to python_callable at runtime as a list[str]. Note that args are split
916
- by newline.
917
- :param templates_dict: a dictionary where the values are templates that
918
- will get templated by the Airflow engine sometime between
919
- ``__init__`` and ``execute`` takes place and are made available
920
- in your callable's context after the template has been applied
921
- :param templates_exts: a list of file extensions to resolve while
922
- processing templated fields, for examples ``['.sql', '.hql']``
923
- :param expect_airflow: expect Airflow to be installed in the target environment. If true, the operator
924
- will raise warning if Airflow is not installed, and it will attempt to load Airflow
925
- macros when starting.
926
- :param skip_on_exit_code: If python_callable exits with this exit code, leave the task
927
- in ``skipped`` state (default: None). If set to ``None``, any non-zero
928
- exit code will be treated as a failure.
929
- :param env_vars: A dictionary containing additional environment variables to set for the virtual
930
- environment when it is executed.
931
- :param inherit_env: Whether to inherit the current environment variables when executing the virtual
932
- environment. If set to ``True``, the virtual environment will inherit the environment variables
933
- of the parent process (``os.environ``). If set to ``False``, the virtual environment will be
934
- executed with a clean environment.
935
- """
936
-
937
- template_fields: Sequence[str] = tuple({"python"}.union(PythonOperator.template_fields))
938
-
939
- def __init__(
940
- self,
941
- *,
942
- python: str,
943
- python_callable: Callable,
944
- serializer: _SerializerTypeDef | None = None,
945
- op_args: Collection[Any] | None = None,
946
- op_kwargs: Mapping[str, Any] | None = None,
947
- string_args: Iterable[str] | None = None,
948
- templates_dict: dict | None = None,
949
- templates_exts: list[str] | None = None,
950
- expect_airflow: bool = True,
951
- expect_pendulum: bool = False,
952
- skip_on_exit_code: int | Container[int] | None = None,
953
- env_vars: dict[str, str] | None = None,
954
- inherit_env: bool = True,
955
- **kwargs,
956
- ):
957
- if not python:
958
- raise ValueError("Python Path must be defined in ExternalPythonOperator")
959
- self.python = python
960
- self.expect_pendulum = expect_pendulum
961
- super().__init__(
962
- python_callable=python_callable,
963
- serializer=serializer,
964
- op_args=op_args,
965
- op_kwargs=op_kwargs,
966
- string_args=string_args,
967
- templates_dict=templates_dict,
968
- templates_exts=templates_exts,
969
- expect_airflow=expect_airflow,
970
- skip_on_exit_code=skip_on_exit_code,
971
- env_vars=env_vars,
972
- inherit_env=inherit_env,
973
- **kwargs,
974
- )
975
-
976
- def execute_callable(self):
977
- python_path = Path(self.python)
978
- if not python_path.exists():
979
- raise ValueError(f"Python Path '{python_path}' must exists")
980
- if not python_path.is_file():
981
- raise ValueError(f"Python Path '{python_path}' must be a file")
982
- if not python_path.is_absolute():
983
- raise ValueError(f"Python Path '{python_path}' must be an absolute path.")
984
- python_version = _PythonVersionInfo.from_executable(self.python)
985
- if python_version.major != sys.version_info.major and (self.op_args or self.op_kwargs):
986
- raise AirflowException(
987
- "Passing op_args or op_kwargs is not supported across different Python "
988
- "major versions for ExternalPythonOperator. Please use string_args."
989
- f"Sys version: {sys.version_info}. "
990
- f"Virtual environment version: {python_version}"
991
- )
992
- return self._execute_python_callable_in_subprocess(python_path)
993
-
994
- def _iter_serializable_context_keys(self):
995
- yield from self.BASE_SERIALIZABLE_CONTEXT_KEYS
996
- if self._get_airflow_version_from_target_env():
997
- yield from self.AIRFLOW_SERIALIZABLE_CONTEXT_KEYS
998
- yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
999
- elif self._is_pendulum_installed_in_target_env():
1000
- yield from self.PENDULUM_SERIALIZABLE_CONTEXT_KEYS
1001
-
1002
- def _is_pendulum_installed_in_target_env(self) -> bool:
1003
- try:
1004
- subprocess.check_call([self.python, "-c", "import pendulum"])
1005
- return True
1006
- except Exception as e:
1007
- if self.expect_pendulum:
1008
- self.log.warning("When checking for Pendulum installed in virtual environment got %s", e)
1009
- self.log.warning(
1010
- "Pendulum is not properly installed in the virtual environment "
1011
- "Pendulum context keys will not be available. "
1012
- "Please Install Pendulum or Airflow in your virtual environment to access them."
1013
- )
1014
- return False
1015
-
1016
- @property
1017
- def _external_airflow_version_script(self):
1018
- """
1019
- Return python script which determines the version of the Apache Airflow.
1020
-
1021
- Import airflow as a module might take a while as a result,
1022
- obtaining a version would take up to 1 second.
1023
- On the other hand, `importlib.metadata.version` will retrieve the package version pretty fast
1024
- something below 100ms; this includes new subprocess overhead.
1025
-
1026
- Possible side effect: It might be a situation that `importlib.metadata` is not available (Python < 3.8),
1027
- as well as backport `importlib_metadata` which might indicate that venv doesn't contain an `apache-airflow`
1028
- or something wrong with the environment.
1029
- """
1030
- return textwrap.dedent(
1031
- """
1032
- try:
1033
- from importlib.metadata import version
1034
- except ImportError:
1035
- from importlib_metadata import version
1036
- print(version("apache-airflow"))
1037
- """
1038
- )
1039
-
1040
- def _get_airflow_version_from_target_env(self) -> str | None:
1041
- from airflow import __version__ as airflow_version
1042
-
1043
- try:
1044
- result = subprocess.check_output(
1045
- [self.python, "-c", self._external_airflow_version_script],
1046
- text=True,
1047
- )
1048
- target_airflow_version = result.strip()
1049
- if target_airflow_version != airflow_version:
1050
- raise AirflowConfigException(
1051
- f"The version of Airflow installed for the {self.python} "
1052
- f"({target_airflow_version}) is different than the runtime Airflow version: "
1053
- f"{airflow_version}. Make sure your environment has the same Airflow version "
1054
- f"installed as the Airflow runtime."
1055
- )
1056
- return target_airflow_version
1057
- except Exception as e:
1058
- if self.expect_airflow:
1059
- self.log.warning("When checking for Airflow installed in virtual environment got %s", e)
1060
- self.log.warning(
1061
- "This means that Airflow is not properly installed by %s. "
1062
- "Airflow context keys will not be available. "
1063
- "Please Install Airflow %s in your environment to access them.",
1064
- self.python,
1065
- airflow_version,
1066
- )
1067
- return None
1068
-
1069
-
1070
- class BranchExternalPythonOperator(ExternalPythonOperator, BranchMixIn):
1071
- """
1072
- A workflow can "branch" or follow a path after the execution of this task.
1073
-
1074
- Extends ExternalPythonOperator, so expects to get Python:
1075
- virtual environment that should be used (in ``VENV/bin`` folder). Should be absolute path,
1076
- so it can run on separate virtual environment similarly to ExternalPythonOperator.
1077
-
1078
- .. seealso::
1079
- For more information on how to use this operator, take a look at the guide:
1080
- :ref:`howto/operator:BranchExternalPythonOperator`
1081
- """
1082
-
1083
- def execute(self, context: Context) -> Any:
1084
- return self.do_branch(context, super().execute(context))
1085
-
1086
-
1087
- def get_current_context() -> Mapping[str, Any]:
1088
- """
1089
- Retrieve the execution context dictionary without altering user method's signature.
1090
-
1091
- This is the simplest method of retrieving the execution context dictionary.
1092
-
1093
- **Old style:**
1094
-
1095
- .. code:: python
1096
-
1097
- def my_task(**context):
1098
- ti = context["ti"]
1099
-
1100
- **New style:**
1101
-
1102
- .. code:: python
1103
-
1104
- from airflow.providers.standard.operators.python import get_current_context
1105
-
1106
-
1107
- def my_task():
1108
- context = get_current_context()
1109
- ti = context["ti"]
1110
-
1111
- Current context will only have value if this method was called after an operator
1112
- was starting to execute.
1113
- """
1114
- if AIRFLOW_V_3_0_PLUS:
1115
- from airflow.sdk import get_current_context
1116
-
1117
- return get_current_context()
1118
- else:
1119
- return _get_current_context()
1120
-
1121
-
1122
- def _get_current_context() -> Mapping[str, Any]:
1123
- # Airflow 2.x
1124
- # TODO: To be removed when Airflow 2 support is dropped
1125
- from airflow.models.taskinstance import _CURRENT_CONTEXT # type: ignore[attr-defined]
1126
-
1127
- if not _CURRENT_CONTEXT:
1128
- raise RuntimeError(
1129
- "Current context was requested but no context was found! "
1130
- "Are you running within an Airflow task?"
1131
- )
1132
- return _CURRENT_CONTEXT[-1]