Path: blob/master/BigQuery/bigqueryconnector.py
2973 views
from google.cloud import bigquery1from google.oauth2 import service_account2import pandas as pd3import logging456class BigQueryConnector:7def __init__(self, service_account_file, project_id):8self.service_account_file = service_account_file9self.project_id = project_id1011self.connection = self.get_connection()1213@property14def _logger(self):15return logging.getLogger(__name__)1617def get_connection(self):18try:19credentials = service_account.Credentials.from_service_account_file(self.service_account_file)20ctx = bigquery.Client(credentials=credentials, project=self.project_id)21self._logger.info("Connection established")22return ctx23except Exception as e:24self._logger.error(e)2526def execute_query(self, query):27try:28df = self.connection.query(query).to_dataframe()2930if not df.empty:31return df32else:33return True34except Exception as e:35self._logger.error(e)36return False3738def load_data_from_csv(self, dataset, table, csv_file):39df = pd.read_csv(csv_file)4041dataset_ref = self.connection.dataset(dataset)42table_ref = dataset_ref.table(table)4344self.connection.load_table_from_dataframe(df, table_ref).result()4546