INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Get the messages of a container group | def get_messages(self, resource_group, name):
"""
Get the messages of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:return: A list of the event messa... |
Get the tail from logs of a container group | def get_logs(self, resource_group, name, tail=1000):
"""
Get the tail from logs of a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
:param tail: the size... |
Delete a container group | def delete(self, resource_group, name):
"""
Delete a container group
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
"""
self.connection.container_groups.delete(r... |
Test if a container group exists | def exists(self, resource_group, name):
"""
Test if a container group exists
:param resource_group: the name of the resource group
:type resource_group: str
:param name: the name of the container group
:type name: str
"""
for container in self.connection.... |
Function decorator that Looks for an argument named default_args and fills the unspecified arguments from it. | def apply_defaults(func):
"""
Function decorator that Looks for an argument named "default_args", and
fills the unspecified arguments from it.
Since python2.* isn't clear about which arguments are missing when
calling a function, and that this can be quite confusing with multi-level
inheritance... |
Builds an ingest query for an HDFS TSV load. | def construct_ingest_query(self, static_path, columns):
"""
Builds an ingest query for an HDFS TSV load.
:param static_path: The path on hdfs where the data is
:type static_path: str
:param columns: List of all the columns that are available
:type columns: list
"... |
This function executes the transfer from the email server ( via imap ) into s3. | def execute(self, context):
"""
This function executes the transfer from the email server (via imap) into s3.
:param context: The context while executing.
:type context: dict
"""
self.log.info(
'Transferring mail attachment %s from mail server via imap to s3 ... |
Check for message on subscribed channels and write to xcom the message with key message | def poke(self, context):
"""
Check for message on subscribed channels and write to xcom the message with key ``message``
An example of message ``{'type': 'message', 'pattern': None, 'channel': b'test', 'data': b'hello'}``
:param context: the context object
:type context: dict
... |
Reloads the current dagrun from the database: param session: database session | def refresh_from_db(self, session=None):
"""
Reloads the current dagrun from the database
:param session: database session
"""
DR = DagRun
exec_date = func.cast(self.execution_date, DateTime)
dr = session.query(DR).filter(
DR.dag_id == self.dag_id,
... |
Returns a set of dag runs for the given search criteria. | def find(dag_id=None, run_id=None, execution_date=None,
state=None, external_trigger=None, no_backfills=False,
session=None):
"""
Returns a set of dag runs for the given search criteria.
:param dag_id: the dag_id to find dag runs for
:type dag_id: int, list
... |
Returns the task instances for this dag run | def get_task_instances(self, state=None, session=None):
"""
Returns the task instances for this dag run
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
tis = session.query(TaskInstance).filter(
TaskInstance.dag_id == self.dag_id,
... |
Returns the task instance specified by task_id for this dag run | def get_task_instance(self, task_id, session=None):
"""
Returns the task instance specified by task_id for this dag run
:param task_id: the task id
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
TI = TaskInstance
ti = session.q... |
The previous DagRun if there is one | def get_previous_dagrun(self, session=None):
"""The previous DagRun, if there is one"""
return session.query(DagRun).filter(
DagRun.dag_id == self.dag_id,
DagRun.execution_date < self.execution_date
).order_by(
DagRun.execution_date.desc()
).first() |
The previous SCHEDULED DagRun if there is one | def get_previous_scheduled_dagrun(self, session=None):
"""The previous, SCHEDULED DagRun, if there is one"""
dag = self.get_dag()
return session.query(DagRun).filter(
DagRun.dag_id == self.dag_id,
DagRun.execution_date == dag.previous_schedule(self.execution_date)
... |
Determines the overall state of the DagRun based on the state of its TaskInstances. | def update_state(self, session=None):
"""
Determines the overall state of the DagRun based on the state
of its TaskInstances.
:return: State
"""
dag = self.get_dag()
tis = self.get_task_instances(session=session)
self.log.debug("Updating state for %s co... |
Verifies the DagRun by checking for removed tasks or tasks that are not in the database yet. It will set state to removed or add the task if required. | def verify_integrity(self, session=None):
"""
Verifies the DagRun by checking for removed tasks or tasks that are not in the
database yet. It will set state to removed or add the task if required.
"""
from airflow.models.taskinstance import TaskInstance # Avoid circular import
... |
: param dag_id: DAG ID: type dag_id: unicode: param execution_date: execution date: type execution_date: datetime: return: DagRun corresponding to the given dag_id and execution date if one exists. None otherwise.: rtype: airflow. models. DagRun | def get_run(session, dag_id, execution_date):
"""
:param dag_id: DAG ID
:type dag_id: unicode
:param execution_date: execution date
:type execution_date: datetime
:return: DagRun corresponding to the given dag_id and execution date
if one exists. None otherwis... |
We need to get the headers in addition to the body answer to get the location from them This function uses jenkins_request method from python - jenkins library with just the return call changed | def jenkins_request_with_headers(jenkins_server, req):
"""
We need to get the headers in addition to the body answer
to get the location from them
This function uses jenkins_request method from python-jenkins library
with just the return call changed
:param jenkins_server: The server to query
... |
This function makes an API call to Jenkins to trigger a build for job_name It returned a dict with 2 keys: body and headers. headers contains also a dict - like object which can be queried to get the location to poll in the queue. | def build_job(self, jenkins_server):
"""
This function makes an API call to Jenkins to trigger a build for 'job_name'
It returned a dict with 2 keys : body and headers.
headers contains also a dict-like object which can be queried to get
the location to poll in the queue.
... |
This method poll the jenkins queue until the job is executed. When we trigger a job through an API call the job is first put in the queue without having a build number assigned. Thus we have to wait the job exit the queue to know its build number. To do so we have to add/ api/ json ( or/ api/ xml ) to the location retu... | def poll_job_in_queue(self, location, jenkins_server):
"""
This method poll the jenkins queue until the job is executed.
When we trigger a job through an API call,
the job is first put in the queue without having a build number assigned.
Thus we have to wait the job exit the queu... |
Given a context this function provides a dictionary of values that can be used to externally reconstruct relations between dags dag_runs tasks and task_instances. Default to abc. def. ghi format and can be made to ABC_DEF_GHI format if in_env_var_format is set to True. | def context_to_airflow_vars(context, in_env_var_format=False):
"""
Given a context, this function provides a dictionary of values that can be used to
externally reconstruct relations between dags, dag_runs, tasks and task_instances.
Default to abc.def.ghi format and can be made to ABC_DEF_GHI format if
... |
Calls callbacks before execution. Note that any exception from callback will be logged but won t be propagated.: param kwargs:: return: None | def on_pre_execution(**kwargs):
"""
Calls callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None
"""
logging.debug("Calling callbacks: %s", __pre_exec_callbacks)
for cb in __pre_exec_callbacks:
try:
... |
Calls callbacks after execution. As it s being called after execution it can capture status of execution duration etc. Note that any exception from callback will be logged but won t be propagated.: param kwargs:: return: None | def on_post_execution(**kwargs):
"""
Calls callbacks after execution.
As it's being called after execution, it can capture status of execution,
duration, etc. Note that any exception from callback will be logged but
won't be propagated.
:param kwargs:
:return: None
"""
logging.debug(... |
This function decides whether or not to Trigger the remote DAG | def conditionally_trigger(context, dag_run_obj):
"""This function decides whether or not to Trigger the remote DAG"""
c_p = context['params']['condition_param']
print("Controller DAG : conditionally_trigger = {}".format(c_p))
if context['params']['condition_param']:
dag_run_obj.payload = {'messa... |
Sends a single datapoint metric to DataDog | def send_metric(self, metric_name, datapoint, tags=None, type_=None, interval=None):
"""
Sends a single datapoint metric to DataDog
:param metric_name: The name of the metric
:type metric_name: str
:param datapoint: A single integer or float related to the metric
:type d... |
Queries datadog for a specific metric potentially with some function applied to it and returns the results. | def query_metric(self,
query,
from_seconds_ago,
to_seconds_ago):
"""
Queries datadog for a specific metric, potentially with some
function applied to it and returns the results.
:param query: The datadog query to execute (se... |
Posts an event to datadog ( processing finished potentially alerts other issues ) Think about this as a means to maintain persistence of alerts rather than alerting itself. | def post_event(self, title, text, aggregation_key=None, alert_type=None, date_happened=None,
handle=None, priority=None, related_event_id=None, tags=None, device_name=None):
"""
Posts an event to datadog (processing finished, potentially alerts, other issues)
Think about this ... |
Given either a manually set token or a conn_id return the webhook_token to use: param token: The manually provided token: type token: str: param http_conn_id: The conn_id provided: type http_conn_id: str: return: webhook_token ( str ) to use | def _get_token(self, token, http_conn_id):
"""
Given either a manually set token or a conn_id, return the webhook_token to use
:param token: The manually provided token
:type token: str
:param http_conn_id: The conn_id provided
:type http_conn_id: str
:return: web... |
Construct the Slack message. All relevant parameters are combined here to a valid Slack json message: return: Slack message ( str ) to send | def _build_slack_message(self):
"""
Construct the Slack message. All relevant parameters are combined here to a valid
Slack json message
:return: Slack message (str) to send
"""
cmd = {}
if self.channel:
cmd['channel'] = self.channel
if self.u... |
Remote Popen ( actually execute the slack webhook call ) | def execute(self):
"""
Remote Popen (actually execute the slack webhook call)
"""
proxies = {}
if self.proxy:
# we only need https proxy for Slack, as the endpoint is https
proxies = {'https': self.proxy}
slack_message = self._build_slack_message(... |
Gets the DAG out of the dictionary and refreshes it if expired | def get_dag(self, dag_id):
"""
Gets the DAG out of the dictionary, and refreshes it if expired
"""
from airflow.models.dag import DagModel # Avoid circular import
# If asking for a known subdag, we want to refresh the parent
root_dag_id = dag_id
if dag_id in sel... |
Given a path to a python module or zip file this method imports the module and look for dag objects within it. | def process_file(self, filepath, only_if_updated=True, safe_mode=True):
"""
Given a path to a python module or zip file, this method imports
the module and look for dag objects within it.
"""
from airflow.models.dag import DAG # Avoid circular import
found_dags = []
... |
Fail given zombie tasks which are tasks that haven t had a heartbeat for too long in the current DagBag. | def kill_zombies(self, zombies, session=None):
"""
Fail given zombie tasks, which are tasks that haven't
had a heartbeat for too long, in the current DagBag.
:param zombies: zombie task instances to kill.
:type zombies: airflow.utils.dag_processing.SimpleTaskInstance
:pa... |
Adds the DAG into the bag recurses into sub dags. Throws AirflowDagCycleException if a cycle is detected in this dag or its subdags | def bag_dag(self, dag, parent_dag, root_dag):
"""
Adds the DAG into the bag, recurses into sub dags.
Throws AirflowDagCycleException if a cycle is detected in this dag or its subdags
"""
dag.test_cycle() # throws if a task cycle is found
dag.resolve_template_files()
... |
Given a file path or a folder this method looks for python modules imports them and adds them to the dagbag collection. | def collect_dags(
self,
dag_folder=None,
only_if_updated=True,
include_examples=configuration.conf.getboolean('core', 'LOAD_EXAMPLES'),
safe_mode=configuration.conf.getboolean('core', 'DAG_DISCOVERY_SAFE_MODE')):
"""
Given a file path or a fold... |
Prints a report around DagBag loading stats | def dagbag_report(self):
"""Prints a report around DagBag loading stats"""
report = textwrap.dedent("""\n
-------------------------------------------------------------------
DagBag loading stats for {dag_folder}
-------------------------------------------------------------------
... |
Call the SparkSubmitHook to run the provided spark job | def execute(self, context):
"""
Call the SparkSubmitHook to run the provided spark job
"""
self._hook = SparkJDBCHook(
spark_app_name=self._spark_app_name,
spark_conn_id=self._spark_conn_id,
spark_conf=self._spark_conf,
spark_py_files=self.... |
Add or subtract days from a YYYY - MM - DD | def ds_add(ds, days):
"""
Add or subtract days from a YYYY-MM-DD
:param ds: anchor date in ``YYYY-MM-DD`` format to add to
:type ds: str
:param days: number of days to add to the ds, you can use negative values
:type days: int
>>> ds_add('2015-01-01', 5)
'2015-01-06'
>>> ds_add('20... |
Takes an input string and outputs another string as specified in the output format | def ds_format(ds, input_format, output_format):
"""
Takes an input string and outputs another string
as specified in the output format
:param ds: input string which contains a date
:type ds: str
:param input_format: input string format. E.g. %Y-%m-%d
:type input_format: str
:param outpu... |
Integrate plugins to the context | def _integrate_plugins():
"""Integrate plugins to the context"""
import sys
from airflow.plugins_manager import macros_modules
for macros_module in macros_modules:
sys.modules[macros_module.__name__] = macros_module
globals()[macros_module._name] = macros_module |
poke matching files in a directory with self. regex | def poke(self, context):
"""
poke matching files in a directory with self.regex
:return: Bool depending on the search criteria
"""
sb = self.hook(self.hdfs_conn_id).get_conn()
self.log.info(
'Poking for %s to be a directory with files matching %s', self.filep... |
poke for a non empty directory | def poke(self, context):
"""
poke for a non empty directory
:return: Bool depending on the search criteria
"""
sb = self.hook(self.hdfs_conn_id).get_conn()
result = [f for f in sb.ls([self.filepath], include_toplevel=True)]
result = self.filter_for_ignored_ext(re... |
Clears a set of task instances but makes sure the running ones get killed. | def clear_task_instances(tis,
session,
activate_dag_runs=True,
dag=None,
):
"""
Clears a set of task instances, but makes sure the running ones
get killed.
:param tis: a list of task instances
:param... |
Return the try number that this task number will be when it is actually run. | def try_number(self):
"""
Return the try number that this task number will be when it is actually
run.
If the TI is currently running, this will match the column in the
databse, in all othercases this will be incremenetd
"""
# This is designed so that task logs e... |
Returns a command that can be executed anywhere where airflow is installed. This command is part of the message sent to executors by the orchestrator. | def command(
self,
mark_success=False,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... |
Returns a command that can be executed anywhere where airflow is installed. This command is part of the message sent to executors by the orchestrator. | def command_as_list(
self,
mark_success=False,
ignore_all_deps=False,
ignore_task_deps=False,
ignore_depends_on_past=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... |
Generates the shell command required to execute this task instance. | def generate_command(dag_id,
task_id,
execution_date,
mark_success=False,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
... |
Get the very latest state from the database if a session is passed we use and looking up the state becomes part of the session otherwise a new session is used. | def current_state(self, session=None):
"""
Get the very latest state from the database, if a session is passed,
we use and looking up the state becomes part of the session, otherwise
a new session is used.
"""
TI = TaskInstance
ti = session.query(TI).filter(
... |
Forces the task instance s state to FAILED in the database. | def error(self, session=None):
"""
Forces the task instance's state to FAILED in the database.
"""
self.log.error("Recording the task instance as FAILED")
self.state = State.FAILED
session.merge(self)
session.commit() |
Refreshes the task instance from the database based on the primary key | def refresh_from_db(self, session=None, lock_for_update=False):
"""
Refreshes the task instance from the database based on the primary key
:param lock_for_update: if True, indicates that the database should
lock the TaskInstance (issuing a FOR UPDATE clause) until the
se... |
Clears all XCom data from the database for the task instance | def clear_xcom_data(self, session=None):
"""
Clears all XCom data from the database for the task instance
"""
session.query(XCom).filter(
XCom.dag_id == self.dag_id,
XCom.task_id == self.task_id,
XCom.execution_date == self.execution_date
).del... |
Returns a tuple that identifies the task instance uniquely | def key(self):
"""
Returns a tuple that identifies the task instance uniquely
"""
return self.dag_id, self.task_id, self.execution_date, self.try_number |
Checks whether the dependents of this task instance have all succeeded. This is meant to be used by wait_for_downstream. | def are_dependents_done(self, session=None):
"""
Checks whether the dependents of this task instance have all succeeded.
This is meant to be used by wait_for_downstream.
This is useful when you do not want to start processing the next
schedule of a task until the dependents are ... |
Returns whether or not all the conditions are met for this task instance to be run given the context for the dependencies ( e. g. a task instance being force run from the UI will ignore some dependencies ). | def are_dependencies_met(
self,
dep_context=None,
session=None,
verbose=False):
"""
Returns whether or not all the conditions are met for this task instance to be run
given the context for the dependencies (e.g. a task instance being force run from... |
Get datetime of the next retry if the task instance fails. For exponential backoff retry_delay is used as base and will be converted to seconds. | def next_retry_datetime(self):
"""
Get datetime of the next retry if the task instance fails. For exponential
backoff, retry_delay is used as base and will be converted to seconds.
"""
delay = self.task.retry_delay
if self.task.retry_exponential_backoff:
min_b... |
Checks on whether the task instance is in the right state and timeframe to be retried. | def ready_for_retry(self):
"""
Checks on whether the task instance is in the right state and timeframe
to be retried.
"""
return (self.state == State.UP_FOR_RETRY and
self.next_retry_datetime() < timezone.utcnow()) |
Returns a boolean as to whether the slot pool has room for this task to run | def pool_full(self, session):
"""
Returns a boolean as to whether the slot pool has room for this
task to run
"""
if not self.task.pool:
return False
pool = (
session
.query(Pool)
.filter(Pool.pool == self.task.pool)
... |
Returns the DagRun for this TaskInstance | def get_dagrun(self, session):
"""
Returns the DagRun for this TaskInstance
:param session:
:return: DagRun
"""
from airflow.models.dagrun import DagRun # Avoid circular import
dr = session.query(DagRun).filter(
DagRun.dag_id == self.dag_id,
... |
Checks dependencies and then sets state to RUNNING if they are met. Returns True if and only if state is set to RUNNING which implies that task should be executed in preparation for _run_raw_task | def _check_and_change_state_before_execution(
self,
verbose=True,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
mark_success=False,
test_mode=False,
job_id=No... |
Immediately runs the task ( without checking or changing db state before execution ) and then sets the appropriate final state after completion and runs any post - execute callbacks. Meant to be called only after another function changes the state to running. | def _run_raw_task(
self,
mark_success=False,
test_mode=False,
job_id=None,
pool=None,
session=None):
"""
Immediately runs the task (without checking or changing db state
before execution) and then sets the appropriate final ... |
Make an XCom available for tasks to pull. | def xcom_push(
self,
key,
value,
execution_date=None):
"""
Make an XCom available for tasks to pull.
:param key: A key for the XCom
:type key: str
:param value: A value for the XCom. The value is pickled and stored
in t... |
Pull XComs that optionally meet certain criteria. | def xcom_pull(
self,
task_ids=None,
dag_id=None,
key=XCOM_RETURN_KEY,
include_prior_dates=False):
"""
Pull XComs that optionally meet certain criteria.
The default value for `key` limits the search to XComs
that were returned b... |
Sets the log context. | def init_run_context(self, raw=False):
"""
Sets the log context.
"""
self.raw = raw
self._set_context(self) |
Close and upload local log file to remote storage Wasb. | def close(self):
"""
Close and upload local log file to remote storage Wasb.
"""
# When application exit, system shuts down all handlers by
# calling close method. Here we check if logger is already
# closed to prevent uploading the log to remote storage multiple
... |
Read logs of given task instance and try_number from Wasb remote storage. If failed read the log from task instance host machine.: param ti: task instance object: param try_number: task instance try_number to read logs from: param metadata: log metadata can be used for steaming log reading and auto - tailing. | def _read(self, ti, try_number, metadata=None):
"""
Read logs of given task instance and try_number from Wasb remote storage.
If failed, read the log from task instance host machine.
:param ti: task instance object
:param try_number: task instance try_number to read logs from
... |
Check if remote_log_location exists in remote storage: param remote_log_location: log s location in remote storage: return: True if location exists else False | def wasb_log_exists(self, remote_log_location):
"""
Check if remote_log_location exists in remote storage
:param remote_log_location: log's location in remote storage
:return: True if location exists else False
"""
try:
return self.hook.check_for_blob(self.was... |
Returns the log found at the remote_log_location. Returns if no logs are found or there is an error.: param remote_log_location: the log s location in remote storage: type remote_log_location: str ( path ): param return_error: if True returns a string error message if an error occurs. Otherwise returns when an error oc... | def wasb_read(self, remote_log_location, return_error=False):
"""
Returns the log found at the remote_log_location. Returns '' if no
logs are found or there is an error.
:param remote_log_location: the log's location in remote storage
:type remote_log_location: str (path)
... |
Writes the log to the remote_log_location. Fails silently if no hook was created.: param log: the log to write to the remote_log_location: type log: str: param remote_log_location: the log s location in remote storage: type remote_log_location: str ( path ): param append: if False any existing log file is overwritten. ... | def wasb_write(self, log, remote_log_location, append=True):
"""
Writes the log to the remote_log_location. Fails silently if no hook
was created.
:param log: the log to write to the remote_log_location
:type log: str
:param remote_log_location: the log's location in remo... |
Retrieves connection to Google Compute Engine. | def get_conn(self):
"""
Retrieves connection to Google Compute Engine.
:return: Google Compute Engine services object
:rtype: dict
"""
if not self._conn:
http_authorized = self._authorize()
self._conn = build('compute', self.api_version,
... |
Starts an existing instance defined by project_id zone and resource_id. Must be called with keyword arguments rather than positional. | def start_instance(self, zone, resource_id, project_id=None):
"""
Starts an existing instance defined by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud Platform zone where the instance exists
:type zone: ... |
Sets machine type of an instance defined by project_id zone and resource_id. Must be called with keyword arguments rather than positional. | def set_machine_type(self, zone, resource_id, body, project_id=None):
"""
Sets machine type of an instance defined by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud Platform zone where the instance exists.
... |
Retrieves instance template by project_id and resource_id. Must be called with keyword arguments rather than positional. | def get_instance_template(self, resource_id, project_id=None):
"""
Retrieves instance template by project_id and resource_id.
Must be called with keyword arguments rather than positional.
:param resource_id: Name of the instance template
:type resource_id: str
:param pro... |
Inserts instance template using body specified Must be called with keyword arguments rather than positional. | def insert_instance_template(self, body, request_id=None, project_id=None):
"""
Inserts instance template using body specified
Must be called with keyword arguments rather than positional.
:param body: Instance template representation as object according to
https://cloud.goo... |
Retrieves Instance Group Manager by project_id zone and resource_id. Must be called with keyword arguments rather than positional. | def get_instance_group_manager(self, zone, resource_id, project_id=None):
"""
Retrieves Instance Group Manager by project_id, zone and resource_id.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud Platform zone where the Instance Group Manager exis... |
Patches Instance Group Manager with the specified body. Must be called with keyword arguments rather than positional. | def patch_instance_group_manager(self, zone, resource_id,
body, request_id=None, project_id=None):
"""
Patches Instance Group Manager with the specified body.
Must be called with keyword arguments rather than positional.
:param zone: Google Cloud Pla... |
Waits for the named operation to complete - checks status of the async call. | def _wait_for_operation_to_complete(self, project_id, operation_name, zone=None):
"""
Waits for the named operation to complete - checks status of the async call.
:param operation_name: name of the operation
:type operation_name: str
:param zone: optional region of the request (... |
Check if bucket_name exists. | def check_for_bucket(self, bucket_name):
"""
Check if bucket_name exists.
:param bucket_name: the name of the bucket
:type bucket_name: str
"""
try:
self.get_conn().head_bucket(Bucket=bucket_name)
return True
except ClientError as e:
... |
Creates an Amazon S3 bucket. | def create_bucket(self, bucket_name, region_name=None):
"""
Creates an Amazon S3 bucket.
:param bucket_name: The name of the bucket
:type bucket_name: str
:param region_name: The name of the aws region in which to create the bucket.
:type region_name: str
"""
... |
Checks that a prefix exists in a bucket | def check_for_prefix(self, bucket_name, prefix, delimiter):
"""
Checks that a prefix exists in a bucket
:param bucket_name: the name of the bucket
:type bucket_name: str
:param prefix: a key prefix
:type prefix: str
:param delimiter: the delimiter marks key hiera... |
Lists prefixes in a bucket under prefix | def list_prefixes(self, bucket_name, prefix='', delimiter='',
page_size=None, max_items=None):
"""
Lists prefixes in a bucket under prefix
:param bucket_name: the name of the bucket
:type bucket_name: str
:param prefix: a key prefix
:type prefix: st... |
Lists keys in a bucket under prefix and not containing delimiter | def list_keys(self, bucket_name, prefix='', delimiter='',
page_size=None, max_items=None):
"""
Lists keys in a bucket under prefix and not containing delimiter
:param bucket_name: the name of the bucket
:type bucket_name: str
:param prefix: a key prefix
... |
Checks if a key exists in a bucket | def check_for_key(self, key, bucket_name=None):
"""
Checks if a key exists in a bucket
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which the file is stored
:type bucket_name: str
"""
if not bucke... |
Returns a boto3. s3. Object | def get_key(self, key, bucket_name=None):
"""
Returns a boto3.s3.Object
:param key: the path to the key
:type key: str
:param bucket_name: the name of the bucket
:type bucket_name: str
"""
if not bucket_name:
(bucket_name, key) = self.parse_s3... |
Reads a key from S3 | def read_key(self, key, bucket_name=None):
"""
Reads a key from S3
:param key: S3 key that will point to the file
:type key: str
:param bucket_name: Name of the bucket in which the file is stored
:type bucket_name: str
"""
obj = self.get_key(key, bucket_... |
Reads a key with S3 Select. | def select_key(self, key, bucket_name=None,
expression='SELECT * FROM S3Object',
expression_type='SQL',
input_serialization=None,
output_serialization=None):
"""
Reads a key with S3 Select.
:param key: S3 key that will ... |
Checks that a key matching a wildcard expression exists in a bucket | def check_for_wildcard_key(self,
wildcard_key, bucket_name=None, delimiter=''):
"""
Checks that a key matching a wildcard expression exists in a bucket
:param wildcard_key: the path to the key
:type wildcard_key: str
:param bucket_name: the name of... |
Returns a boto3. s3. Object object matching the wildcard expression | def get_wildcard_key(self, wildcard_key, bucket_name=None, delimiter=''):
"""
Returns a boto3.s3.Object object matching the wildcard expression
:param wildcard_key: the path to the key
:type wildcard_key: str
:param bucket_name: the name of the bucket
:type bucket_name: ... |
Loads a local file to S3 | def load_file(self,
filename,
key,
bucket_name=None,
replace=False,
encrypt=False):
"""
Loads a local file to S3
:param filename: name of the file to load.
:type filename: str
:param key: S... |
Loads a string to S3 | def load_string(self,
string_data,
key,
bucket_name=None,
replace=False,
encrypt=False,
encoding='utf-8'):
"""
Loads a string to S3
This is provided as a convenience to drop a... |
Loads bytes to S3 | def load_bytes(self,
bytes_data,
key,
bucket_name=None,
replace=False,
encrypt=False):
"""
Loads bytes to S3
This is provided as a convenience to drop a string in S3. It uses the
boto infrastr... |
Loads a file object to S3 | def load_file_obj(self,
file_obj,
key,
bucket_name=None,
replace=False,
encrypt=False):
"""
Loads a file object to S3
:param file_obj: The file-like object to set as the content for the... |
Creates a copy of an object that is already stored in S3. | def copy_object(self,
source_bucket_key,
dest_bucket_key,
source_bucket_name=None,
dest_bucket_name=None,
source_version_id=None):
"""
Creates a copy of an object that is already stored in S3.
No... |
: param bucket: Name of the bucket in which you are going to delete object ( s ): type bucket: str: param keys: The key ( s ) to delete from S3 bucket. | def delete_objects(self,
bucket,
keys):
"""
:param bucket: Name of the bucket in which you are going to delete object(s)
:type bucket: str
:param keys: The key(s) to delete from S3 bucket.
When ``keys`` is a string, it's supposed... |
Queries cassandra and returns a cursor to the results. | def _query_cassandra(self):
"""
Queries cassandra and returns a cursor to the results.
"""
self.hook = CassandraHook(cassandra_conn_id=self.cassandra_conn_id)
session = self.hook.get_conn()
cursor = session.execute(self.cql)
return cursor |
Takes a cursor and writes results to a local file. | def _write_local_data_files(self, cursor):
"""
Takes a cursor, and writes results to a local file.
:return: A dictionary where keys are filenames to be used as object
names in GCS, and values are file handles to local files that
contain the data for the GCS objects.
... |
Takes a cursor and writes the BigQuery schema for the results to a local file system. | def _write_local_schema_file(self, cursor):
"""
Takes a cursor, and writes the BigQuery schema for the results to a
local file system.
:return: A dictionary where key is a filename to be used as an object
name in GCS, and values are file handles to local files that
... |
Converts a user type to RECORD that contains n fields where n is the number of attributes. Each element in the user type class will be converted to its corresponding data type in BQ. | def convert_user_type(cls, name, value):
"""
Converts a user type to RECORD that contains n fields, where n is the
number of attributes. Each element in the user type class will be converted to its
corresponding data type in BQ.
"""
names = value._fields
values = ... |
Converts a tuple to RECORD that contains n fields each will be converted to its corresponding data type in bq and will be named field_<index > where index is determined by the order of the tuple elements defined in cassandra. | def convert_tuple_type(cls, name, value):
"""
Converts a tuple to RECORD that contains n fields, each will be converted
to its corresponding data type in bq and will be named 'field_<index>', where
index is determined by the order of the tuple elements defined in cassandra.
"""
... |
Converts a map to a repeated RECORD that contains two fields: key and value each will be converted to its corresponding data type in BQ. | def convert_map_type(cls, name, value):
"""
Converts a map to a repeated RECORD that contains two fields: 'key' and 'value',
each will be converted to its corresponding data type in BQ.
"""
converted_map = []
for k, v in zip(value.keys(), value.values()):
conv... |
Send an email with html content using sendgrid. | def send_email(to, subject, html_content, files=None, dryrun=False, cc=None,
bcc=None, mime_subtype='mixed', sandbox_mode=False, **kwargs):
"""
Send an email with html content using sendgrid.
To use this plugin:
0. include sendgrid subpackage as part of your Airflow installation, e.g.,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.