INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a Google Cloud Storage service object.
def get_conn(self): """ Returns a Google Cloud Storage service object. """ if not self._conn: self._conn = storage.Client(credentials=self._get_credentials()) return self._conn
Copies an object from a bucket to another with renaming if requested.
def copy(self, source_bucket, source_object, destination_bucket=None, destination_object=None): """ Copies an object from a bucket to another, with renaming if requested. destination_bucket or destination_object can be omitted, in which case source bucket/object is used, bu...
Has the same functionality as copy except that will work on files over 5 TB as well as when copying between locations and/ or storage classes.
def rewrite(self, source_bucket, source_object, destination_bucket, destination_object=None): """ Has the same functionality as copy, except that will work on files over 5 TB, as well as when copying between locations and/or storage classes. destination_object ca...
Get a file from Google Cloud Storage.
def download(self, bucket_name, object_name, filename=None): """ Get a file from Google Cloud Storage. :param bucket_name: The bucket to fetch from. :type bucket_name: str :param object_name: The object to fetch. :type object_name: str :param filename: If set, a ...
Uploads a local file to Google Cloud Storage.
def upload(self, bucket_name, object_name, filename, mime_type='application/octet-stream', gzip=False): """ Uploads a local file to Google Cloud Storage. :param bucket_name: The bucket to upload to. :type bucket_name: str :param object_name: The object name to set...
Checks for the existence of a file in Google Cloud Storage.
def exists(self, bucket_name, object_name): """ Checks for the existence of a file in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the object is. :type bucket_name: str :param object_name: The name of the blob_name to check in the Google cloud ...
Checks if an blob_name is updated in Google Cloud Storage.
def is_updated_after(self, bucket_name, object_name, ts): """ Checks if an blob_name is updated in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the object is. :type bucket_name: str :param object_name: The name of the object to check in the Goo...
Deletes an object from the bucket.
def delete(self, bucket_name, object_name): """ Deletes an object from the bucket. :param bucket_name: name of the bucket, where the object resides :type bucket_name: str :param object_name: name of the object to delete :type object_name: str """ client =...
List all objects from the bucket with the give string prefix in name
def list(self, bucket_name, versions=None, max_results=None, prefix=None, delimiter=None): """ List all objects from the bucket with the give string prefix in name :param bucket_name: bucket name :type bucket_name: str :param versions: if true, list all versions of the objects ...
Gets the size of a file in Google Cloud Storage.
def get_size(self, bucket_name, object_name): """ Gets the size of a file in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the blob_name is. :type bucket_name: str :param object_name: The name of the object to check in the Google clo...
Gets the CRC32c checksum of an object in Google Cloud Storage.
def get_crc32c(self, bucket_name, object_name): """ Gets the CRC32c checksum of an object in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the blob_name is. :type bucket_name: str :param object_name: The name of the object to check in the Google...
Gets the MD5 hash of an object in Google Cloud Storage.
def get_md5hash(self, bucket_name, object_name): """ Gets the MD5 hash of an object in Google Cloud Storage. :param bucket_name: The Google cloud storage bucket where the blob_name is. :type bucket_name: str :param object_name: The name of the object to check in the Google cloud...
Creates a new bucket. Google Cloud Storage uses a flat namespace so you can t create a bucket with a name that is already in use.
def create_bucket(self, bucket_name, resource=None, storage_class='MULTI_REGIONAL', location='US', project_id=None, labels=None ): """ Creates a new b...
Creates a new ACL entry on the specified bucket_name. See: https:// cloud. google. com/ storage/ docs/ json_api/ v1/ bucketAccessControls/ insert
def insert_bucket_acl(self, bucket_name, entity, role, user_project=None): """ Creates a new ACL entry on the specified bucket_name. See: https://cloud.google.com/storage/docs/json_api/v1/bucketAccessControls/insert :param bucket_name: Name of a bucket_name. :type bucket_name: s...
Creates a new ACL entry on the specified object. See: https:// cloud. google. com/ storage/ docs/ json_api/ v1/ objectAccessControls/ insert
def insert_object_acl(self, bucket_name, object_name, entity, role, user_project=None): """ Creates a new ACL entry on the specified object. See: https://cloud.google.com/storage/docs/json_api/v1/objectAccessControls/insert :param bucket_name: Name of a bucket_name. :type bucket...
Composes a list of existing object into a new object in the same storage bucket_name
def compose(self, bucket_name, source_objects, destination_object): """ Composes a list of existing object into a new object in the same storage bucket_name Currently it only supports up to 32 objects that can be concatenated in a single operation https://cloud.google.com/stora...
Return the index i in arr that minimizes f ( arr [ i ] )
def argmin(arr, f): """Return the index, i, in arr that minimizes f(arr[i])""" m = None i = None for idx, item in enumerate(arr): if item is not None: if m is None or f(item) < m: m = f(item) i = idx return i
Returns true if training job s secondary status message has changed.
def secondary_training_status_changed(current_job_description, prev_job_description): """ Returns true if training job's secondary status message has changed. :param current_job_description: Current job description, returned from DescribeTrainingJob call. :type current_job_description: dict :param ...
Returns a string contains start time and the secondary training job status message.
def secondary_training_status_message(job_description, prev_description): """ Returns a string contains start time and the secondary training job status message. :param job_description: Returned response from DescribeTrainingJob call :type job_description: dict :param prev_description: Previous job...
Tar the local file or directory and upload to s3
def tar_and_s3_upload(self, path, key, bucket): """ Tar the local file or directory and upload to s3 :param path: local file or directory :type path: str :param key: s3 key :type key: str :param bucket: s3 bucket :type bucket: str :return: None ...
Extract the S3 operations from the configuration and execute them.
def configure_s3_resources(self, config): """ Extract the S3 operations from the configuration and execute them. :param config: config of SageMaker operation :type config: dict :rtype: dict """ s3_operations = config.pop('S3Operations', None) if s3_opera...
Check if an S3 URL exists
def check_s3_url(self, s3url): """ Check if an S3 URL exists :param s3url: S3 url :type s3url: str :rtype: bool """ bucket, key = S3Hook.parse_s3_url(s3url) if not self.s3_hook.check_for_bucket(bucket_name=bucket): raise AirflowException( ...
Establish an AWS connection for retrieving logs during training
def get_log_conn(self): """ Establish an AWS connection for retrieving logs during training :rtype: CloudWatchLogs.Client """ config = botocore.config.Config(retries={'max_attempts': 15}) return self.get_client_type('logs', config=config)
Create a training job
def create_training_job(self, config, wait_for_completion=True, print_log=True, check_interval=30, max_ingestion_time=None): """ Create a training job :param config: the config for training :type config: dict :param wait_for_completion: if the program...
Create a tuning job
def create_tuning_job(self, config, wait_for_completion=True, check_interval=30, max_ingestion_time=None): """ Create a tuning job :param config: the config for tuning :type config: dict :param wait_for_completion: if the program should keep running unt...
Create a transform job
def create_transform_job(self, config, wait_for_completion=True, check_interval=30, max_ingestion_time=None): """ Create a transform job :param config: the config for transform job :type config: dict :param wait_for_completion: if the program should ...
Create an endpoint
def create_endpoint(self, config, wait_for_completion=True, check_interval=30, max_ingestion_time=None): """ Create an endpoint :param config: the config for endpoint :type config: dict :param wait_for_completion: if the program should keep running until ...
Return the training job info associated with job_name and print CloudWatch logs
def describe_training_job_with_log(self, job_name, positions, stream_names, instance_count, state, last_description, last_describe_job_call): """ Return the training job info associated with job_name and print CloudWatch logs ...
Check status of a SageMaker job
def check_status(self, job_name, key, describe_function, check_interval, max_ingestion_time, non_terminal_states=None): """ Check status of a SageMaker job :param job_name: name of the job to check status :type job_name: str...
Display the logs for a given training job optionally tailing them until the job is complete.
def check_training_status_with_log(self, job_name, non_terminal_states, failed_states, wait_for_completion, check_interval, max_ingestion_time): """ Display the logs for a given training job, optionally tailing them until the job is complete. :para...
Execute the python dataflow job.
def execute(self, context): """Execute the python dataflow job.""" bucket_helper = GoogleCloudBucketHelper( self.gcp_conn_id, self.delegate_to) self.py_file = bucket_helper.google_cloud_to_local(self.py_file) hook = DataFlowHook(gcp_conn_id=self.gcp_conn_id, ...
Checks whether the file specified by file_name is stored in Google Cloud Storage ( GCS ) if so downloads the file and saves it locally. The full path of the saved file will be returned. Otherwise the local file_name will be returned immediately.
def google_cloud_to_local(self, file_name): """ Checks whether the file specified by file_name is stored in Google Cloud Storage (GCS), if so, downloads the file and saves it locally. The full path of the saved file will be returned. Otherwise the local file_name will be returned...
Run migrations in offline mode.
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
Run migrations in online mode.
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = settings.engine with connectable.connect() as connection: context.configure( connection=connection, ...
Deletes the specified Cloud Bigtable instance. Raises google. api_core. exceptions. NotFound if the Cloud Bigtable instance does not exist.
def delete_instance(self, instance_id, project_id=None): """ Deletes the specified Cloud Bigtable instance. Raises google.api_core.exceptions.NotFound if the Cloud Bigtable instance does not exist. :param project_id: Optional, Google Cloud Platform project ID where the ...
Creates new instance.
def create_instance(self, instance_id, main_cluster_id, main_cluster_zone, project_id=None, replica_cluster_id=None, replica_cluster_zone=None, instance...
Creates the specified Cloud Bigtable table. Raises google. api_core. exceptions. AlreadyExists if the table exists.
def create_table(instance, table_id, initial_split_keys=None, column_families=None): """ Creates the specified Cloud Bigtable table. Raises ``google.api_core.exceptions.AlreadyExists`` if the table exists. :type instance: In...
Deletes the specified table in Cloud Bigtable. Raises google. api_core. exceptions. NotFound if the table does not exist.
def delete_table(self, instance_id, table_id, project_id=None): """ Deletes the specified table in Cloud Bigtable. Raises google.api_core.exceptions.NotFound if the table does not exist. :type instance_id: str :param instance_id: The ID of the Cloud Bigtable instance. :t...
Updates number of nodes in the specified Cloud Bigtable cluster. Raises google. api_core. exceptions. NotFound if the cluster does not exist.
def update_cluster(instance, cluster_id, nodes): """ Updates number of nodes in the specified Cloud Bigtable cluster. Raises google.api_core.exceptions.NotFound if the cluster does not exist. :type instance: Instance :param instance: The Cloud Bigtable instance that owns the clu...
This function creates the command list from available information
def _prepare_cli_cmd(self): """ This function creates the command list from available information """ conn = self.conn hive_bin = 'hive' cmd_extra = [] if self.use_beeline: hive_bin = 'beeline' jdbc_url = "jdbc:hive2://{host}:{port}/{schem...
This function prepares a list of hiveconf params from a dictionary of key value pairs.
def _prepare_hiveconf(d): """ This function prepares a list of hiveconf params from a dictionary of key value pairs. :param d: :type d: dict >>> hh = HiveCliHook() >>> hive_conf = {"hive.exec.dynamic.partition": "true", ... "hive.exec.dynamic.partition.m...
Run an hql statement using the hive cli. If hive_conf is specified it should be a dict and the entries will be set as key/ value pairs in HiveConf
def run_cli(self, hql, schema=None, verbose=True, hive_conf=None): """ Run an hql statement using the hive cli. If hive_conf is specified it should be a dict and the entries will be set as key/value pairs in HiveConf :param hive_conf: if specified these key value pairs will be ...
Loads a pandas DataFrame into hive.
def load_df( self, df, table, field_dict=None, delimiter=',', encoding='utf8', pandas_kwargs=None, **kwargs): """ Loads a pandas DataFrame into hive. Hive data types will be inferred if not passed but column nam...
Loads a local file into Hive
def load_file( self, filepath, table, delimiter=",", field_dict=None, create=True, overwrite=True, partition=None, recreate=False, tblproperties=None): """ Loads a local file into Hive...
Returns a Hive thrift client.
def get_metastore_client(self): """ Returns a Hive thrift client. """ import hmsclient from thrift.transport import TSocket, TTransport from thrift.protocol import TBinaryProtocol ms = self.metastore_conn auth_mechanism = ms.extra_dejson.get('authMechanism...
Checks whether a partition exists
def check_for_partition(self, schema, table, partition): """ Checks whether a partition exists :param schema: Name of hive schema (database) @table belongs to :type schema: str :param table: Name of hive table @partition belongs to :type schema: str :partition: E...
Checks whether a partition with a given name exists
def check_for_named_partition(self, schema, table, partition_name): """ Checks whether a partition with a given name exists :param schema: Name of hive schema (database) @table belongs to :type schema: str :param table: Name of hive table @partition belongs to :type sche...
Get a metastore table object
def get_table(self, table_name, db='default'): """Get a metastore table object >>> hh = HiveMetastoreHook() >>> t = hh.get_table(db='airflow', table_name='static_babynames') >>> t.tableName 'static_babynames' >>> [col.name for col in t.sd.cols] ['state', 'year', ...
Get a metastore table object
def get_tables(self, db, pattern='*'): """ Get a metastore table object """ with self.metastore as client: tables = client.get_tables(db_name=db, pattern=pattern) return client.get_table_objects_by_name(db, tables)
Returns a list of all partitions in a table. Works only for tables with less than 32767 ( java short max val ). For subpartitioned table the number might easily exceed this.
def get_partitions( self, schema, table_name, filter=None): """ Returns a list of all partitions in a table. Works only for tables with less than 32767 (java short max val). For subpartitioned table, the number might easily exceed this. >>> hh = HiveMetastoreHook() ...
Helper method to get max partition of partitions with partition_key from part specs. key: value pair in filter_map will be used to filter out partitions.
def _get_max_partition_from_part_specs(part_specs, partition_key, filter_map): """ Helper method to get max partition of partitions with partition_key from part specs. key:value pair in filter_map will be used to filter out partitions. :param part_specs: list of partition specs....
Returns the maximum value for all partitions with given field in a table. If only one partition key exist in the table the key will be used as field. filter_map should be a partition_key: partition_value map and will be used to filter out partitions.
def max_partition(self, schema, table_name, field=None, filter_map=None): """ Returns the maximum value for all partitions with given field in a table. If only one partition key exist in the table, the key will be used as field. filter_map should be a partition_key:partition_value map an...
Check if table exists
def table_exists(self, table_name, db='default'): """ Check if table exists >>> hh = HiveMetastoreHook() >>> hh.table_exists(db='airflow', table_name='static_babynames') True >>> hh.table_exists(db='airflow', table_name='does_not_exist') False """ ...
Returns a Hive connection object.
def get_conn(self, schema=None): """ Returns a Hive connection object. """ db = self.get_connection(self.hiveserver2_conn_id) auth_mechanism = db.extra_dejson.get('authMechanism', 'NONE') if auth_mechanism == 'NONE' and db.login is None: # we need to give a us...
Get results of the provided hql in target schema.
def get_results(self, hql, schema='default', fetch_size=None, hive_conf=None): """ Get results of the provided hql in target schema. :param hql: hql to be executed. :type hql: str or list :param schema: target schema, default to 'default'. :type schema: str :para...
Execute hql in target schema and write results to a csv file.
def to_csv( self, hql, csv_filepath, schema='default', delimiter=',', lineterminator='\r\n', output_header=True, fetch_size=1000, hive_conf=None): """ Execute hql in target schema and write result...
Get a set of records from a Hive query.
def get_records(self, hql, schema='default', hive_conf=None): """ Get a set of records from a Hive query. :param hql: hql to be executed. :type hql: str or list :param schema: target schema, default to 'default'. :type schema: str :param hive_conf: hive_conf to e...
Get a pandas dataframe from a Hive query
def get_pandas_df(self, hql, schema='default'): """ Get a pandas dataframe from a Hive query :param hql: hql to be executed. :type hql: str or list :param schema: target schema, default to 'default'. :type schema: str :return: result of hql execution :rty...
Retrieves connection to Cloud Vision.
def get_conn(self): """ Retrieves connection to Cloud Vision. :return: Google Cloud Vision client object. :rtype: google.cloud.vision_v1.ProductSearchClient """ if not self._client: self._client = ProductSearchClient(credentials=self._get_credentials()) ...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductSetCreateOperator
def create_product_set( self, location, product_set, project_id=None, product_set_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVi...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductSetGetOperator
def get_product_set( self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetGetOperator` """ client = self.get_conn() ...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductSetUpdateOperator
def update_product_set( self, product_set, location=None, product_set_id=None, update_mask=None, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :class:`~airflow.contrib.operat...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductSetDeleteOperator
def delete_product_set( self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetDeleteOperator` """ client = self.get_conn() ...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductCreateOperator
def create_product( self, location, product, project_id=None, product_id=None, retry=None, timeout=None, metadata=None ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductCreateOperator` """ client = self.get_conn...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductGetOperator
def get_product(self, location, product_id, project_id=None, retry=None, timeout=None, metadata=None): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductGetOperator` """ client = self.get_conn() name = ProductSearchCli...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductUpdateOperator
def update_product( self, product, location=None, product_id=None, update_mask=None, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_visi...
For the documentation see:: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionProductDeleteOperator
def delete_product(self, location, product_id, project_id=None, retry=None, timeout=None, metadata=None): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductDeleteOperator` """ client = self.get_conn() name = ProductSea...
For the documentation see:: py: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionReferenceImageCreateOperator
def create_reference_image( self, location, product_id, reference_image, reference_image_id=None, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :py:class:`~airflow.contrib.op...
For the documentation see:: py: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionReferenceImageCreateOperator
def delete_reference_image( self, location, product_id, reference_image_id, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_operator.Cl...
For the documentation see:: py: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionAddProductToProductSetOperator
def add_product_to_product_set( self, product_set_id, product_id, location=None, project_id=None, retry=None, timeout=None, metadata=None, ): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_operat...
For the documentation see:: py: class: ~airflow. contrib. operators. gcp_vision_image_annotator_operator. CloudVisionAnnotateImage
def annotate_image(self, request, retry=None, timeout=None): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_image_annotator_operator.CloudVisionAnnotateImage` """ client = self.annotator_client self.log.info('Annotating image') r...
For the documentation see:: py: class: ~airflow. contrib. operators. gcp_vision_operator. CloudVisionDetectImageSafeSearchOperator
def safe_search_detection( self, image, max_results=None, retry=None, timeout=None, additional_properties=None ): """ For the documentation see: :py:class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionDetectImageSafeSearchOperator` """ client = self.annot...
Get Dingding endpoint for sending message.
def _get_endpoint(self): """ Get Dingding endpoint for sending message. """ conn = self.get_connection(self.http_conn_id) token = conn.password if not token: raise AirflowException('Dingding token is requests but get nothing, ' ...
Build different type of Dingding message As most commonly used type text message just need post message content rather than a dict like { content: message }
def _build_message(self): """ Build different type of Dingding message As most commonly used type, text message just need post message content rather than a dict like ``{'content': 'message'}`` """ if self.message_type in ['text', 'markdown']: data = { ...
Send Dingding message
def send(self): """ Send Dingding message """ support_type = ['text', 'link', 'markdown', 'actionCard', 'feedCard'] if self.message_type not in support_type: raise ValueError('DingdingWebhookHook only support {} ' 'so far, but receive {}'....
Endpoint for streaming log.: param ti: task instance object: param try_number: try_number of the task instance: param metadata: log metadata can be used for steaming log reading and auto - tailing.: return: a list of log documents and metadata.
def _read(self, ti, try_number, metadata=None): """ Endpoint for streaming log. :param ti: task instance object :param try_number: try_number of the task instance :param metadata: log metadata, can be used for steaming log reading and auto-tailing. ...
Returns the logs matching log_id in Elasticsearch and next offset. Returns if no log is found or there was an error.: param log_id: the log_id of the log to read.: type log_id: str: param offset: the offset start to read log from.: type offset: str
def es_read(self, log_id, offset): """ Returns the logs matching log_id in Elasticsearch and next offset. Returns '' if no log is found or there was an error. :param log_id: the log_id of the log to read. :type log_id: str :param offset: the offset start to read log from....
Helper method that binds parameters to a SQL query.
def _bind_parameters(operation, parameters): """ Helper method that binds parameters to a SQL query. """ # inspired by MySQL Python Connector (conversion.py) string_parameters = {} for (name, value) in iteritems(parameters): if value is None: string_parameters[name] = 'NULL' ...
Helper method that escapes parameters to a SQL query.
def _escape(s): """ Helper method that escapes parameters to a SQL query. """ e = s e = e.replace('\\', '\\\\') e = e.replace('\n', '\\n') e = e.replace('\r', '\\r') e = e.replace("'", "\\'") e = e.replace('"', '\\"') return e
Helper method that casts a BigQuery row to the appropriate data types. This is useful because BigQuery returns all fields as strings.
def _bq_cast(string_field, bq_type): """ Helper method that casts a BigQuery row to the appropriate data types. This is useful because BigQuery returns all fields as strings. """ if string_field is None: return None elif bq_type == 'INTEGER': return int(string_field) elif bq_...
function to check expected type and raise error if type is not correct
def _validate_value(key, value, expected_type): """ function to check expected type and raise error if type is not correct """ if not isinstance(value, expected_type): raise TypeError("{} argument must have a type {} not {}".format( key, expected_type, type(value)))
Returns a BigQuery PEP 249 connection object.
def get_conn(self): """ Returns a BigQuery PEP 249 connection object. """ service = self.get_service() project = self._get_field('project') return BigQueryConnection( service=service, project_id=project, use_legacy_sql=self.use_legacy_s...
Returns a BigQuery service object.
def get_service(self): """ Returns a BigQuery service object. """ http_authorized = self._authorize() return build( 'bigquery', 'v2', http=http_authorized, cache_discovery=False)
Returns a Pandas DataFrame for the results produced by a BigQuery query. The DbApiHook method must be overridden because Pandas doesn t support PEP 249 connections except for SQLite. See:
def get_pandas_df(self, sql, parameters=None, dialect=None): """ Returns a Pandas DataFrame for the results produced by a BigQuery query. The DbApiHook method must be overridden because Pandas doesn't support PEP 249 connections, except for SQLite. See: https://github.com/pydata...
Checks for the existence of a table in Google BigQuery.
def table_exists(self, project_id, dataset_id, table_id): """ Checks for the existence of a table in Google BigQuery. :param project_id: The Google cloud project in which to look for the table. The connection supplied to the hook must provide access to the specified proj...
Creates a new empty table in the dataset. To create a view which is defined by a SQL query parse a dictionary to view kwarg
def create_empty_table(self, project_id, dataset_id, table_id, schema_fields=None, time_partitioning=None, cluster_fields=None, lab...
Creates a new external table in the dataset with the data in Google Cloud Storage. See here:
def create_external_table(self, external_project_dataset_table, schema_fields, source_uris, source_format='CSV', autodetect=False, compressi...
Patch information in an existing table. It only updates fileds that are provided in the request object.
def patch_table(self, dataset_id, table_id, project_id=None, description=None, expiration_time=None, external_data_configuration=None, friendly_name=None, label...
Executes a BigQuery SQL query. Optionally persists results in a BigQuery table. See here:
def run_query(self, sql, destination_dataset_table=None, write_disposition='WRITE_EMPTY', allow_large_results=False, flatten_results=None, udf_config=None, use_legacy_sql=None, ...
Executes a BigQuery extract command to copy data from BigQuery to Google Cloud Storage. See here:
def run_extract( # noqa self, source_project_dataset_table, destination_cloud_storage_uris, compression='NONE', export_format='CSV', field_delimiter=',', print_header=True, labels=None): """ Executes a BigQu...
Executes a BigQuery copy command to copy data from one BigQuery table to another. See here:
def run_copy(self, source_project_dataset_tables, destination_project_dataset_table, write_disposition='WRITE_EMPTY', create_disposition='CREATE_IF_NEEDED', labels=None): """ Executes a BigQuery copy command to copy dat...
Executes a BigQuery load command to load data from Google Cloud Storage to BigQuery. See here:
def run_load(self, destination_project_dataset_table, source_uris, schema_fields=None, source_format='CSV', create_disposition='CREATE_IF_NEEDED', skip_leading_rows=0, write_disposition='WRITE_EMPTY', ...
Executes a BigQuery SQL query. See here:
def run_with_configuration(self, configuration): """ Executes a BigQuery SQL query. See here: https://cloud.google.com/bigquery/docs/reference/v2/jobs For more details about the configuration parameter. :param configuration: The configuration parameter maps directly to ...
Cancel all started queries that have not yet completed
def cancel_query(self): """ Cancel all started queries that have not yet completed """ jobs = self.service.jobs() if (self.running_job_id and not self.poll_job_complete(self.running_job_id)): self.log.info('Attempting to cancel job : %s, %s', self.proj...
Get the schema for a given datset. table. see https:// cloud. google. com/ bigquery/ docs/ reference/ v2/ tables#resource
def get_schema(self, dataset_id, table_id): """ Get the schema for a given datset.table. see https://cloud.google.com/bigquery/docs/reference/v2/tables#resource :param dataset_id: the dataset ID of the requested table :param table_id: the table ID of the requested table ...
Get the data of a given dataset. table and optionally with selected columns. see https:// cloud. google. com/ bigquery/ docs/ reference/ v2/ tabledata/ list
def get_tabledata(self, dataset_id, table_id, max_results=None, selected_fields=None, page_token=None, start_index=None): """ Get the data of a given dataset.table and optionally with selected columns. see https://cloud.google.com/bigquery/docs/referen...
Delete an existing table from the dataset ; If the table does not exist return an error unless ignore_if_missing is set to True.
def run_table_delete(self, deletion_dataset_table, ignore_if_missing=False): """ Delete an existing table from the dataset; If the table does not exist, return an error unless ignore_if_missing is set to True. :param deletion_dataset_table: A dotted ...
creates a new empty table in the dataset ; If the table already exists update the existing table. Since BigQuery does not natively allow table upserts this is not an atomic operation.
def run_table_upsert(self, dataset_id, table_resource, project_id=None): """ creates a new, empty table in the dataset; If the table already exists, update the existing table. Since BigQuery does not natively allow table upserts, this is not an atomic operation. :param d...
Grant authorized view access of a dataset to a view table. If this view has already been granted access to the dataset do nothing. This method is not atomic. Running it may clobber a simultaneous update.
def run_grant_dataset_view_access(self, source_dataset, view_dataset, view_table, source_project=None, view_project=None): ...
Create a new empty dataset: https:// cloud. google. com/ bigquery/ docs/ reference/ rest/ v2/ datasets/ insert
def create_empty_dataset(self, dataset_id="", project_id="", dataset_reference=None): """ Create a new empty dataset: https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/insert :param project_id: The name of the project where we want to create ...