INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Delete a dataset of Big query in your project.: param project_id: The name of the project where we have the dataset.: type project_id: str: param dataset_id: The dataset to be delete.: type dataset_id: str: return:
def delete_dataset(self, project_id, dataset_id): """ Delete a dataset of Big query in your project. :param project_id: The name of the project where we have the dataset . :type project_id: str :param dataset_id: The dataset to be delete. :type dataset_id: str :re...
Method returns dataset_resource if dataset exist and raised 404 error if dataset does not exist
def get_dataset(self, dataset_id, project_id=None): """ Method returns dataset_resource if dataset exist and raised 404 error if dataset does not exist :param dataset_id: The BigQuery Dataset ID :type dataset_id: str :param project_id: The GCP Project ID :type pr...
Method returns full list of BigQuery datasets in the current project
def get_datasets_list(self, project_id=None): """ Method returns full list of BigQuery datasets in the current project .. seealso:: For more information, see: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list :param project_id: Google Cloud ...
Method to stream data into BigQuery one record at a time without needing to run a load job
def insert_all(self, project_id, dataset_id, table_id, rows, ignore_unknown_values=False, skip_invalid_rows=False, fail_on_error=False): """ Method to stream data into BigQuery one record at a time without needing to run a load job .. seealso:: ...
Executes a BigQuery query and returns the job ID.
def execute(self, operation, parameters=None): """ Executes a BigQuery query, and returns the job ID. :param operation: The query to execute. :type operation: str :param parameters: Parameters to substitute into the query. :type parameters: dict """ sql =...
Execute a BigQuery query multiple times with different parameters.
def executemany(self, operation, seq_of_parameters): """ Execute a BigQuery query multiple times with different parameters. :param operation: The query to execute. :type operation: str :param seq_of_parameters: List of dictionary parameters to substitute into the que...
Helper method for fetchone which returns the next row from a buffer. If the buffer is empty attempts to paginate through the result set for the next page and load it into the buffer.
def next(self): """ Helper method for fetchone, which returns the next row from a buffer. If the buffer is empty, attempts to paginate through the result set for the next page, and load it into the buffer. """ if not self.job_id: return None if len(se...
Fetch the next set of rows of a query result returning a sequence of sequences ( e. g. a list of tuples ). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is not given the cursor s arraysize determines the number of rows to be fetc...
def fetchmany(self, size=None): """ Fetch the next set of rows of a query result, returning a sequence of sequences (e.g. a list of tuples). An empty sequence is returned when no more rows are available. The number of rows to fetch per call is specified by the parameter. If it is...
Fetch all ( remaining ) rows of a query result returning them as a sequence of sequences ( e. g. a list of tuples ).
def fetchall(self): """ Fetch all (remaining) rows of a query result, returning them as a sequence of sequences (e.g. a list of tuples). """ result = [] while True: one = self.fetchone() if one is None: break else: ...
Loads the manifest file and register the url_for_asset_ template tag.: param app:: return:
def configure_manifest_files(app): """ Loads the manifest file and register the `url_for_asset_` template tag. :param app: :return: """ def parse_manifest_json(): # noinspection PyBroadException try: global manifest manifest_file = os.path.join(os.path.di...
Queries Postgres and returns a cursor to the results.
def _query_postgres(self): """ Queries Postgres and returns a cursor to the results. """ postgres = PostgresHook(postgres_conn_id=self.postgres_conn_id) conn = postgres.get_conn() cursor = conn.cursor() cursor.execute(self.sql, self.parameters) return curs...
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 ...
Takes a value from Postgres and converts it to a value that s safe for JSON/ Google Cloud Storage/ BigQuery. Dates are converted to UTC seconds. Decimals are converted to floats. Times are converted to seconds.
def convert_types(cls, value): """ Takes a value from Postgres, and converts it to a value that's safe for JSON/Google Cloud Storage/BigQuery. Dates are converted to UTC seconds. Decimals are converted to floats. Times are converted to seconds. """ if type(value) in (date...
Create all the intermediate directories in a remote host
def _make_intermediate_dirs(sftp_client, remote_directory): """ Create all the intermediate directories in a remote host :param sftp_client: A Paramiko SFTP client. :param remote_directory: Absolute Path of the directory containing the file :return: """ if remote_directory == '/': s...
Create queue using connection object
def create_queue(self, queue_name, attributes=None): """ Create queue using connection object :param queue_name: name of the queue. :type queue_name: str :param attributes: additional attributes for the queue (default: None) For details of the attributes parameter se...
Send message to the queue
def send_message(self, queue_url, message_body, delay_seconds=0, message_attributes=None): """ Send message to the queue :param queue_url: queue url :type queue_url: str :param message_body: the contents of the message :type message_body: str :param delay_seconds...
Integrate plugins to the context
def _integrate_plugins(): """Integrate plugins to the context""" from airflow.plugins_manager import hooks_modules for hooks_module in hooks_modules: sys.modules[hooks_module.__name__] = hooks_module globals()[hooks_module._name] = hooks_module
Run the task command.
def run_command(self, run_with=None, join_args=False): """ Run the task command. :param run_with: list of tokens to run the task command with e.g. ``['bash', '-c']`` :type run_with: list :param join_args: whether to concatenate the list of command tokens e.g. ``['airflow', 'run'...
A callback that should be called when this is done running.
def on_finish(self): """ A callback that should be called when this is done running. """ if self._cfg_path and os.path.isfile(self._cfg_path): if self.run_as_user: subprocess.call(['sudo', 'rm', self._cfg_path], close_fds=True) else: ...
Parse options and process commands
def _main(): """ Parse options and process commands """ # Parse arguments usage = "usage: nvd3.py [options]" parser = OptionParser(usage=usage, version=("python-nvd3 - Charts generator with " "nvd3.js and d3.js")) parser.add_option...
add serie - Series are list of data that will be plotted y { 1 2 3 4 5 }/ x { 1 2 3 4 5 }
def add_serie(self, y, x, name=None, extra=None, **kwargs): """ add serie - Series are list of data that will be plotted y {1, 2, 3, 4, 5} / x {1, 2, 3, 4, 5} **Attributes**: * ``name`` - set Serie name * ``x`` - x-axis data * ``y`` - y-axis data ...
Build HTML content only no header or body tags. To be useful this will usually require the attribute juqery_on_ready to be set which will wrap the js in $ ( function () { <regular_js > } ; )
def buildcontent(self): """Build HTML content only, no header or body tags. To be useful this will usually require the attribute `juqery_on_ready` to be set which will wrap the js in $(function(){<regular_js>};) """ self.buildcontainer() # if the subclass has a method bui...
Build the HTML page Create the htmlheader with css/ js Create html page Add Js code for nvd3
def buildhtml(self): """Build the HTML page Create the htmlheader with css / js Create html page Add Js code for nvd3 """ self.buildcontent() self.content = self.htmlcontent self.htmlcontent = self.template_page_nvd3.render(chart=self)
generate HTML header content
def buildhtmlheader(self): """generate HTML header content""" self.htmlheader = '' # If the JavaScript assets have already been injected, don't bother re-sourcing them. global _js_initialized if '_js_initialized' not in globals() or not _js_initialized: for css in sel...
generate HTML div
def buildcontainer(self): """generate HTML div""" if self.container: return # Create SVG div with style if self.width: if self.width[-1] != '%': self.style += 'width:%spx;' % self.width else: self.style += 'width:%s;' %...
generate javascript code for the chart
def buildjschart(self): """generate javascript code for the chart""" self.jschart = '' # add custom tooltip string in jschart # default condition (if build_custom_tooltip is not called explicitly with date_flag=True) if self.tooltip_condition_string == '': self.toolt...
Create X - axis
def create_x_axis(self, name, label=None, format=None, date=False, custom_format=False): """Create X-axis""" axis = {} if custom_format and format: axis['tickFormat'] = format elif format: if format == 'AM_PM': axis['tickFormat'] = "function(d) { r...
Create Y - axis
def create_y_axis(self, name, label=None, format=None, custom_format=False): """ Create Y-axis """ axis = {} if custom_format and format: axis['tickFormat'] = format elif format: axis['tickFormat'] = "d3.format(',%s')" % format if label: ...
Build HTML content only no header or body tags. To be useful this will usually require the attribute juqery_on_ready to be set which will wrap the js in $ ( function () { <regular_js > } ; )
def buildcontent(self): """Build HTML content only, no header or body tags. To be useful this will usually require the attribute `juqery_on_ready` to be set which will wrap the js in $(function(){<regular_js>};) """ self.buildcontainer() # if the subclass has a method bui...
Returns a sqlite connection object
def get_conn(self): """ Returns a sqlite connection object """ conn = self.get_connection(self.sqlite_conn_id) conn = sqlite3.connect(conn.host) return conn
Decorator to log user actions
def action_logging(f): """ Decorator to log user actions """ @functools.wraps(f) def wrapper(*args, **kwargs): with create_session() as session: if g.user.is_anonymous: user = 'anonymous' else: user = g.user.username log =...
Decorator to make a view compressed
def gzipped(f): """ Decorator to make a view compressed """ @functools.wraps(f) def view_func(*args, **kwargs): @after_this_request def zipper(response): accept_encoding = request.headers.get('Accept-Encoding', '') if 'gzip' not in accept_encoding.lower(): ...
Decorator to check whether the user has read/ write permission on the dag.
def has_dag_access(**dag_kwargs): """ Decorator to check whether the user has read / write permission on the dag. """ def decorator(f): @functools.wraps(f) def wrapper(self, *args, **kwargs): has_access = self.appbuilder.sm.has_access dag_id = request.args.get('da...
Returns the last dag run for a dag None if there was none. Last dag run can be any type of run eg. scheduled or backfilled. Overridden DagRuns are ignored.
def get_last_dagrun(dag_id, session, include_externally_triggered=False): """ Returns the last dag run for a dag, None if there was none. Last dag run can be any type of run eg. scheduled or backfilled. Overridden DagRuns are ignored. """ DR = DagRun query = session.query(DR).filter(DR.dag_i...
Creates a dag run from this dag including the tasks associated with this dag. Returns the dag run.
def create_dagrun(self, run_id, state, execution_date, start_date=None, external_trigger=False, conf=None, session=None): """ Creates a dag run from t...
Publish the message to SQS queue
def execute(self, context): """ Publish the message to SQS queue :param context: the context object :type context: dict :return: dict with information about the message sent For details of the returned dict see :py:meth:`botocore.client.SQS.send_message` :rty...
Generates the HTML for a paging component using a similar logic to the paging auto - generated by Flask managed views. The paging component defines a number of pages visible in the pager ( window ) and once the user goes to a page beyond the largest visible it would scroll to the right the page numbers and keeps the cu...
def generate_pages(current_page, num_of_pages, search=None, showPaused=None, window=7): """ Generates the HTML for a paging component using a similar logic to the paging auto-generated by Flask managed views. The paging component defines a number of pages visible in the pager (window)...
returns a json response from a json serializable python object
def json_response(obj): """ returns a json response from a json serializable python object """ return Response( response=json.dumps( obj, indent=4, cls=AirflowJsonEncoder), status=200, mimetype="application/json")
Opens the given file. If the path contains a folder with a. zip suffix then the folder is treated as a zip archive opening the file inside the archive.
def open_maybe_zipped(f, mode='r'): """ Opens the given file. If the path contains a folder with a .zip suffix, then the folder is treated as a zip archive, opening the file inside the archive. :return: a file object, as in `open`, or as in `ZipFile.open`. """ _, archive, filename = ZIP_REGEX....
Used by cache to get a unique key per URL
def make_cache_key(*args, **kwargs): """ Used by cache to get a unique key per URL """ path = request.path args = str(hash(frozenset(request.args.items()))) return (path + args).encode('ascii', 'ignore')
Returns Gcp Video Intelligence Service client
def get_conn(self): """ Returns Gcp Video Intelligence Service client :rtype: google.cloud.videointelligence_v1.VideoIntelligenceServiceClient """ if not self._conn: self._conn = VideoIntelligenceServiceClient(credentials=self._get_credentials()) return self....
Performs video annotation.
def annotate_video( self, input_uri=None, input_content=None, features=None, video_context=None, output_uri=None, location=None, retry=None, timeout=None, metadata=None, ): """ Performs video annotation. :param ...
Get Opsgenie api_key for creating alert
def _get_api_key(self): """ Get Opsgenie api_key for creating alert """ conn = self.get_connection(self.http_conn_id) api_key = conn.password if not api_key: raise AirflowException('Opsgenie API Key is required for this hook, ' ...
Overwrite HttpHook get_conn because this hook just needs base_url and headers and does not need generic params
def get_conn(self, headers=None): """ Overwrite HttpHook get_conn because this hook just needs base_url and headers, and does not need generic params :param headers: additional headers to be passed through as a dictionary :type headers: dict """ conn = self.get_c...
Execute the Opsgenie Alert call
def execute(self, payload={}): """ Execute the Opsgenie Alert call :param payload: Opsgenie API Create Alert payload values See https://docs.opsgenie.com/docs/alert-api#section-create-alert :type payload: dict """ api_key = self._get_api_key() return ...
Execute the bash command in a temporary directory which will be cleaned afterwards
def poke(self, context): """ Execute the bash command in a temporary directory which will be cleaned afterwards """ bash_command = self.bash_command self.log.info("Tmp dir root location: \n %s", gettempdir()) with TemporaryDirectory(prefix='airflowtmp') as tmp_dir...
Construct the Opsgenie JSON payload. All relevant parameters are combined here to a valid Opsgenie JSON payload.
def _build_opsgenie_payload(self): """ Construct the Opsgenie JSON payload. All relevant parameters are combined here to a valid Opsgenie JSON payload. :return: Opsgenie payload (dict) to send """ payload = {} for key in [ "message", "alias", "descri...
Call the OpsgenieAlertHook to post message
def execute(self, context): """ Call the OpsgenieAlertHook to post message """ self.hook = OpsgenieAlertHook(self.opsgenie_conn_id) self.hook.execute(self._build_opsgenie_payload())
check if aws conn exists already or create one and return it
def get_conn(self): """ check if aws conn exists already or create one and return it :return: boto3 session """ if not self.conn: self.conn = self.get_client_type('athena') return self.conn
Run Presto query on athena with provided config and return submitted query_execution_id
def run_query(self, query, query_context, result_configuration, client_request_token=None): """ Run Presto query on athena with provided config and return submitted query_execution_id :param query: Presto query to run :type query: str :param query_context: Context in which query...
Fetch the status of submitted athena query. Returns None or one of valid query states.
def check_query_status(self, query_execution_id): """ Fetch the status of submitted athena query. Returns None or one of valid query states. :param query_execution_id: Id of submitted athena query :type query_execution_id: str :return: str """ response = self.con...
Fetch submitted athena query results. returns none if query is in intermediate state or failed/ cancelled state else dict of query output
def get_query_results(self, query_execution_id): """ Fetch submitted athena query results. returns none if query is in intermediate state or failed/cancelled state else dict of query output :param query_execution_id: Id of submitted athena query :type query_execution_id: str ...
Poll the status of submitted athena query until query state reaches final state. Returns one of the final states
def poll_query_status(self, query_execution_id, max_tries=None): """ Poll the status of submitted athena query until query state reaches final state. Returns one of the final states :param query_execution_id: Id of submitted athena query :type query_execution_id: str :pa...
Returns an SFTP connection object
def get_conn(self): """ Returns an SFTP connection object """ if self.conn is None: cnopts = pysftp.CnOpts() if self.no_host_key_check: cnopts.hostkeys = None cnopts.compression = self.compress conn_params = { ...
Returns a dictionary of { filename: { attributes }} for all files on the remote system ( where the MLSD command is supported ).: param path: full path to the remote directory: type path: str
def describe_directory(self, path): """ Returns a dictionary of {filename: {attributes}} for all files on the remote system (where the MLSD command is supported). :param path: full path to the remote directory :type path: str """ conn = self.get_conn() fli...
Returns a list of files on the remote system.: param path: full path to the remote directory to list: type path: str
def list_directory(self, path): """ Returns a list of files on the remote system. :param path: full path to the remote directory to list :type path: str """ conn = self.get_conn() files = conn.listdir(path) return files
Creates a directory on the remote system.: param path: full path to the remote directory to create: type path: str: param mode: int representation of octal mode for directory
def create_directory(self, path, mode=777): """ Creates a directory on the remote system. :param path: full path to the remote directory to create :type path: str :param mode: int representation of octal mode for directory """ conn = self.get_conn() conn.m...
Transfers the remote file to a local location. If local_full_path is a string path the file will be put at that location: param remote_full_path: full path to the remote file: type remote_full_path: str: param local_full_path: full path to the local file: type local_full_path: str
def retrieve_file(self, remote_full_path, local_full_path): """ Transfers the remote file to a local location. If local_full_path is a string path, the file will be put at that location :param remote_full_path: full path to the remote file :type remote_full_path: str ...
Transfers a local file to the remote location. If local_full_path_or_buffer is a string path the file will be read from that location: param remote_full_path: full path to the remote file: type remote_full_path: str: param local_full_path: full path to the local file: type local_full_path: str
def store_file(self, remote_full_path, local_full_path): """ Transfers a local file to the remote location. If local_full_path_or_buffer is a string path, the file will be read from that location :param remote_full_path: full path to the remote file :type remote_full_path...
Sleep for the time specified in the exception. If not specified wait for 60 seconds.
def __handle_rate_limit_exception(self, rate_limit_exception): """ Sleep for the time specified in the exception. If not specified, wait for 60 seconds. """ retry_after = int( rate_limit_exception.response.headers.get('Retry-After', 60)) self.log.info( ...
Call Zendesk API and return results
def call(self, path, query=None, get_all_pages=True, side_loading=False): """ Call Zendesk API and return results :param path: The Zendesk API to call :param query: Query parameters :param get_all_pages: Accumulate results over all pages before returning. Due to s...
Retrieves the partition values for a table.
def get_partitions(self, database_name, table_name, expression='', page_size=None, max_items=None): """ Retrieves the partition values for a table. :param database_name: The name o...
Checks whether a partition exists
def check_for_partition(self, database_name, table_name, expression): """ Checks whether a partition exists :param database_name: Name of hive database (schema) @table belongs to :type database_name: str :param table_name: Name of hive table @partition belongs to :type t...
Get the information of the table
def get_table(self, database_name, table_name): """ Get the information of the table :param database_name: Name of hive database (schema) @table belongs to :type database_name: str :param table_name: Name of hive table :type table_name: str :rtype: dict ...
Get the physical location of the table
def get_table_location(self, database_name, table_name): """ Get the physical location of the table :param database_name: Name of hive database (schema) @table belongs to :type database_name: str :param table_name: Name of hive table :type table_name: str :return...
Return status of a cluster
def cluster_status(self, cluster_identifier): """ Return status of a cluster :param cluster_identifier: unique identifier of a cluster :type cluster_identifier: str """ conn = self.get_conn() try: response = conn.describe_clusters( Clu...
Delete a cluster and optionally create a snapshot
def delete_cluster( self, cluster_identifier, skip_final_cluster_snapshot=True, final_cluster_snapshot_identifier=''): """ Delete a cluster and optionally create a snapshot :param cluster_identifier: unique identifier of a cluster :type cl...
Gets a list of snapshots for a cluster
def describe_cluster_snapshots(self, cluster_identifier): """ Gets a list of snapshots for a cluster :param cluster_identifier: unique identifier of a cluster :type cluster_identifier: str """ response = self.get_conn().describe_cluster_snapshots( ClusterIden...
Restores a cluster from its snapshot
def restore_from_cluster_snapshot(self, cluster_identifier, snapshot_identifier): """ Restores a cluster from its snapshot :param cluster_identifier: unique identifier of a cluster :type cluster_identifier: str :param snapshot_identifier: unique identifier for a snapshot of a cl...
Creates a snapshot of a cluster
def create_cluster_snapshot(self, snapshot_identifier, cluster_identifier): """ Creates a snapshot of a cluster :param snapshot_identifier: unique identifier for a snapshot of a cluster :type snapshot_identifier: str :param cluster_identifier: unique identifier of a cluster ...
SlackAPIOperator calls will not fail even if the call is not unsuccessful. It should not prevent a DAG from completing in success
def execute(self, **kwargs): """ SlackAPIOperator calls will not fail even if the call is not unsuccessful. It should not prevent a DAG from completing in success """ if not self.api_params: self.construct_api_call_params() slack = SlackHook(token=self.token, ...
Args: volume ( Volume ):
def add_volume(self, volume): """ Args: volume (Volume): """ self._add_volume(name=volume.name, configs=volume.configs)
Args: volume_mount ( VolumeMount ):
def add_mount(self, volume_mount): """ Args: volume_mount (VolumeMount): """ self._add_mount( name=volume_mount.name, mount_path=volume_mount.mount_path, sub_path=volume_mount.sub_path, read_only=volume_mount.r...
Creates a job flow using the config from the EMR connection. Keys of the json extra hash may have the arguments of the boto3 run_job_flow method. Overrides for this config may be passed as the job_flow_overrides.
def create_job_flow(self, job_flow_overrides): """ Creates a job flow using the config from the EMR connection. Keys of the json extra hash may have the arguments of the boto3 run_job_flow method. Overrides for this config may be passed as the job_flow_overrides. """ ...
Will test the filepath result and test if its size is at least self. filesize
def filter_for_filesize(result, size=None): """ Will test the filepath result and test if its size is at least self.filesize :param result: a list of dicts returned by Snakebite ls :param size: the file size in MB a file should be at least to trigger True :return: (bool) dependi...
Will filter if instructed to do so the result to remove matching criteria
def filter_for_ignored_ext(result, ignored_ext, ignore_copying): """ Will filter if instructed to do so the result to remove matching criteria :param result: list of dicts returned by Snakebite ls :type result: list[dict] :param ignored_ext: list of ignored extensions :t...
Executed by task_instance at runtime
def execute(self, context): """ Executed by task_instance at runtime """ s3_conn = S3Hook(self.s3_conn_id) # Grab collection and execute query according to whether or not it is a pipeline if self.is_pipeline: results = MongoHook(self.mongo_conn_id).aggregate(...
Takes an iterable ( pymongo Cursor or Array ) containing dictionaries and returns a stringified version using python join
def _stringify(iterable, joinable='\n'): """ Takes an iterable (pymongo Cursor or Array) containing dictionaries and returns a stringified version using python join """ return joinable.join( [json.dumps(doc, default=json_util.default) for doc in iterable] )
Get pool by a given name.
def get_pool(name, session=None): """Get pool by a given name.""" if not (name and name.strip()): raise AirflowBadRequest("Pool name shouldn't be empty") pool = session.query(Pool).filter_by(pool=name).first() if pool is None: raise PoolNotFound("Pool '%s' doesn't exist" % name) re...
Create a pool with a given parameters.
def create_pool(name, slots, description, session=None): """Create a pool with a given parameters.""" if not (name and name.strip()): raise AirflowBadRequest("Pool name shouldn't be empty") try: slots = int(slots) except ValueError: raise AirflowBadRequest("Bad value for `slots`...
Delete pool by a given name.
def delete_pool(name, session=None): """Delete pool by a given name.""" if not (name and name.strip()): raise AirflowBadRequest("Pool name shouldn't be empty") pool = session.query(Pool).filter_by(pool=name).first() if pool is None: raise PoolNotFound("Pool '%s' doesn't exist" % name) ...
Converts a python dictionary to the proto supplied
def _dict_to_proto(py_dict, proto): """ Converts a python dictionary to the proto supplied :param py_dict: The dictionary to convert :type py_dict: dict :param proto: The proto object to merge with dictionary :type proto: protobuf :return: A parsed python diction...
Given an operation continuously fetches the status from Google Cloud until either completion or an error occurring
def wait_for_operation(self, operation, project_id=None): """ Given an operation, continuously fetches the status from Google Cloud until either completion or an error occurring :param operation: The Operation to wait for :type operation: google.cloud.container_V1.gapic.enums.Op...
Fetches the operation from Google Cloud
def get_operation(self, operation_name, project_id=None): """ Fetches the operation from Google Cloud :param operation_name: Name of operation to fetch :type operation_name: str :param project_id: Google Cloud Platform project ID :type project_id: str :return: Th...
Append labels to provided Cluster Protobuf
def _append_label(cluster_proto, key, val): """ Append labels to provided Cluster Protobuf Labels must fit the regex ``[a-z]([-a-z0-9]*[a-z0-9])?`` (current airflow version string follows semantic versioning spec: x.y.z). :param cluster_proto: The proto to append resource_labe...
Deletes the cluster including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resources that might be in use by the cluster ( e. g. load balancer resources ) will not be deleted if they weren’t present at the i...
def delete_cluster(self, name, project_id=None, retry=DEFAULT, timeout=DEFAULT): """ Deletes the cluster, including the Kubernetes endpoint and all worker nodes. Firewalls and routes that were configured during cluster creation are also deleted. Other Google Compute Engine resour...
Creates a cluster consisting of the specified number and type of Google Compute Engine instances.
def create_cluster(self, cluster, project_id=None, retry=DEFAULT, timeout=DEFAULT): """ Creates a cluster, consisting of the specified number and type of Google Compute Engine instances. :param cluster: A Cluster protobuf or dict. If dict is provided, it must be of the same ...
Gets details of specified cluster
def get_cluster(self, name, project_id=None, retry=DEFAULT, timeout=DEFAULT): """ Gets details of specified cluster :param name: The name of the cluster to retrieve :type name: str :param project_id: Google Cloud Platform project ID :type project_id: str :param r...
Given a Discord http_conn_id return the default webhook endpoint or override if a webhook_endpoint is manually supplied.
def _get_webhook_endpoint(self, http_conn_id, webhook_endpoint): """ Given a Discord http_conn_id, return the default webhook endpoint or override if a webhook_endpoint is manually supplied. :param http_conn_id: The provided connection ID :param webhook_endpoint: The manually pr...
Construct the Discord JSON payload. All relevant parameters are combined here to a valid Discord JSON payload.
def _build_discord_payload(self): """ Construct the Discord JSON payload. All relevant parameters are combined here to a valid Discord JSON payload. :return: Discord payload (str) to send """ payload = {} if self.username: payload['username'] = self....
Execute the Discord webhook call
def execute(self): """ Execute the Discord webhook call """ proxies = {} if self.proxy: # we only need https proxy for Discord proxies = {'https': self.proxy} discord_payload = self._build_discord_payload() self.run(endpoint=self.webhook_...
Encrypts a plaintext message using Google Cloud KMS.
def encrypt(self, key_name, plaintext, authenticated_data=None): """ Encrypts a plaintext message using Google Cloud KMS. :param key_name: The Resource Name for the key (or key version) to be used for encyption. Of the form ``projects/*/location...
Remote Popen
def Popen(self, cmd, **kwargs): """ Remote Popen :param cmd: command to remotely execute :param kwargs: extra arguments to Popen (see subprocess.Popen) :return: handle to subprocess """ masked_cmd = ' '.join(self.cmd_mask_password(cmd)) self.log.info("Exe...
Imports table from remote location to target dir. Arguments are copies of direct sqoop command line arguments
def import_table(self, table, target_dir=None, append=False, file_type="text", columns=None, split_by=None, where=None, direct=False, driver=None, extra_import_options=None): """ Imports table from remote location to target dir. Arguments are copies of d...
Imports a specific query from the rdbms to hdfs
def import_query(self, query, target_dir, append=False, file_type="text", split_by=None, direct=None, driver=None, extra_import_options=None): """ Imports a specific query from the rdbms to hdfs :param query: Free format query to run :param target_dir: HDFS destinat...
Exports Hive table to remote location. Arguments are copies of direct sqoop command line Arguments
def export_table(self, table, export_dir, input_null_string, input_null_non_string, staging_table, clear_staging_table, enclosed_by, escaped_by, input_fields_terminated_by, input_lines_terminated_by, input_optionall...
Retrieves connection to Cloud Text to Speech.
def get_conn(self): """ Retrieves connection to Cloud Text to Speech. :return: Google Cloud Text to Speech client object. :rtype: google.cloud.texttospeech_v1.TextToSpeechClient """ if not self._client: self._client = TextToSpeechClient(credentials=self._get_...
Synthesizes text input
def synthesize_speech(self, input_data, voice, audio_config, retry=None, timeout=None): """ Synthesizes text input :param input_data: text input to be synthesized. See more: https://googleapis.github.io/google-cloud-python/latest/texttospeech/gapic/v1/types.html#google.cloud.texttos...
Close and upload local log file to remote storage S3.
def close(self): """ Close and upload local log file to remote storage S3. """ # 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 # ...